Open source blockchain platforms enable developers to create decentralized applications (dApps) that provide solutions for various problems. Primarily a blockchain platform is built to transact with their peers anytime. It should have user identification labels that facilitate transactions among active users. Also, it must provide mechanisms for the verification of transactions and to stop transactions that cannot be verified.
Popular New Releases in Blockchain
bitcoin
Bitcoin Core 22.0
go-ethereum
Osun (v1.10.16)
lerna
v4.0.0
vnpy
2.9.0
openzeppelin-contracts
Popular Libraries in Blockchain
by bitcoin c++
63479 MIT
Bitcoin Core integration/staging tree
by ethereum go
35547 LGPL-3.0
Official Go implementation of the Ethereum protocol
by lerna javascript
31453 MIT
:dragon: A tool for managing JavaScript projects with multiple packages.
by ccxt javascript
24082 MIT
A JavaScript / Python / PHP cryptocurrency trading API with support for more than 100 bitcoin/altcoin exchanges
by vnpy python
17636 MIT
基于Python的开源量化交易平台开发框架
by OpenZeppelin javascript
17136 MIT
OpenZeppelin Contracts is a library for secure smart contract development.
by freqtrade python
17102 GPL-3.0
Free, open source crypto trading bot
by bitcoinbook python
16943 NOASSERTION
Mastering Bitcoin 2nd Edition - Programming the Open Blockchain
by less javascript
16769 Apache-2.0
Less. The dynamic stylesheet language.
Trending New libraries in Blockchain
by microsoft python
8313 MIT
Qlib is an AI-oriented quantitative investment platform, which aims to realize the potential, empower the research, and create the value of AI technologies in quantitative investment. With Qlib, you can easily try your ideas to create better Quant investment strategies. An increasing number of SOTA Quant research works/papers are released in Qlib.
by scaffold-eth css
6612 MIT
🏗 forkable Ethereum dev stack focused on fast product iterations
by chrisleekr javascript
3098 MIT
Automated Binance trading bot - Trade multiple cryptocurrencies. Buy low/sell high with Grid Trading. Integrated with TradingView technical analysis
by CyberPunkMetalHead python
2797 MIT
This is a fully functioning Binance trading bot that measures the volatility of every coin on Binance and places trades with the highest gaining coins If you like this project consider donating though the Brave browser to allow me to continuously improve the script.
by ethereum-boilerplate javascript
2329 MIT
The ultimate full-stack Ethereum Dapp Boilerplate which gives you maximum flexibility and speed. Feel free to fork and contribute. Although this repo is called "Ethereum Boilerplate" it works with any EVM system and even Solana support is coming soon! Happy BUIDL!👷♂️
by project-serum rust
1899 Apache-2.0
⚓ Solana Sealevel Framework
by getumbrel html
1659 NOASSERTION
A beautiful personal server OS for Raspberry Pi or any Linux distro for running self-hosted apps
by tharsis go
1619 LGPL-3.0
Ethermint is a scalable and interoperable Ethereum library, built on Proof-of-Stake with fast-finality using the Cosmos SDK.
by ava-labs go
1535 BSD-3-Clause
Go implementation of an Avalanche node.
Top Authors in Blockchain
1
74 Libraries
88690
2
59 Libraries
18548
3
58 Libraries
28117
4
55 Libraries
3641
5
47 Libraries
16661
6
44 Libraries
3058
7
37 Libraries
1236
8
37 Libraries
2735
9
35 Libraries
2353
10
34 Libraries
672
1
74 Libraries
88690
2
59 Libraries
18548
3
58 Libraries
28117
4
55 Libraries
3641
5
47 Libraries
16661
6
44 Libraries
3058
7
37 Libraries
1236
8
37 Libraries
2735
9
35 Libraries
2353
10
34 Libraries
672
Trending Kits in Blockchain
This is related to water treatment and purification.
DataViz Group
This helps with DaaViz
Cyber Data Analytics Group
This is for Cyber Data Analytics Group
zeronet group
this is zeronet group
Automation Group
this is part of Automation Group
Build an end-to-end automated trading application to visualize financial data of stock holdings. Buy/sell stocks automatically using Python trading bot libs.
The key functions of a stock trading bot built using the Python algorithmic trading libraries are getting the data, training the model, entering and exiting trades, placing orders, and getting notified. Through backtesting on historical data and by minimizing human intervention, a Python trading bot can increase the speed of order entry and establish discipline in the volatile stock market to help traders earn profits. Since computer systems react quickly to fluctuating markets, an automated Python-based trading system can produce bids as soon as the defined trading conditions are met.
Browse below to check out the latest and trending Python libraries to build your automated trading bot:
zipline
- Backtesting and algorithm development framework for trading strategies.
- Easily integrates with live trading platforms.
- Provides a range of built-in statistical and risk analysis tools.
ta-lib
- Offers over 150 technical analysis indicators.
- Widely used in financial markets for quantitative analysis.
- Supports multiple programming languages, including Python.
freqtrade
- High-frequency trading bot with a focus on cryptocurrencies.
- Supports machine learning and AI-based strategy development.
- Offers an active community and a range of pre-built strategies.
binance-trade-bot
- Designed specifically for trading on the Binance exchange.
- Supports various trading pairs and strategies.
- Offers real-time market data and order execution.
jesse
- Python-based framework for cryptocurrency trading strategies.
- Provides a simple and clean syntax for strategy development.
- Supports multiple exchanges and backtesting.
Crypto-Signal
- Cryptocurrency trading signals and alert system.
- Offers technical analysis indicators and custom signal creation.
- Integration with popular cryptocurrency exchanges.
Binance-volatility-trading-bot
- Designed for volatility-based trading strategies on Binance.
- Focuses on profiting from price fluctuations.
- Offers various trading parameters for customization.
binance-trader
- A simple and lightweight Binance trading bot.
- Supports spot and futures trading on the Binance platform.
- Suitable for both beginners and experienced traders.
OctoBot
- Modular and extensible cryptocurrency trading bot.
- Provides a web-based dashboard for monitoring and configuration.
- Supports various technical analysis indicators.
cointrol
- Open-source cryptocurrency trading bot with a focus on Bitcoin.
- Supports multiple exchanges and customizable strategies.
- Offers risk management and trading performance analysis.
Cryptocurrency-Trading-Bots-Python-Beginner-Advance
- A collection of Python trading bot examples for all skill levels.
- Educational resource with various trading strategies.
- Suitable for beginners and experienced traders.
algobot
- Algorithmic trading bot framework with a range of features.
- Supports backtesting, live trading, and data analysis.
- Integrates with various data sources and brokers.
binance-tutorials
- Educational resources and tutorials for Binance trading.
- Covers various aspects of trading on the Binance platform.
- Suitable for traders looking to learn and improve their skills.
pybacktest
- A Python library for backtesting trading strategies.
- Supports historical price data analysis and strategy optimization.
- Provides visualizations for performance analysis.
crypto-trader
- A simple cryptocurrency trading bot for Bitcoin.
- Designed for automated trading on various exchanges.
- Offers basic trading strategies.
stock-trading-ml
- Machine learning-based stock trading bot.
- Uses historical stock data for predictive trading.
- Suitable for those interested in AI-driven trading.
tradingview-webhooks-bot
- A bot that uses TradingView webhooks for automated trading.
- Integrates with TradingView alerts to trigger trades.
- Suitable for traders using TradingView for technical analysis.
crypto-arbitrage
- Focuses on cryptocurrency arbitrage trading strategies.
- Aims to profit from price differences on different exchanges.
- Supports multiple cryptocurrency pairs.
TensorFlow-Bitcoin-Robot
- Utilizes TensorFlow for machine learning-based Bitcoin trading.
- Provides tools for developing and training trading models.
- Suitable for those with machine learning expertise.
pyjuque
- Cryptocurrency trading bot framework with a focus on flexibility.
- Supports custom strategies and risk management.
- Designed for traders with coding experience.
Titan
- Algorithmic trading bot for various asset classes, including cryptocurrencies.
- Offers machine learning capabilities and strategy customization.
- Designed for both beginners and experienced traders.
PyTrendFollow
- A trend-following trading bot framework.
- Focuses on capturing trends in various financial markets.
- Supports strategy development and live trading.
Bitcoin-Surge-Trading-Alpha
- A cryptocurrency trading bot with a focus on capturing surges in Bitcoin prices.
- Designed for short-term trading strategies.
- Offers features for risk management and portfolio tracking.
pytrader
- A simple and lightweight cryptocurrency trading bot.
- Supports multiple exchanges and basic trading strategies.
- Suitable for beginners and traders looking for a minimalistic approach.
FAQ
1. How to choose a Python trading bot library for backtesting and live trading?
When choosing a Python trading bot library, consider:-
1. versatility in strategy development,
2. access to historical and real-time data, and
3. support for various order types.
Seek libraries with intuitive APIs, risk controls, and exchange compatibility. Also, a vibrant community and regular updates are essential for long-term reliability.
2. Can Python trading bot libraries handle multiple trading pairs?
Python trading bot libraries are typically flexible and can handle multiple trading pairs. These libraries adapt to diverse markets, including cryptocurrencies, traditional stocks, and more.
3. How do Python trading bot libraries handle risk management to protect investments?
Risk management is paramount in Python trading bot libraries. Traders can apply stop-loss, position sizing, and risk controls to protect investments. Users can set preset loss limits, reducing the impact of market downturns.
4. What tools do Python trading bot libraries provide for performance analysis?
Python trading bot libraries provide tools for strategy optimization and performance analysis. Traders can backtest their strategies using historical data to fine-tune their algorithms. Performance metrics and visualization tools help assess strategy effectiveness and make informed adjustments.
5. Can Python trading bot libraries run on cloud servers or require infrastructure?
Python trading bot libraries can be deployed on cloud servers, eliminating hardware needs. This cloud-based approach offers scalability, cost-efficiency, and accessibility for users. Thus making it an attractive option for both beginners and experienced traders.
Over the past few years, we’ve witnessed a significant rise in the usage of algorithmic trading bots, especially by sophisticated institutions.
These bots follow a set of predefined rules and place and place trades to generate high-frequency profits in the stock market. However, the cryptocurrency market is still nascent, and yet algorithmic trading is now accessible to all retail and individual traders alike. Many of these trading bots are developed using Java libraries. Here are some of the best Java algorithmic trading libraries. Released under the Apache license, Coin Trader is a Java-based backend for trading cryptocurrencies. It is connected to many crypto exchanges and offers various features, including but not limited to simulated crypto trading live order execution, 24-hour OHLC bars, and backorder routing.
Knowm’s XChange offers a simple and consistent API connecting more than 60 crypto exchanges with modular components which are under active development. Another one, ta4j, is an open-source, 100% pure Java library with 130+ indicators essential to technical analysis. It comes equipped with basic components which are necessary for creating, testing, and executing a range of trading strategies. Developers tend to use some of the following trending open-source libraries:
XChange
- Provides a consistent API for interacting with various cryptocurrency exchanges.
- Cryptocurrency exchanges can access market data, place orders, and manage accounts.
- Supports various cryptocurrency exchanges like Coinbase Pro, Bitstamp, Binance, and Kraken.
ta4j
- Provides tools for performing technical analysis on financial data.
- Helps build and test trading methods in Java.
- Helps you create and test trading methods that use technical analysis indicators.
Used-Trading-Platform
- Is a Java library used for Object-Relational Mapping, Utilities, and Spring applications.
- Allows developers to integrate trading functionalities into their applications.
- Supports the development of custom indicators and trading methods.
bateman
- Designed to facilitate the development and execution of algorithmic trading methods.
- Provides various functions for strategy development, live trading, data analysis, and backtesting.
- Helps automate trading decisions based on predefined rules and market indicators.
tsharding
- Used by algorithmic trading firms, individual developers, and quantitative traders.
- Helps connect their trading algorithms directly to their brokerage accounts.
- Provides unified API to access many cryptocurrency exchanges.
bxbot
- Makes algorithmic trading bots easier to develop with new features.
- Users could implement and customize their trading methods using the provided framework.
- Fetches real-time market data, enabling trading decisions based on the latest information.
CoinExchange_CryptoExchange_Java
- Provides a simple and easy-to-use interface for strategy development.
- Allows users to develop and test trading algorithms on historical data.
- Helps connect their trading algorithms directly to their brokerage accounts.
univocity-trader
- Helps create and test trading strategies using past and current market information.
- Test their trading methods on past data to see how well they performed.
- Helps implement risk management rules to control position sizing and risk exposure.
parity
- Designed to facilitate the development of high-performance, ultra-fast trading applications for financial markets.
- Can handle market data feeds, manage risks, execute orders, and handle financial instruments.
- Provides functions for order submission, modification, cancellation, and tracking.
Axon-trader
- Helps build event-driven, Command Query Responsibility Segregation applications.
- Helps build scalable and maintainable applications.
- Can save and find an application's status using a sequence of events.
cointrader
- Is a Java-based backend for algorithmically trading cryptocurrencies.
- Provides data collection and export, complex event processing, triggering, and backtesting.
- Enables developers to integrate cryptocurrency trading functionality into their applications.
trading-backtest
- Helps in backtesting and live trading of financial strategies.
- Offers extensive features for strategy development and optimization.
- Provides built-in backtesting capabilities for their supported trading strategies.
binance-trader
- A flexible and feature-rich library for backtesting and live trading of financial strategies.
- Provides a simple and easy-to-use interface for strategy development.
- Allows you to develop and test trading algorithms on historical data.
xmarket
- Includes functions for pricing and risk management of financial instruments.
- Support for automated trading strategies, connectivity to various exchanges, and risk management.
- Helps connect their trading algorithms directly to their brokerage accounts.
philadelphia
- Designed to facilitate the development and execution of algorithmic trading strategies.
- Offers functions for strategy development, live trading, backtesting, and data analysis.
- Helps automate trading decisions based on predefined rules and market indicators.
FAQ
What is backtesting and paper trading, and how can they be used for algorithmic trading with Java?
Backtesting and paper trading are essential components of algorithmic trading. Before trading, traders and developers can improve their methods by reviewing them. Backtesting is when you test a trading strategy on old market data to see how it would have worked before. Paper trading is a practice where traders execute trades without using real money.
Which Python libraries are commonly used for algorithmic trading?
Python is a popular programming language for algorithmic trading. It's simple, flexible, and has many libraries. Here are some popular Python libraries frequently used for algorithmic trading:
- Backtrader
- Zipline
- QuantConnect
- PyAlgoTrade
- CCXT
- TA-Lib
- pandas
- NumPy and SciPy
- TensorFlow and PyTorch
- vn.py
- AlgoTrader
- Lean Algorithm Framework
How does the engine work in an algorithmic trading system?
The trading system's engine executes trading methods, processes orders, and manages trades. It is a critical part of the overall system architecture. It directly interacts with the markets. It ensures that trading methods are executed efficiently and accurately. The trading engine has two parts. These parts are the Order Management System and the Execution Management System.
Here is how the engine works in an algorithmic trading system:
- Strategy Execution
- Order Management System
- Risk Management
- Execution Management System
- Order Routing and Matching
- Real-time Monitoring
- Record Keeping
Are there any advantages to using automated trading bots over manual trades?
Automated trading bots and manual trading each have their benefits. Automated trading bots have pros and cons compared to manual trades.
Advantages:
- Speed and Efficiency – Bots can execute trades in milliseconds. This can be crucial in high-frequency trading, where quick reactions are needed.
- Consistency – Bots follow predefined rules without emotions. It avoids the impact of human biases and erratic decision-making.
- Backtesting & Optimization – Bots can improve their strategies by testing with old data. This helps identify potential issues before deploying them in live trading.
- Diversification – Bots can manage many strategies and trading pairs simultaneously, providing diversification benefits.
- Algorithm Complexity – Bots can handle complex strategies with many indicators and conditions. Manual traders may find this challenging.
Are there any open-source solutions for developing an algorithmic trading library using Java?
You can use Java to create an algorithm trading library with open source solutions. Java is a popular programming language for making trading applications. It's fast, flexible, and has many useful libraries. Here are a few open source options to consider:
- QuantConnect Lean
- AlgoTrader
- Tradelink
- QuickFIX/J
- XChange
Which electronic products are suitable for algorithmic traders using Java libraries for trading?
Java library users can apply their strategies to various electronic trading products. Traders choose products based on knowledge, goals, risk tolerance, and library capabilities. These products are traded electronically using Java libraries and algorithmic strategies.
- Equities and Stocks
- Futures and Options
- Foreign Exchange (Forex)
- Cryptocurrencies
- Fixed Income
- Commodities
- Exchange-Traded Funds (ETFs)
- Spread Betting and Contracts for Difference (CPDs)
- Index Funds and ETF Rebalancing
- Algorithmic Market-Making
If traders help trading algorithms, where can they find financial information?
Alternative financial data can provide valuable insights for algorithmic trading strategies. If you use a Java library for trading, you can find data sources to help with decisions.
- News APIs and Feeds
- Bloomberg API
- Reuters Connect API
- Alpha Vantage API
- Financial News Websites
- Social Media Platforms
- Event Calendars
- Government and Regulatory Websites
- Specialized News Providers
- Web Scraping
- Natural Language Processing
- Data Vendors
- Financial Data Platforms
Develop a Python trading app with Data Collection, Technical Analysis, Plotting, Machine Learning, NLP, and more using algorithmic trading libraries.
The crucial aspect is to train your applications to evaluate trading ideas and map out historical data by sourcing data and information from diverse sources. These can include spreadsheets, CSVs, and online platforms like Yahoo Finance, Google Finance, etc. Moreover, you can easily forecast live trading prices with the help of artificial neural networks and trading algorithms built using Python trading packages and algorithmic libraries. With the Python trading code, you can enable functions like aggregations, sorting, and visualization of complex data with just one or two commands.
Check out some of the top and most widely used open-source algorithmic trading libraries that provide code packages in Python to developers:
pyalgotrade
- It offers a simple and easy-to-use framework for developing trading strategies.
- It makes it accessible for both beginners and experienced developers.
- It has an active community, and its documentation is comprehensive.
zipline
- It is crucial for developing and testing trading strategies.
- It provides a realistic simulation environment for backtesting strategies using historical market data.
- It offers event-driven backtesting, transaction cost modeling, and performance analytics.
ta-lib
- It is a Python library used in Websites, Business, and Bitcoin applications.
- Integrating ta-lib into trading algorithms allows for the creation of more sophisticated strategies.
- It will help identify potential entry and exit points in the market.
freqtrade
- It is an open-source cryptocurrency trading bot written in Python.
- Its importance in Python algorithmic trading libraries lies in its features and flexibility.
- It supports many cryptocurrency exchanges, enabling users to trade on different platforms.
qlib
- It is a Python library designed for quantitative finance and algorithmic trading.
- It offers efficient data management tools, including data downloading, preprocessing, and feature engineering.
- It simplifies the process of developing and testing trading strategies.
abu
- It is a Python library used in Blockchain and cryptocurrency applications.
- It has no bugs or vulnerabilities, a Strong Copyleft License, and medium support.
- You can install it using 'pip install abu' or download it from GitHub or PyPI.
backtrader
- It is a popular Python library for developing and testing algorithmic trading strategies.
- It is flexible, allowing users to install and test various trading strategies.
- It is a valuable tool for both developing and deploying trading strategies.
trump2cash
- It is a Python library used in Analytics and predictive Analytics applications.
- It has no bugs or vulnerabilities and has built files available.
- It is a stock trading bot powered by Trump tweets.
binance-trade-bot
- It plays a crucial role in automating trading strategies. It is done on the Binance cryptocurrency exchange.
- It often includes features for backtesting trading strategies.
- These are often customizable. This allows traders to tailor strategies to their specific preferences and risk tolerance.
rqalpha
- It offers a framework for developing and testing trading strategies.
- It is open source, allowing developers to inspect and change the source code.
- It makes it accessible for both beginners and experienced users.
tensortrade
- It helps in building and researching algorithmic trading strategies. We can do this by using deep reinforcement learning.
- It benefits from contributions and feedback from a community of developers and researchers.
- It helps in adapting to different trading scenarios and experimenting with various models.
python-binance
- It is a Python wrapper for the Binance API.
- It makes it easier to interact with the Binance cryptocurrency exchange.
- It supports WebSocket streams, providing real-time updates on market events.
Crypto-Signal
- It plays a crucial role in Python algorithmic trading libraries.
- It provides key insights and triggers for automated trading decisions.
- It can include risk management parameters. We can help algorithms adjust position sizes or exit trades to manage risk.
finmarketpy
- It is a Python library designed for financial market analysis and algorithmic trading.
- It includes a wide range of technical analysis tools and indicators.
- It supports event-driven backtesting.
mlfinLab
- It focuses on machine learning applications in finance and algorithmic trading.
- It provides tools for effective feature engineering, a crucial aspect of financial ML.
- It includes functionalities for fractional differentiation.
tqsdk-python
- It is a Python SDK (Software Development Kit) designed for quantitative trading.
- It aims to provide an interface for algorithmic trading. We can do it by making it accessible for beginners and experienced developers.
- A vibrant community and active support can enhance the development experience.
catalyst
- It plays a crucial role as it acts as a framework. That facilitates the development, testing, and execution of trading strategies.
- It offers a structured environment for designing and implementing trading strategies.
- Effective risk management is a crucial aspect of algorithmic trading.
clairvoyant
- It is a Python library used in websites and business applications.
- Backtest your model for accuracy and simulate investment portfolio performance.
- It is Software designed to identify and check trading strategies.
quant-trading
- Quantitative trading, or quant-trading, is essential in algorithmic trading.
- Python's extensive libraries, such as Pandas and NumPy. It is easing efficient data analysis and manipulation.
- It helps in backtesting trading strategies.
eiten
- It is a Python library used in websites and portfolio applications.
- Backtesting module that both backtests and forward tests all portfolios.
- It is used as a statistical and algorithmic investing strategy.
zvt
- Zero-cost virtual trading (ZVT) in Python algorithmic trading libraries.
- Need for testing and refining trading strategies without risking real capital.
- It allows developers to simulate trades in a realistic market environment.
backtesting.py
- It is used in algorithmic trading to evaluate the performance of trading strategies.
- It helps assess the effectiveness of a trading strategy. We can do so by applying it to historical market data.
- Calculates and presents various performance metrics to quantify the strategy's performance.
binance-trader
- It provides a Python API for interacting with Binance.
- It allows traders to access market data, execute trades, and manage their accounts.
- It helps in tracking and managing portfolios.
pytrader
- It is a library related to trading or finance.
- Its importance would likely be tied to its features and functionalities.
- It helps in cryptocurrency trading robots.
High-frequency-Trading-Model-with-IB
- It helps traders to execute orders at high speeds.
- It takes advantage of small price discrepancies in the market.
- It will provide access to real-time market data and quick order execution.
qstrader
- It offers a framework for developing and testing quantitative trading strategies.
- It allows users to define and install custom trading strategies.
- It offers flexibility for a wide range of trading styles and preferences.
pyrh
- It could enable users to automate trading strategies. We can do so by interacting with the Robinhood platform.
- The framework could ease the retrieval and analysis of financial data from Robinhood. We can do it with informed decision-making.
- It may allow integration with other Python libraries and tools.
coinbasepro-python
- It is often called coinbasepro-python, a Python client for the Coinbase Pro API.
- It supports the placement and management of orders on the Coinbase Pro platform.
- Developers can customize and adapt the library to suit their specific trading strategies.
bulbea
- It is a Python library in Artificial Intelligence, Machine Learning, and DL apps.
- It has a Non-SPDX License. You can download it from GitHub.
- It is a Deep Learning-based Python Library for Stock Market Prediction and Modelling.
thetagang
- It is a Python library used in Automation and bot applications.
- It is an IBKR trading bot. It helps collect premiums by selling options using the "The Wheel" strategy.
- It implements a modified version of The Wheel with my tweaks.
ib_insync
- It is a Python library designed for algorithmic trading with IB TWS and IB Gateway.
- It allows for asynchronous programming, enabling you to handle many tasks.
- It uses an event-driven programming model.
RLTrader
- It plays a crucial role in Python algorithmic trading libraries.
- It leverages reinforcement learning techniques to make trading decisions.
- It can optimize decision-making processes and manage risk.
cointrol
- It is crucial in algorithmic trading to manage risk.
- It ensures orderly execution and adapts to market conditions.
- Real-time monitoring allows algorithms to react to changing market conditions.
deep_trader
- It is a Python library used in Institutions, Learning, Education, AI, ML, Nodejs, and Unity apps.
- It uses reinforcement learning on the stock market, and the agent tries to learn trading.
- It has no bugs, it has no vulnerabilities, it has built files available, and it has medium support.
qtpylib
- It is a Python library that provides tools for algorithmic trading.
- It is built on the popular open-source algorithmic trading library Quantlib.
- It helps be flexible and allows traders to customize and adapt the library.
surpriver
- It helps in Artificial Intelligence, Machine Learning, and Deep Learning applications.
- It helps find big moving stocks before they move using a machine.
- It generates price and volume return features and plenty of technical indicators.
AIAlpha
- It enables the development of more sophisticated trading strategies.
- It leverages advanced machine-learning techniques to analyze vast amounts of financial data.
- It allows algorithms to adapt to changing market conditions.
IbPy
- IbPy, or Interactive Brokers Python API, is important in algorithmic trading libraries.
- It provides a Python interface to interact with the Interactive Brokers trading platform.
- It allows developers to install automated trading strategies using Python.
personae
- Personae in Python algorithm trading libraries refer to predefined sets of characteristics.
- It is assigned to different types of market participants or trading strategies.
- It can model diverse market scenarios and participant behaviors.
hummingbot
- It plays a significant role in Python algorithmic trading libraries.
- It supports various cryptocurrency exchanges. It enables traders to connect to many markets.
- It provides liquidity in the cryptocurrency markets.
FAQ
1. What is algorithmic trading?
Algorithmic trading involves using computer algorithms. It automates the process of buying or selling financial instruments in the market. It aims to execute trading strategies with speed and efficiency.
2. Why use Python for algorithmic trading?
It is a popular programming language. It helps in algorithmic trading. It is because of its simplicity, extensive libraries, and large community. It provides tools like NumPy, pandas, and scikit-learn. Those tools help in data analysis and machine learning.
3. Which Python libraries do we use for algorithmic trading?
Commonly used libraries include:
- Backtrader: A versatile backtesting and live trading framework.
- Zipline: A powerful library for backtesting trading strategies.
- ccxt: A cryptocurrency trading library supporting many exchanges.
- pandas: Useful for data manipulation and analysis.
- NumPy: Essential for numerical operations.
4. What is backtesting?
It is the process of testing a trading strategy. We can do so using historical data to assess its performance. It helps traders test how a strategy would have performed in the past.
5. How do I install these libraries?
You can install these libraries using the pip package manager.
For example, pip install backtrader.
You can use JavaScript trading libraries to access financial market data. You can use these libraries to test strategies. You can also trade live and analyze data from different platforms.
JavaScript is a programming language commonly used to create interactive features on websites and can also be used to build algorithmic trading systems. In algorithmic trading, deals are automatically executed by computers based on pre-established rules and circumstances.
You would need a solid command of JavaScript and familiarity with terms like variables, functions, loops, and data structures to construct an algorithmic trading system in the language. You would also need to know how to transmit orders to a brokerage or trading platform and how to retrieve and evaluate financial data like stock prices and trade volumes.
To create an algorithmic trading system in JavaScript, consider these steps:
- Choose the trading approach you want to use.
- Create a set of criteria and guidelines that will use to execute trades automatically.
- Obtain financial information from a database or stock market, for example.
- Apply JavaScript to the data analysis.
- To automatically execute transactions, join a trading platform or brokerage.
For creating algorithmic trading systems, several JavaScript libraries can be helpful. A few choices are "ccxt": with the help of this library, you may access a variety of cryptocurrency exchanges, extract and analyze their data, and execute trades automatically. Both the REST and WebSocket APIs are supported; “gecko”; “binance-trading-bot”; “superalgos”; “crypto-trading-bot”; and more.
Check out the below list to find the best JavaScript algorithmic trading libraries for your application development:
ccxt
- This library is open source and lets you interact with different cryptocurrency exchanges.
- The goal is to make accessing and trading on different cryptocurrency exchanges easier. Providing a consistent API for various platforms does this.
- Developers can create programs to analyze data and communicate with cryptocurrency exchanges.
gekko
- It is an open source cryptocurrency trading bot and backtesting platform.
- Traders and developers can use it to make and test plans for cryptocurrency markets.
- Gekko is more centered around algorithmic trading strategies and historical data analysis.
binance-trading-bot
- Supports various buy/sell orders based on the configuration.
- Can monitor multiple symbols. We will monitor all symbols per second.
- It uses MongoDB to provide a persistent database. But it doesn't use the latest MongoDB to support the newer Raspberry versions.
Superalgos
- It is a project that is open to the public. It helps with trading and analyzing cryptocurrency.
- This tool helps traders and developers test strategies on various crypto exchanges.
- Offers a platform to design, test, and execute algorithmic trading strategies.
crypto-trading-bot
- It offers basic buy and sell signals and offers many things to be profitable.
- Users can create trading strategies using blocks in the software's visual interface.
- Use blocks to make trading strategies with conditions, actions, indicators, and triggers.
technicalindicators
- This is a JavaScript library. It's open-source and offers many commonly used technical indicators. Analysts use these indicators to analyze financial markets.
- This tool helps developers and traders analyze indicators to make better trading decisions.
- You can use it to create trading bots, charting apps, and other tools for technical analysis.
cryptocurrency-arbitrage
- You can use it to create trading bots, test strategies, and analyze financial market data.
- It is flexible and customizable so you can create complex trading algorithms with it.
- Supports various asset classes and offers automated trading, strategy optimization, and risk management.
node-binance-trader
- It creates custom indicators and strategies for the TradingView charting platform.
- Supports various asset classes and offers risk management, strategy optimization, and automated trading.
- The flexibility and customizability make it capable of creating complex trading algorithms.
algotrader
- Users on this platform can trade stocks, forex, cryptocurrencies, futures, and options.
- Traders can use a strong testing tool to analyze their strategies on past data. This helps them refine trading rules and improve performance.
- It offers real-time execution of trading strategies across multiple markets and exchanges.
crypto-exchanges-gateway
- You can focus on important tasks because the client side handles authentication.
- Offers a unified REST API to various exchanges and can automate trading or build bots.
- Offers WS access for real-time data and a basic UI that implements most API calls.
btcrobot
- The purpose of its creation was to trade cryptocurrencies automatically, focusing on Bitcoin.
- The tool is advertised to users as a way to make money from cryptocurrency price changes.
- The company used algorithms to find trading chances and make trades for users.
node-steam-tradeoffer-manager
- It is a JavaScript library used for working with trade offers in Steam.
- Allows developers to interact with trade offers programmatically
- It can help make trading bots, manage items, and automate trading on Steam.
gekkoga
- It is an open source platform to automate trading strategies over bitcoin markets.
- In a genetic algorithm, we use Gekko to optimize trading strategies.
- Define your trading strategy, and Gekko will take care of everything else.
automated-trading
- Traders use algorithms and computer programs to make trades, following specific rules automatically.
- Developing trading platforms is a central aspect of automated trading.
- Automated trading systems analyze past and current market data to find trading opportunities.
bitimulate
- Traders can practice their strategies in a simulated environment with past price data.
- To see how well your strategies have worked in the past, you can run them using historical data.
- Allows users to execute simulated trades in real time without using real funds.
jiji2
- Our goal is to provide a platform for algorithmic trading. You can trade and create solutions here.
- Supports various order types like limit, stop, and market, allowing sophisticated trading strategies.
- Provides various functions to build, test, and execute trading strategies.
real-time-charts
- It offers various indicators, candlestick analysis functions, and patterns.
- Offers a comprehensive collection of technical indicators commonly used in technical analysis.
- You can easily calculate and use these indicators in trading strategies.
bitprophet
- The trading platform for Binance uses chatbots as its interface.
- Its main purpose is the automation of trading techniques.
- You can use it to track orders or get alerts for popular technical indicators.
react-trading-ui
- You can use this free trading bot framework with many exchanges and trading pairs.
- The platform has a visual interface for creating strategies and includes technical indicators.
- It is extensible and allows users to implement custom strategies using technical indicators.
FAQ
1. Can I use a JavaScript library for basic stock and option trading algorithms?
Follow these steps to use a JavaScript library for basic stock and option trading. Here is a high-level overview of the process:
Choose a JavaScript library: Select a suitable JavaScript library for algorithmic trading. It can provide tools to access stock and option trading data and execute trades.
Market Data Access: You can get stock and option prices from the library for up-to-date market info. Many libraries offer APIs that allow you to fetch this data.
Strategy Development:
- Design and code your training strategy in JavaScript.
- Use indicators and averages like technical indicators to decide when to buy or sell.
- Ensure your strategy has clear entry and exit conditions.
Backtesting: Use historical market data to backtest your strategy. You can use past data to simulate trades and see how well your strategy would have done.
Risk Management: Implement risk management methods in your algorithm. To reduce losses, you can do three things:
- Set stop-loss levels.
- Diversify your investments.
- Adjust the size of your positions.
Order Execution: To follow your plan, use the library's API to carry out the orders you get. It involves placing market or limit orders to buy or sell stocks and options.
Monitoring and Logging: Set up systems to track how well your algorithm is doing. It can help you identify issues and fine-tune your strategy.
Paper Trading: Try paper trading your algorithm before using it in a real environment. It helps simulate trades in real time without using real funds. It helps validate your strategy's effectiveness in a risk-free environment.
Live Trading: When you are confident in how well your strategy works, you can use it for live trading. Be cautious and start with a small amount of capital to mitigate potential risks.
Continuous Optimization: Continuously monitor and optimize your algorithmic trading strategy.
2. What is the best way to deploy crypto bots using Javascript libraries?
To use crypto trading bots safely, follow these steps using JavaScript libraries. This will improve performance and security. Here is a general guide to help you get started:
Choose a Trading Library: Select a suitable JavaScript library for your bot. It integrates with the exchange you want to trade on.
Strategy Development & Testing: Develop and test your strategy using historical data and backtesting. Ensure that your strategy is well-defined and meets your trading goals.
Setting Up a Development Environment: Install Node JS and clone or Install libraries.
Configuration: Configure exchange APIs and strategy.
Backtesting and Simulation: Use backtesting to evaluate the historical performance of your strategy. Ensure your strategy aligns with your expectations before moving to live trading.
Paper Trading: It simulates trading in a risk-free environment with fake funds. It helps validate your strategy's effectiveness without using real money.
Monitoring & Logging: Create a system to record and log trades, performance, and mistakes. It will help you analyze your bot's behavior.
Server and Infrastructure: Choose to host and configure the server.
Security: Protect API keys. Set up the server's firewall and access controls to keep your bot safe.
Deployment: Deploy your bot's code in the server and run in the deployment.
Continuous Monitoring: To ensure your bot works well, observe how it acts and track what it does. Setting up mechanisms to handle errors and expectations gracefully.
Scaling: Optimize your performance and multi-instance.
3. How can I use Javascript libraries to get market data for my trading models?
If you want to add market data to your trading models, you can use JavaScript libraries. These libraries will help you connect with exchange APIs or data providers. Here is a general guide on how to do so:
Choose an exchange or data provider: Select an exchange or data provider. This will allow you to obtain market data for cryptocurrencies.
Obtain API keys: Sign up for an account on the chosen exchange and obtain API keys. It would help to have API keys to authenticate your requests and access market data.
Understand API Documentation: To understand the API documentation, read about the exchange's API. The information includes the endpoints, authentication methods, response formats, and request parameters.
Make HTTP Requests: Use these to send HTTP requests to the exchange's API endpoints. Construct the requests according to the documentation.
Authentication: To verify your requests, include your API keys or parameters.
Retrieve Market data: Volume, historical candlestick, price, and order book data. Different endpoints will offer different types of data.
Handle Responses: Handle the responses from the API requests. Extract the important data from the JSON responses for your trading model.
Data processing: Once you have the data, you can preprocess and format it as needed for your algorithm.
Real-Time data: Use the exchange's WebSocket connections to get current trading data. WebSocket connections can stream live market data directly to your application.
Data frequency: To carry out your plan, you may need certain information at various times. This includes current data, records, and brief intervals. Ensure the data you are collecting matches your strategy's requirements.
Rate limits: Attention to the API's rate limits and usage policies. Exceeding rate limits can result in temporary bans or limitations on your API access.
Error Handling: Implement error handling to handle API request failures or unexpected data.
4. Does Interactive Brokers API integrate well with the algorithms created by these Libraries?
Integrating the Interactive Brokers API with JavaScript libraries can be challenging. Interactive Brokers' APIs are mainly made for Python, Java, and C++. Using Interactive Brokers' API with JavaScript apps can be more complicated. It may require more work than using officially supported languages.
5. What are the best tools that JavaScript Algorithmic Trading Libraries offer?
JavaScript trading libraries help traders and developers create, test and use trading strategies. Here are some of the most useful tools commonly provided by these libraries:
Market data access: It offers functions to fetch real-time and historical market data. This data helps develop and test trading strategies.
Technical Indicators: It includes various built-in technical indicators. It helps traders analyze price trends and make informed decisions.
Strategy development: It offers tools to define and test trading strategies. You can make your own strategies using price patterns and technical indicators.
Backtesting: It tests your trading strategies using historical market data. Before applying your strategies in a real situation, assessing how well they work is good.
Paper trading: It helps practice trading strategies using virtual money. It is a safe way to test your strategies in real time without risking real money.
Live trading: It offers APIs to execute trades on live exchanges. It is crucial to automate the execution of your strategies in real-time.
Risk management: To manage risks, strategies include adjusting and diversifying investments. It also includes setting stop-loss and take-profit levels.
Order execution: You can use order execution to place different orders. This includes limit and market orders. It offers functions to cancel or modify orders.
Real-time data streaming: It allows you to react to changes in the market quickly.
Performance metrics: You can measure how well your strategies are working. These tools analyze metrics like drawdown, profitability, and risk-adjusted returns. They calculate and measure them.
Visualization: You can make charts and graphs to see how your trading strategy is doing.
Configuration & customization: Customize your trading by adjusting strategies and indicators. It matches your preferences. This helps you fine-tune parameters and settings.
Logging and reporting: It helps you keep track of executed errors, trades, and other events. It is valuable for troubleshooting and performance analysis.
Community and support: You can ask for help, learn from others, and share ideas.
Python is an easy-to-learn coding language that offers simplicity to Bitcoin programming thanks to its free packages, a wide code library, and software tools.
Experts say that using Python blockchains can be coded in under 50 lines of code, and even complex algorithms can be coded with lesser code. Python is used extensively by developers, due to which you'll find plenty of support in the community. It is considered to be an excellent choice for Bitcoin mining. Developers can create powerful APIs by relying on built-in modules and standard libraries. Moreover, Python-based bitcoin can seamlessly integrate Machine Learning, Data Analysis, and arithmetic tools, to make it a more wholesome technology.
Our list will give you Python Bitcoin components that will help you build Bitcoin wallets, mining & trading software, and more for your Bitcoin apps. Torba, a new wallet library, helps scale up your Bitcoin project by enabling developers to build wallets efficiently at a fast speed. Cointrol is an advanced crypto trading bot that facilitates auto Bitcoin speculation based on price change triggers and different trading strategies. It also offers live updating of your Bitstamp dashboard, where you can view all your orders and transactions in real-time. P2Pool is a decentralized Bitcoin mining pool that functions by forming a peer-to-peer chain of miner nodes. Contrary to usual mining pools, P2Pool secures your Bitcoin against 51% of disruptive attacks, minimizing double-spending instances.
freqtrade
- Freqtrade is an open-source cryptocurrency trading bot that allows users to automate.
- Traders can backtest their strategies using historical market data to evaluate.
- The platform includes features for risk management, including stop-loss and take-profit orders.
electrum
- Electrum is a popular and widely used open-source Bitcoin wallet.
- It's known for its simplicity, speed, and security features.
- Electrum is user-friendly and straightforward.
jesse
- jesse is a Python library typically used in Blockchain, Cryptocurrency, and Bitcoin applications.
- jesse has no bugs or vulnerabilities.
- you can install using 'npm i jesse' or download it from GitHub, npm.
alpha_vantage
- Alpha Vantage is a financial data provider that offers a suite of APIs for accessing it.
- These APIs cover a wide range of financial instruments, including stocks, cryptocurrencies, etc.
- It includes stocks, exchange-traded funds (ETFs), cryptocurrencies, and forex pairs.
Crypto-Signal
- Crypto-Signal is a Python library used in Financial Services, Fintech, Blockchain, and Cryptocurrency.
- Crypto-Signal has no bugs, it has no vulnerabilities.
- Crypto-Signal has a medium active ecosystem.
torba
- torba is a Python library typically used in Blockchain, Cryptocurrency, Bitcoin applications.
- torba has no bugs or vulnerabilities.
- you can install using 'pip install torba' or download it from GitHub, PyPI.
bitcoin-arbitrage
- Bitcoin arbitrage refers to the practice of exploiting price imbalances for Bitcoin.
- The goal of arbitrage is to take advantage of price differences to make a profit with minimal risk.
- On one exchange they buy Bitcoin at a lower price. Then they sell it at a higher price on another exchange.
binance-trader
- binance-trader is a Python library typically used in Blockchain, Cryptocurrency, Bitcoin applications.
- binance-trader has no bugs, it has no vulnerabilities.
- binance-trader has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
raspiblitz
- RaspiBlitz is an open-source project that allows individuals to turn a Raspberry Pi.
- RaspiBlitz allows users to run a full Bitcoin node. This means they maintain a blockchain.
- This helps contribute to the decentralization and resilience of the Bitcoin network.
coinbasepro-python
- coinbasepro-python is a Python library typically used in Financial Services, Fintech, Blockchain, Cryptocurrency.
- coinbasepro-python has no bugs, it has no vulnerabilities.
- You can install using 'pip install coinbasepro-python' or download it from GitHub, PyPI.
rotki
- Rotki is a portfolio tracking, accounting, and tax reporting tool designed for cryptocurrency.
- It is an open-source platform that aims to help individuals manage their cryptocurrency.
- Rotki supports multiple platforms and exchanges.
OctoBot
- OctoBot is an open-source cryptocurrency trading bot platform.
- It provides a framework to develop and execute trading strategies in the cryptocurrency.
- This flexibility helps users to tailor the bot to their specific trading preferences.
tinychain
- TinyChain might be the name of a specific blockchain project, platform, or technology.
- tinychain is a Python library typically used in Blockchain, Bitcoin applications.
- tinychain has no bugs or vulnerabilities.
python-bitcoinlib
- python-bitcoinlib is a Python library that provides a set of tools with Bitcoin.
- It allows developers to interact, create, and manage with the Bitcoin network.
- The library provides functionality to interact with the Bitcoin blockchain.
cointrol
- cointrol is a Python library typically used in Blockchain, Cryptocurrency, Bitcoin applications.
- Cointrol allows users to automate their Bitcoin trading strategies and monitor their cryptocurrency.
- It is a solution for individuals interested in algorithmic trading.
lightning-rfc
- lightning-rfc is a Python library typically used in Blockchain, Bitcoin applications.
- lightning-rfc has no bugs or vulnerabilities.
- The specifications are currently a work-in-progress.
freqtrade-strategies
- Freqtrade allows users to define and execute trading strategies based on technical indicators.
- Freqtrade provides a framework for developing custom trading strategies.
- Freqtrade comes with built-in strategies that users can use as a starting point.
cryptofeed
- cryptofeed is a Python library that provides a framework for handling real-time cryptocurrency.
- It simplifies the process of consuming and processing data.
- cryptofeed supports connectivity to multiple cryptocurrency exchanges.
pycoin
- pycoin is a Python library typically used in Financial Services, Fintech, Blockchain, Cryptocurrency.
- cryptofeed supports connectivity to multiple cryptocurrency exchanges.
- The library focuses on providing real-time market data, including price updates.
MikaLendingBot
- MikaLendingBot is a Python library typically used in Financial Services, Banks, Payments, Blockchain.
- MikaLendingBot has no bugs, it has no vulnerabilities.
- it has a build file available and has a Permissive License.
p2pool
- p2pool is a Python library typically used in Blockchain, Cryptocurrency, Bitcoin applications.
- Peer-to-Peer Pool is a decentralized mining pool protocol for various cryptocurrencies, including Bitcoin.
- P2Pool operates as a decentralized network of nodes, each running its own instance.
bit
- bit is a Python library typically used in Blockchain, Cryptocurrency, Bitcoin applications.
- bit has no bugs and has no vulnerabilities.
- You can install using 'pip install bit' or download it from GitHub, PyPI.
bitcoin-abe
- bitcoin-abe is a Python library typically used in Blockchain, Bitcoin applications.
- bitcoin-abe has no bugs and has a build file available.
- A block explorer tool helps users to explore and search the blockchain.
BitcoinExchangeFH
- BitcoinExchangeFH is a Python library typically used in Security, Cryptography, Bitcoin applications.
- BitcoinExchangeFH has no bugs, it has no vulnerabilities.
- BitcoinExchangeFH is a slim application to record the price depth and trades.
btcrecover
- btcrecover is an open-source Bitcoin wallet password recovery tool.
- It helps users recover or discover forgotten passwords for their Bitcoin.
- The primary purpose of btcrecover is to assist users in recovering passwords.
Cryptocurrency-Trading-Bots-Python-Beginner-Advance
- Cryptocurrency-Trading-Bots-Python-Beginner-Advance is a Python library typically used in Blockchain, Cryptocurrency.
- Cryptocurrency-Trading-Bots-Python-Beginner-Advance has no bugs.
- Cryptocurrency-Trading-Bots-Python-Beginner-Advance build file is not available.
api-v1-client-python
- api-v1-client-python is a Python library typically used in Web Services, REST, Bitcoin applications.
- api-v1-client-python has no bugs, it has no vulnerabilities.
- You can install using 'pip install api-v1-client-python' or download it from GitHub, PyPI.
bitpredict
- bitpredict is a Python library typically used in Blockchain, Cryptocurrency, Bitcoin applications.
- The dataset is a series of one second snapshots of open buy and sell orders on the Bitfinex exchange.
- it has a Permissive License, and it has low support.
pyminer
- pyminer is a Python library typically used in Security, Cryptography, Bitcoin applications.
- Cryptocurrency mining uses computational power to solve complex mathematical problems.
- Miners get newly minted cryptocurrency coins for their efforts.
electrumx
- ElectrumX is a server implementation of the Electrum protocol.
- ElectrumX implements the Electrum protocol, which are lightweight.
- ElectrumX is a server software that serves as the backend for Electrum wallets.
cryptocurrency_arbitrage
- cryptocurrency_arbitrage is a Python library typically used in Security, Cryptography, and Bitcoin applications.
- Traders engage in arbitrage to profit from inefficiencies in the pricing of assets.
- Traders look for discrepancies in the prices of a particular cryptocurrency on exchanges.
poclbm
- Poclbm stands for Proof of Concept (POC) Bitcoin Miner.
- It was one of the early Bitcoin mining software programs that utilized OpenCL for mining on GPUs.
- Poclbm was initially developed as a proof of concept to demonstrate its feasibility.
deep-trading-agent
- deep-trading-agent is a Python library typically used in Artificial Intelligence, Machine Learning, Bitcoin.
- Deep Reinforcement Learning-based Trading Agent for Bitcoin using DeepSense Network.
- deep-trading-agent has no bugs, it has no vulnerabilities.
FAQ
1. What is python-bitcoin?
python-bitcoin is not a specific library or tool. There are several, such as bitcoinlib, python-bitcoin-lib, and others. These libraries provide functionality to work with Bitcoin-related tasks like key management, etc.
2. How do I generate a Bitcoin address in Python?
To generate a Bitcoin address in Python, you can use a library like python-bitcoinlib.
Example:
from bitcoinlib.wallets import Wallet
wallet = Wallet.create('MyWallet')
new_address = wallet.get_key().address
print(f'New Bitcoin address: {new_address}')
3. What Python libraries are commonly used for Bitcoin development?
The Popular Python libraries for Bitcoin development include bitcoinlib, python-bitcoinlib, and pycoin. These libraries provide various functionalities for working with Bitcoin transactions, keys, and addresses.
4. How do I interact with a Bitcoin node using Python?
It can use the Bitcoinrpc library to interact with a Bitcoin node. Ensure that your Bitcoin node has RPC enabled.
Example:
from bitcoinrpc.auth proxy import AuthServiceProxy, JSONRPCException
rpc_user = 'your_rpc_user'
rpc_password = 'your_rpc_password'
rpc_connection = AuthServiceProxy(f'http://{rpc_user}: {rpc_password}@localhost:8332')
5. How do I use Python for Bitcoin price analysis?
It can use Python libraries like pandas and matplotlib for data analysis. Additionally, It might use APIs from cryptocurrency data providers to fetch real-time data.
Technology has always been evolving at a breakneck speed, but the pace of change today is surely unprecedented. Applications of blockchain, for instance, go beyond cryptocurrencies into industries like finance, healthcare, supply chain and logistics, asset management, etc. It is one of the most disruptive technologies of the 21st century, and now you can program blockchain web apps using JavaScript. With that in mind, here are some of the JavaScript libraries to help you in the process. ccxt - A cryptocurrency trading API; ZeroNet - Decentralized websites using Bitcoin crypto and the BitTorrent network; truffle - A tool for developing smart contracts. The following is a list of the most popular open-source libraries for building and scaling JavaScript Blockchain Applications.
A Python cryptocurrency library is essential for developers working with cryptocurrencies. It provides a set of tools and functions to interact with blockchain networks.
It manages digital wallets, performs cryptographic operations, and handles transactions. These libraries simplify complex tasks, enabling blockchain integration into applications. It also eases the development of cryptocurrency-related projects.
There are numerous popular cryptocurrency libraries in Python. Electrum is a Bitcoin wallet. It ensures the encryption of your private keys and never leaves your system. It guarantees zero downtime and is fast with cold storage options. Freqtrade is a cryptocurrency algorithmic trading software. It allows you to program your strategy using pandas. With this, you can download market data and test your strategy using simulated money. We also have LBRY, which claims to publish what Bitcoin did to money. With millions of people using the platform, it provides a free and open network for digital content. Vyper is a contract-oriented language that targets the Ethereum Virtual Machine. It aims to build secure smart contracts with simpler language implementation and auditability.
freqtrade:
- It is a popular open-source cryptocurrency trading bot written in Python.
- It offers a backtesting feature. This allows traders to test their strategies using historical data.
- It benefits from the developer and contributor community.
lbry-sdk:
- It is a software development kit (SDK) for the LBRY protocol.
- LBRY is a decentralized content-sharing and publishing platform that utilizes blockchain technology.
- It helps developers to build applications and services on LBRY protocol.
electrum:
- It is often used as a lightweight and efficient wallet implementation.
- It provides a simplified interface for interacting with the Bitcoin blockchain.
- It is modular, allowing developers to customize and extend its functionality.
bips:
- "BIPs" likely refers to Bitcoin Improvement Proposals.
- It helps with Blockchain, Cryptocurrency, and Bitcoin applications.
- It plays a role as a standardization and communication mechanism.
binance-trade-bot:
- It helps to automate your trading strategies, executing trades based on predefined criteria.
- It can offer several advantages in the cryptocurrency space.
- It can operate around the clock. This responds to market changes even when you're not monitoring the markets.
vyper:
- It helps with Blockchain, Cryptocurrency, Ethereum applications.
- It is a Pythonic Smart Contract Language for the EVM.
- It reduces the risk of vulnerabilities in smart contracts.
python-binance:
- It is a Python wrapper for the Binance API,
- It provides convenient access to Binance's cryptocurrency trading and data services.
- It simplifies the integration of Binance's services into Python applications.
alpha_vantage:
- Alpha Vantage is a financial data provider.
- It offers APIs for accessing various financial and cryptocurrency market data.
- It supports data from various cryptocurrency exchanges. This allows users to access information from different markets.
Crypto-Signal:
- It gives insights into market trends and potential trading opportunities.
- It can include risk management parameters, such as stop-loss and take-profit levels.
- It enables the automation of trading strategies.
web3.py:
- It provides functionality to interact with Ethereum, a blockchain-based cryptocurrency platform.
- Developers can interact with Ethereum smart contracts using Python.
- It is a set of specifications for interacting with Ethereum-like blockchains.
golem:
- It is a Python library used in Blockchain, & Ethereum applications.
- It is a decentralized marketplace for computing power.
- It enables CPUs and GPUs to connect in a peer-to-peer network.
manticore:
- manticore is a Python cryptocurrency library.
- It helps with Code Quality, Code Analyzer, and Ethereum applications.
- It is a symbolic execution tool for analysing smart contracts and binaries.
mythril:
- It helps in Financial Services, Fintech, Blockchain, Cryptocurrency, and Ethereum applications.
- A security analysis tool for EVM bytecode.
- It is also used in the security analysis platform.
catalyst:
- Catalysts offer a framework for developing complex trading algorithms.
- It provides a structured environment for designing, testing, and executing trading strategies.
- It provides tools for simulating and evaluating the performance of trading algorithms.
bitcoin-arbitrage:
- It allows traders to exploit price differences between different cryptocurrency exchanges.
- It allows for the development of sophisticated algorithmic trading strategies.
- It is an opportunity detector.
eth2.0-specs:
- It helps in Blockchain, Cryptocurrency, and Ethereum applications.
- These are crucial for implementing and interacting with Ethereum 2.0.
- These specifications define the rules and protocols for Ethereum's transition.
zvt:
- It is a Python library used in Blockchain and cryptocurrency applications.
- It acts as a modular quant framework.
- You can install it using 'pip install zvt' or download it from GitHub, or PyPI.
binance-trader:
- Binance-trader in Python is significant for cryptocurrency trading.
- It offers a simplified interface to interact with the Binance exchange.
- It allows developers to automate trading strategies, access market data, and execute orders.
pytrader:
- pytrader is a Python Cryptocurrency library.
- It helps with Blockchain, Cryptocurrency, Bitcoin, Nodejs applications.
- It is a cryptocurrency trading robot.
raspiblitz:
- raspiblitz is a Python Cryptocurrency library.
- It helps in Security, Cryptography, Bitcoin applications.
- It is a lightning node running on a RaspberryPi with a nice LCD.
raiden:
- raiden is a Python Cryptocurrency library.
- It helps with Blockchain, and Ethereum applications.
- It helps address scalability issues in blockchain networks, particularly for Ethereum.
SimpleCoin:
- SimpleCoin is a Python Cryptocurrency library.
- It helps in Financial Services, Fintech, Blockchain, and Bitcoin applications.
- It is simple, insecure, and incomplete implementation.
coinbasepro-python:
- It is particularly used for interacting with the Coinbase Pro API.
- It provides a way for developers to integrate their apps with this trading platform.
- It facilitates tasks such as accessing market data and placing and managing orders.
py-evm:
- Py-EVM, short for Python Ethereum Virtual Machine, is a Python library.
- It provides an implementation of the Ethereum Virtual Machine (EVM).
- It allows developers to work with Ethereum-based applications and smart contracts using Python.
tinychain:
- tinychain is a Python Cryptocurrency library.
- It helps with Blockchain, and Bitcoin applications.
- It is a pocket-sized implementation of Bitcoin.
RLTrader:
- It is a Reinforcement Learning Trader, in a Python Cryptocurrency library.
- It automates trading decisions, reducing the need for constant manual monitoring.
- It allows us to learn from historical market data and adjust its trading decisions.
python-bitcoinlib:
- It is a Python library that provides tools for working with Bitcoin.
- It facilitates the creation, signing, and broadcasting of Bitcoin transactions.
- It maintains and updates, ensuring compatibility with the latest Bitcoin protocol changes.
cointrol:
- It is a Python library used in Blockchain, Cryptocurrency, and Bitcoin applications.
- It is a Bitcoin trading bot and real-time dashboard for Bitstamp.
- It creates to automate Bitcoin speculation.
pycoin:
- It is a Python library designed to work with Bitcoin and other cryptocurrencies.
- It facilitates key generation, conversion, and management.
- It assists in creating and validating complex scripts used in Bitcoin transactions.
smart-contracts:
- smart contracts is a Python Cryptocurrency library.
- It plays a crucial role by enabling self-executing contracts with predefined rules.
- It acts as an Ethereum smart contract for security and utility tokens.
MikaLendingBot:
- It is a Python Cryptocurrency library.
- It helps with Blockchain, Cryptocurrency, Ethereum, Bitcoin applications.
- It acts as an automated lending on Cryptocurrency exchanges.
hummingbot:
- It is a Python cryptocurrency library.
- It is an open-source software that facilitates algorithmic trading in the cryptocurrency market.
- It is particularly useful for market makers who seek to provide liquidity to the market.
FAQ
1. What is the purpose of the Python Cryptocurrency library?
It eases the integration of cryptocurrency-related functionalities into Python applications. It offers a set of tools and methods for tasks. Those tasks are blockchain interaction, wallet management, and transaction processing.
2. Which cryptocurrencies get support from the library?
The supported cryptocurrencies may vary depending on the library. Supported ones include Bitcoin, Ethereum, and others. It's essential to check the library documentation for the specific cryptocurrencies it supports.
3. How do I install the Python Cryptocurrency library?
Installation methods can vary. You can use pip, which is the Python package manager. It helps with a command like pip install cryptocurrency-library. Refer to the library documentation for any more installation instructions.
4. Does the library provide functions for interacting with blockchain data?
Yes, the library often includes functions for fetching blockchain information. Also, it includes querying transaction details and obtaining data from the blockchain. Consult the library documentation for specific methods and examples.
5. Can I create and manage cryptocurrency wallets using this library?
Yes, many cryptocurrency libraries offer functionalities for creating and managing wallets. You can generate addresses, check balances, and perform transactions. Ensure you follow security best practices when handling wallets.
NFT stands for Non-Fungible Token. It is a digital asset and what makes it unique from stock photos is the token associated with the asset. This combination of asset and token makes it non-fungible and guaranteed by blockchain technology. You may compare it to original artwork or maybe an autographed print copy or digital trading cards. An easy start into NFT is a self service marketplace like OpenSea or Mintable. But if you are more of a developer than an artist, here are trending libraries that help you publish your own NFTs.
Listing NFTs in your Website
The libraries embeddable, nfte and nftgecko help in listing the NFTs in your website.
Creating DApp
Scaffold-eth, etherplate and kitty-items are frameworks for creating DApp (Decentralized Applications) & Marketplace on Ethereum blockchain.
Deploying and Minting NFTs
EthArt, contractor and open-proofs are used for deploying and minting the NFTs.
When trading in Forex, it is important to develop a trading bot that makes risk management easy - since Forex involves high-level financial market data.
Python is one of the most popular programming languages for Forex because it enables the API to be functionally separated to perform buying and selling operations. Python-based open-source software supports both backtesting and live trading operations to help the traders develop sound strategies for a Forex application. Python libraries also provide code for working with real-time currency exchange rates.
Below is a comprehensive list of the 26 best open-source python libraries for developing Forex algorithmic trading applications. If you are looking for a full-scale, event-driven library that transitions seamlessly from testing to live trading, then qsforex is for you. Yahoofinancials is a code package that enables you to pull data like indices, currencies, ETFs, etc. from Yahoo Finance.
If you intend to trade in cryptocurrencies, bitex enables you to do that by using API classes without employing interface classes. Forex-python is a library that shows exchange rates and cyptocurrency price index using ratesapi.io.
qsforex
- It helps the development and testing of trading algorithms. We intend it for the forex market.
- It provides a framework for implementing various trading strategies.
- It enables users to assess their performance based on historical market data.
yahoofinancials
- It focuses on fetching historical market data from Yahoo Finance.
- It facilitates the retrieval of historical data for specific currency pairs. Users could get historical exchange rate information between different currency pairs.
- It integrates historical foreign exchange data into various financial applications.
- It allows developers to incorporate currency-related insights and analytics into their projects.
bitex
- It provides a unified API for accessing various cryptocurrency exchanges. It exchanges its digital assets for traditional currencies.
- It allows users to manage their cryptocurrency portfolios across different exchanges.
- It facilitates the execution of trades across multiple platforms.
forex-python
- It is a Python library that provides a way to fetch foreign exchange rates.
- It performs currency conversion and accesses historical data.
- It offers a simple and easy-to-use interface. It works with foreign exchange data.
LSTM---Stock-prediction
- LSTM models can forecast future exchange rates based on historical data and patterns.
- It can process sequential data to identify patterns and trends in the forex market.
- It captures the dependencies and relationships between different currency pairs over time.
- It enables traders to make decisions on the buying and selling of currencies.
Google-Search-API
- Developers can use the Google Search API to fetch real-time foreign exchange rates.
- It enables them to integrate up-to-date currency exchange data into their applications.
- It helps retrieve the market updates related to the foreign exchange market.
money
- The "money" library in Python refers to a Python package.
- It provides functionality for working with monetary values and currencies.
- It facilitates seamless currency conversion between different currencies.
- It converts the monetary values of currency based on the prevailing exchange rates.
ratesapi
- It is an open-source foreign exchange rates API.
- It provides real-time and historical foreign exchange rate data.
- It offers a simple way for developers to access up-to-date foreign exchange rates.
Forex-DQN
- It approximates a state-value function in a Q-Learning framework with a neural network.
- Foreign exchange is a global market. It helps in the trading of currencies.
- It is a learning agent that trains a critic. It helps estimate discounted expected cumulative reward.
gym-fx
- Gym-FX is an open-source Python library and Pythonic API.
- It provides a forex trading environment for developing and testing reinforcement learning agents.
- It provides simulated training environments to train reinforcement learning agents.
- It is an essential toolkit for training RL algorithms.
currencyconverter
- It provides functionality for currency conversion and foreign exchange rate retrieval.
- This library allows users to convert monetary values between different currencies.
- It retrieves up-to-date exchange rate information.
- Developers can perform various foreign exchange-related tasks efficiently within their Python applications.
TradingGym
- "TradingGym" could provide a simulated trading environment.
- It allows users to test and develop trading strategies for foreign exchange.
- It enables traders and developers to experiment with different trading approaches.
- It assesses their effectiveness in different market conditions.
forex-rl-challenge
- It offers a collection of reinforcement learning algorithms for foreign exchange markets.
- It helps optimize trading strategies and decision-making processes.
- It integrates external data. It provides access to historical and real-time foreign exchange market data.
Forex-and-Stock-Python-Pattern-Recognizer
- It can recognize patterns inside Forex or stock data.
- Foreign exchanges help identify recurring patterns in market data.
- It can make informed trading decisions.
- It helps analyze historical market data to detect patterns and trends.
- It provides insights into potential future market movements.
django-money-rates
- A little Django app that uses py-moneyed to add support for Money fields in your models and forms.
- It supports for proper Money value handling (using the standard Money design pattern)
- A currency class and definitions for all currencies in circulation
- It helps format most currencies with the correct currency sign.
Trading-Bot
- It is a software program that executes trades on behalf of traders in foreign exchange.
- It follows pre-defined trading strategies and algorithms.
- It can continuously watch the forex market and execute trades anytime.
intrinio-realtime-python-sdk
- It is a software development kit.
- It allows developers to integrate real-time financial data into their Python applications.
- It enables developers to access real-time foreign exchange data, including live currency exchanges.
- It helps analyze real-time currency market data. It helps make decisions in the foreign exchange market.
alfred3-workflow-CurrencyX
- It is a Python library in Security, Cryptography, and Ethereum applications.
- It captures the dependencies and relationships between different currency pairs over time.
- It enables them to integrate up-to-date currency exchange data into their applications.
currency-exchange
- It is a Python library typically used in Automation BPM applications.
- It provides functionality for currency conversion and foreign exchange rate retrieval.
- This library allows users to convert monetary values between different currencies.
- It retrieves up-to-date exchange rate information.
django-exchange
- It helps in handling currency conversion and displaying foreign exchange rates.
- It makes it easier to manipulate money throughout your application.
- It provides a simple, flexible, and extensible way to work with currencies in Django.
ImundboQuant
- It is an open-source project that uses machine learning in Python and MQL4.
- It helps in stock market and forex market predictions and fully automated trading.
- It is a powerful tool. It can improve users' investment performance.
- It helps to make better investment decisions by providing information about the market.
mexbtcapi
- It is a Python library typically used in Blockchain, Cryptocurrency, and Bitcoin applications.
- It is a Multi-Exchange Bitcoin API. It provides consistent APIs of various cryptocurrency exchanges.
- This API supports multi-currency and multi-exchange functions.
jiji-with-tensorflow-example
- It is a Python library typically used in Artificial Intelligence and Tensorflow applications.
- This library allows users to convert monetary values between different currencies.
- It retrieves up-to-date exchange rate information.
- It facilitates seamless currency conversion between different currencies.
pyfx
- It is a Python library typically used in Blockchain and cryptocurrency applications.
- A way to integrate historical foreign exchange data into various financial applications.
- It allows developers to incorporate currency-related insights and analytics into their projects.
FinanceMarketDataGrabber
- It is a Python library typically used in Web Services, REST, and Panda's applications.
- It helps access stock/forex quotes from Yahoo and Google Finance 'APIs'.
- We can receive multiple stock quotes and multiple symbols in a single call.
- It retrieves real-time and Historical data for foreign exchange.
QuantConnect-Trading-Strategies
- It helps in Machine Learning and Deep Learning applications.
- Use algorithmic trading strategies to identify trends and patterns to make trading decisions.
- It includes risk management parameters to help minimize potential losses.
FAQ:
1. What is the Python library for currency?
Forex-Python is a Python foreign exchange library. It provides a way to get a currency conversion rate through API calls. It takes the currency codes you want to convert from one currency to another. It returns the current value.
2. What is foreign exchange data?
The foreign exchange market is a global decentralized market. It helps in currency trading. It will help determine foreign exchange rates for every currency. It will include all aspects of buying and exchanging currencies at determined prices.
3. What is the function of a currency converter in Python?
Access up-to-date data directly from reliable sources. Automatically update the conversion rates without manual intervention. Ensure accuracy and reliability in conversions.
4. What is fixer io?
Fixer.io is a simple and easy API for current and historical foreign exchange rates. It offers real-time data on the exchange rates for world currencies.
5. Is there a free exchange rate API?
Yes, a 100% free solution for handling exchange rate conversions exists. Our currency API provides live and historical exchange rate data ranging.
A smart contract is a computer program that directly controls the transfer of digital currencies or assets between parties under certain conditions.
Actions are triggered by an event, a message transmitted on the blockchain network, and results are guaranteed by the consensus of multiple nodes. Smart contracts can also be used to store information about an application, such as domain registration information or membership records. Smart contracts are used to execute transactions in a decentralized manner.
This means that the validation of a transaction does not depend on a single party, but rather everyone involved in the transaction will validate it. A smart contract can be written in Solidity or any other language that compiles to EVM (Ethereum Virtual Machine) bytecode. The following is a list of the most popular open-source Python Smart contract libraries:
vyper
- Vyper wants its code to be easy and safe so there are fewer chances of mistakes.
- It focuses on making the code easy to read and understand so developers know what's happening.
- Vyper tries to use less computer power when running on the Ethereum Virtual Machine.
mythril
- Mythril looks for common mistakes in the code, even the well-known ones, automatically.
- It fits into how you work, helping you keep an eye on security while you build.
- Mythril keeps an eye on security from the start to the end of making your program.
brownie
- Brownie makes it easy to build smart contracts if you know Python.
- It has tools that help you test your program to make sure it works well.
- Brownie helps you put your program on the Ethereum network without a headache.
smart-contracts
- Smart contracts automatically follow the rules written in the code.
- They make deals and transactions happen without needing anyone in the middle.
- Smart contracts work on the Ethereum system, making everything trustworthy and decentralized.
uniswap-v1
- Uniswap-v1 was the first to make trading happen automatically on decentralized platforms.
- It's a system that lets you swap different types of tokens easily.
- Uniswap-v1 has a set formula to keep trading steady and reliable.
yearn-vaults
- Yearn Vaults know how to save and make you earn more on what you put in.
- They keep searching for the best ways to make more money across different programs.
- Just put your money in, and Yearn Vaults work to make you extra money without you doing much.
MAIAN
- MAIAN is like a security expert for Ethereum smart contracts.
- It checks the code closely to find and fix common security problems.
- Gives tools to developers to find and fix security issues in their smart contracts
octopus
- Octopus is like a toolbox for building, testing, and putting your work on the blockchain.
- It's built to be flexible and easy to use for making changes without headaches.
- Octopus provides tools to ensure your work is solid and reliable in development and use.
awesome-buggy-erc20-tokens
- It's a group of tokens meant to show mistakes for learning, not for real use.
- These tokens show problems that can happen in ERC-20 tokens, helping others learn.
- The project wants to teach people about common mistakes in ERC-20 token contracts.
eosfactory
- Eosfactory is a helper for developers making programs for EOS.
- It lets you safely test your EOS programs before putting them into action.
- Supports fast testing and trying out ideas for applications on the EOS blockchain.
pyteal
- Pyteal helps you use the Python language to build smart contracts on Algorand.
- It opens up smart contract development to more people who know Python.
- Supports Algorand's special language for making smart contracts called TEAL.
scrooge -mcetherface
- This tool is a helper for making things on the blockchain using Python.
- It's advertised as having no mistakes or problems, showing it's well-made and safe.
- Scrooge -Mcetherface helps developers find and fix Ether theft and destruction issues.
vandal
- Vandal is like a detective tool for looking closely at Ethereum smart contracts.
- It uses special techniques to break down the code into something understandable.
- Vandal is open for anyone to see and use, following clear rules for sharing on GitHub.
Rouleth
- Rouleth was one of the first smart contracts on Ethereum without mistakes.
- The current Proof of Concept (PoC) shows it working well on the blockchain.
- It's a tool for blockchain, cryptocurrency, and Ethereum project developers.
python-smart-contract-workshop
- This library gives a hands-on place for learning to build smart contracts in Python.
- It includes tasks and activities to guide developers in creating their smart contracts.
- Focuses on how to build using Python, aligning with what's needed in real situations.
erays
- Erays says it has no bugs, making developers feel more confident about using it.
- It helps developers understand smart contracts better by looking beyond the usual code.
- Even if there's no downloadable file, it improves how developers understand smart contracts.
vertigo
- Vertigo is great for checking if your smart contract is strong and reliable.
- Focuses on testing tools made for Solidity, which is crucial for Ethereum development.
- Vertigo offers ways to check for issues and weaknesses in smart contract code.
contracting
- Contracting makes basic operations like creating, reading, updating, and deleting easy.
- Lamden makes it and ensures that your smart contract works well and is safe.
- Though there's less help available, installing Contracting is simple with 'pip install contracting.'
cobra
- Cobra is a Python tool used in finance, fintech, blockchain, and Ethereum projects.
- It helps build and adapt Ethereum smart contracts, supporting a fast development process.
- Users can use scripts to deploy and make changes easily, making it flexible and adaptable.
smartbugs
- Smartbugs have tools to find problems in smart contracts and fix them.
- Finds and reports issues in Ethereum smart contracts to make them more secure.
- It reviews code to ensure it follows security practices in smart contract development.
raiden-contracts
- Raiden-contracts focus on making transactions faster and cheaper, solving problems with Ethereum's size.
- Facilitates fast, cost-effective transactions outside the main Ethereum network.
- It uses state channels, a proven method, to make transactions both safe and scalable.
FAQ
1. What is Vyper?
Vyper is like a language (but for computers) used to make things on Ethereum. It's like Python and focuses on making things simple and safe.
2. How does Mythril help keep things safe in smart contracts?
Mythril is like a smart friend that checks computer programs for problems. It looks at Ethereum programs and finds mistakes that could cause trouble.
3. What tools does Brownie have for testing?
Brownie is like a helper with tools for checking if Ethereum programs work well. It helps make sure that the things you build are strong and won't break easily.
4. How does Uniswap do its job?
Uniswap is like a special place online where you can change different tokens easily. It doesn't use the usual way of trading. Instead, it has a system that makes swapping tokens simple and fast.
5. Why do we use Yearn Vaults?
Yearn Vaults are like smart piggy banks. They help your money grow without you doing much. They look for the best ways to make more money with what you put in, like a helper for your savings.
One of the reasons Python trading libraries are a good choice for financial market analysis is that Python is an OOP language.
Each function in Python and the data manipulated by it belong to a unique object, making it possible to abstract individual functions. Quantitative finance banks on backtesting trading strategies - Python modules provide pre-written code with the lowest possible error potential, making it a reliable language for risk analysis. Augmenting a Python code with a robust framework such as Django enables developers to create an analysis tool capable of machine learning and time series analysis of the market.
Here is a great list of useful Python stock market tracker libraries you can use as a readymade solution for your programs. For crawling the historical data, specifically of China stocks, install the Tushare library. Another great library to have in your collection is yfinance, which gives you the capability of downloading market data. Qlib is a great tool for quantitative investments, providing the trader with capability of using AI in their stock trading applications.
tushare:
- It provides access to financial data from various sources.
- It is valuable for stock market tracking and analysis.
- It helps in cleaning and preprocessing financial data. It saves time for analysts and researchers.
qlib:
- It is a quantitative investment library for Python.
- Its importance lies in its features tailored for quantitative finance and algorithmic trading.
- It supports live trading. It allows users to install and execute their strategies in real-time markets.
ajenti:
- It is a Python library used in User Interface, Frontend Framework, Angular applications.
- It is a Linux & BSD modular server admin panel.
- It is a web-based control panel for managing systems. It includes a dashboard for monitoring various aspects of a system.
yfinance:
- It provides a simple interface to download financial data from Yahoo Finance.
- It allows you to access a diverse set of financial data. It includes historical stock prices, dividends, and splits.
- Being used, yfinance benefits from an active community.
trump2cash:
- It is a Python library used in Analytics, Predictive Analytics applications.
- It is a stock trading bot powered by Trump tweets.
- The code is written in Python and run on a Google Compute Engine instance.
rqalpha:
- It is a Python library designed for quantitative finance and algorithmic trading.
- It provides a framework for backtesting. Also, it provides a paper on trading strategies using historical market data.
- RQAlpha aims to make it accessible for those starting with algorithmic trading.
LSTM-Neural-Network-for-Time-Series-Prediction:
- They are crucial for time series prediction in Python stock market tracker libraries.
- The importance lies in the capacity to learn and remember information.
- They excel in handling temporal relationships, making them well-suited for predicting stock prices.
pandas-ta:
- pandas-ta (Technical Analysis) is an extension library for Pandas.
- It helps to ease the technical analysis of financial market data.
- This allows for a thorough analysis of price movements. It helps in making informed trading decisions.
clairvoyant:
- clairvoyant techniques, or predictive analytics, can be important for forecasting future stock prices.
- By leveraging historical data and various algorithms, this aims to predict market trends.
- This can assist traders and investors in making informed decisions. Its basis is future price movements.
backtesting.py:
- It is crucial to evaluate the performance of trading strategies using historical data.
- It allows you to simulate and test how a specific strategy would have performed in the past.
- It helps traders and developers refine their strategies and optimize parameters.
bulbea:
- It helps in Artificial Intelligence, Machine Learning, and Deep Learning applications.
- It is a Deep Learning based Python Library for Stock Market Prediction and Modelling.
- It has built files available, and it has medium support. But bulbea has a Non-SPDX License. You can download it from GitHub.
Reddit-Stock-Trends:
- It is a Python library used in Web Site, Business applications.
- Traders often check these trends for potential investment insights.
- It helps to see trending stock tickers on Reddit and check Stock performance.
deep_trader:
- It helps in Institutions, Learning, Education, Artificial Intelligence, ML, Nodejs, Unity apps.
- This project uses reinforcement learning on stock market. Its agent tries to learn trading.
- The goal is to check if the agent can learn to read tapes.
surpriver:
- It helps in Artificial Intelligence, Machine Learning, Deep Learning applications.
- It is a module for loading data from Yahoo Finance.
- It is a folder to save data dictionaries for later use.
stock-rnn:
- It is a type of neural network designed for analyzing and predicting stock market data.
- It can capture these dynamics. This allows more accurate predictions compared to simpler models.
- Identifies the most important factors affecting stock prices without explicit feature engineering.
AIAlpha:
- AIAlpha refers to the integration of artificial intelligence (AI) capabilities.
- Integrating AIAlpha in stock market trackers allows for dynamic portfolio management.
- It enables stock market trackers to make decisions based on more analysis of data.
Personae:
- Personae, or personas, is a Python stock market tracker library.
- It refers to the user roles or profiles that interact with the software.
- Active traders may use real-time data and technical analysis tools. It also has customizable dashboards for quick decision-making.
stocksight:
- It is a Python library used in Analytics and Predictive Analytics applications.
- It is an open-source stock market analysis software. This software uses Elasticsearch to store Twitter and news headlines data for stocks.
- It analyzes the emotions of what the author writes and does sentiment analysis on the text.
yahoo-finance:
- It is a Python library used in Web Services, REST, and Pandas applications. It allows you to access financial data from Yahoo Finance.
- Its importance lies in providing a convenient and accessible way to retrieve information.
- It simplifies the process of fetching and working with stock-related information.
fooltrader:
- fooltrader is a Python library used in websites and business applications.
- It is a tool or library related to stock market tracking. You can install it using 'pip install fooltrader' or download it from GitHub or PyPI.
- Its importance would depend on its features, accuracy, and community support.
MachineLearningStocks:
- ML models can analyze historical stock data to identify patterns and trends. It aids in predicting future stock prices.
- It can help assess risk by analyzing market volatility, enabling better-informed investment decisions.
- It can process large datasets, extracting valuable information for making informed investment decisions.
FAQ
1. What is a Python stock market tracker library?
A Python stock market tracker library is a set of tools and functions. Those tools and functions access, retrieve and analyze financial market data. It particularly allows us to retrieve stock prices using Python programming language.
2. How do I install a stock market tracker library in Python?
You can use a package manager like pip to install a stock market tracker library. For example, you can use pip install yfinance for Yahoo Finance API.
3. What are some popular Python stock market tracker libraries?
Some popular libraries include yfinance, pandas_datareader, and alpha_vantage. These libraries provide interfaces to access financial data from various sources.
4. Can I track real-time stock prices with Python?
Yes, some libraries, like yfinance and alpha_vantage, provide real-time stock price data. Keep in mind that real-time data might come with limitations depending on the data source.
5. How do I retrieve historical stock data using Python?
You can use functions provided by libraries. Those libraries are like yfinance or pandas_datareader to fetch historical stock data.
For example:
With yfinance, you can use history = yf.download("AAPL", start="2022-01-01", end="2023-01-01").
Creating an online voting system using reusable libraries involves selecting appropriate libraries for different components of the system.
In recent years, the usage of mobile phones is increased. It has been surveyed that there is a rising interest in voting on SMS cell phones and through social networking tools like Facebook or Twitter. It's believed the voting process by cell phones gives some decision power to the citizens, which can actuate directly on decisions of their concerns. The voting process also can give ways for numerical information surveillance about social phenomena. It describes the intention to create an electronic voting process using mobile. You can create your own customized online e-voting system. 1. Development Environment 2. Database 3. Vote collecting Web Services 4. E-voting application 5. Vote Tally application
Development Environment
VS code is used for development for web application.
Database
Database is used to collect and maintain the voting data collected during the public voting process.
Vote Tally application
Application is used to tally the votes.
Vote collecting Web Services
The services are dynamic pages which receives parameters via the web browser component from inside Android application.
E-voting application
e-voting application is used for smart voting from various devices
All secure systems on the internet use HTTPS, which means the encrypted data sent from a browser is decrypted only at the server end and vice versa. But even while storing this data, we need to ensure that it’s secure and unreadable by unauthorized personnel. This is now possible using JavaScript, where we can implement both symmetric key cryptography and asymmetric encryption using algorithms like Triple DES and AES, which use 128 bits key length and above for increased security. With this in mind, let’s look at some of the JavaScript encryption libraries. gun - open source cybersecurity protocol; jsencrypt - Javascript library to perform OpenSSL RSA Encryption; Forge - A fully native implementation of the TLS protocol in JavaScript, a set of cryptography utilities, and a set of tools for developing Web Apps that utilize many network resources. Full list of the best open-source JavaScript Encryption libraries below.
Developing a blockchain in Java makes it portable across various devices because it uses plugin-architecture, which means it is possible to develop several blockchain-based components in parallel. Blockchain technologies are considered highly secure for the cryptocurrency universe because of their distributed ledger property. In the blockchain world, java is considered one of the best blockchain programming languages because of its reliable frameworks of Hyperledger Fabric and Web3j. In addition, the JIT and GC functionalities make the Java runtime environment highly time efficient, which is highly preferable for Java developers. Bitcoinj library allows the user to keep a Bitcoin wallet and a ledger of transactions that do not need a local copy. The bitcoin-wallet library is an exclusive code package meant for Android-based Bitcoin applications. The functionality to manage Hyperledger lifecycle is provided to the developer by the library fabric-sdk-java. Listed below are some interesting Java libraries for blockchain applications that provide handy code packages for ready implementation.
A proof-of-work (PoW) is a piece of data that is difficult (costly, time-consuming) to produce but easy for others to verify and that satisfies certain requirements. Producing a proof of work can be a random process with low probability so a lot of trial and error is required on average before a valid proof of work is generated. A major advantage of PoW is its ability to safeguard against 51 percent attack. In order for an attacker to control more than half of the network’s computational power, it would cost him millions of dollars in mining equipment and electricity bills. It also protects against Sybil attacks, where an attacker can create multiple fake identities in order to gain control over the network. You can find dozens of open source libraries on the Internet these days. Below are the top 11 Python Proof of work libraries in use today:
NFT stands for Non-Fungible Token. Something that is "fungible" can be exchanged with an equivalent item .Non-fungible tokens (NFTs) are changing the way we own things digitally. Things that are not directly interchangeable or replaceable are known as non-fungible. The non-fungible token has garnered significant attention as one of the most exciting, transformative innovations blockchain has to offer developers and businesses. The Meaning of Life NFT Collection aims to create unique and personalized answers to the question: What is the meaning of life, the universe, and everything else? The NFT collection is limited to 42 NFTs.
Development Environment
VSCode is used for development and debugging. Node.js is an open-source, cross-platform, JavaScript runtime environment. It executes JavaScript code outside of a browser, whereas VSCode is used to get a typical experience of IDE for developers. npm is the default package manager for the JavaScript runtime environment Node.js.
Cryptowallet
MetaMask-extension library is a software cryptocurrency wallet used to interact with the Ethereum blockchain.
Installation Guide
Download, extract and double-click kit_installer file to install the kit. Note: Do ensure to extract the zip file before running it.
Metamask Connection
1. After adding Metamask extension to your browser, click get started there you will see 'IMPORT WALLET' and ' CREATE WALLET' there click the create wallet. 2. There you select I agree and it asks you to create the password. After creating the password it shows you the recovery phrase. 3. If you forget the password you can use the recovery phrase. 4. Then one Account will be created, and the default network will be there 'ETHEREUM MAINNET'. 5. At the top there is a Network tab there click show/hide network there find and select the "show test networks". 6. To collect ETH in your account click the link . 7. Copy the address which is present below the account, paste it into Testnet account address then click send the request.
Support
If you need help to use this kit, you can email us at kandi.support@openweaver.com or direct message us on Twitter Message Message @OpenWeaverInc.
NFT's or Non Fungible Token's are a new technology phenomenon allowing clear ownership and easy transferability of digital art. This property means each token is unique and cannot be swapped identically for another token ever. NFT can be most anything digital, such as art, images, videos, music, memes, and tweets. The process of creating NFTs is “minting”, similar in concept to metal coins that are minted (stamped) to confirm their legitimacy. Minting an NFT produces a one-of-a-kind token on the blockchain and an electronic certificate of authenticity. NFT Marketplace for Images is used to generate the cryptoboy using the NFT, Blockchain, Cryptocurrency. The generated cryptoboy can be sold and they can see who is the token owner and also token metadata.
Training and Certification - NFT Marketplace for Images
Watch this self-guided tutorial on NFT Marketplace for Images. This includes an understanding of Metamask; a chrome extension used as a crypto wallet, Ganache-Truffle Suite a personal Ethereum Blockchain for distributed application development to build your own NFT Marketplace for CryptoBoy Images Completed the training? Apply for your Participation Certificate and Achievement Certificate now! Tag us on social media with a screenshot or video of your working application for a chance to be featured as an Open Source Champion and get a verified badge.
Installation Guide
⬇️Download, extract and double-click kit installer file to install the kit. Note: Do ensure to extract the zip file before running it.
Development Environment
VSCode is used for development and debugging. Node.js is an open-source, cross-platform, JavaScript runtime environment. It executes JavaScript code outside of a browser, whereas VSCode is used to get a typical experience of IDE for developers.
Tools
To make a Crypto boy you need to install truffle, Ganache CLI, npm, Metamask. Truffle framework is used as a testing framework and asset pipeline for blockchains using the Ethereum Virtual Machine (EVM). Ganache-CLI is the latest version of TestRPC and a fast and customizable blockchain emulator. npm is the default package manager for the JavaScript runtime environment Node.js. MetaMask is a software cryptocurrency wallet used to interact with the Ethereum blockchain.
Support
If you need help to use this kit, you can email us at kandi.support@openweaver.com or direct message us on Twitter Message Message @OpenWeaverInc.
Blockchain games are using various levels of decentralization as part of their mechanics. Blockchain technology also enables cross-game interoperability, player-driven economy, and play-to-earn gaming models. Through the tokenization of gameplay and smart contracts, memory puzzle will increase the number of tokens for each matches.
Metamask Extension
- After adding Metamask extension to your browser, click get started there you will see 'IMPORT WALLET' and ' CREATE WALLET' there click the create wallet.
- There you select I agree and it asks you to create the password. After creating the password it shows you the recovery phrase.
- If you forget the password you can use the recovery phrase.
- Then one Account will be created, and the default network will be there 'ETHEREUM MAINNET'.
- At the top there is a Network tab there click show/hide network there find and select the "show test networks".
- Then delete 'Localhost:8545'.
- lick 'Add Network' and fill the Network name : 'Ganache' ,RPC URL: 'HTTP://127.0.0.1:7545', Chain Id :'1337' then save. Now you can see 'Ganache Network' in metamask.
Troubleshoot
- While running batch file, if you encounter Windows protection alert, select More info --> Run anyway.
- During kit installer, if you encounter a Windows security alert, click Allow.
- Ensure Ganache is open before running the 1-Click Installer.
- Make sure you have chosen the Ganache Network in the Metamask Extension.
- Sometimes you may face the "out of gas error" to resolve this error, edit the "Gas Limit".
- Sometimes after npm start it throw's an error as create the .env file. For that create the .env file inside the project SKIP_PREFLIGHT_CHECK=true.
For a detailed tutorial on installing & executing the solution as well as learning resources including training & certification opportunities, please visit the OpenWeaver Community
Development Environment
VSCode is used for development and debugging. Node.js is an open-source, cross-platform, JavaScript runtime environment. It executes JavaScript code outside of a browser, whereas VSCode is used to get a typical experience of IDE for developers. npm is the default package manager for the JavaScript runtime environment Node.js.
Ethereum Development Tools
Truffle is a development environment, testing framework and asset pipeline for Ethereum. Web3.js is the Ethereum JavaScript API which connects to the Generic JSON-RPC spec. Solidity is a component to build custom contracts and more complex decentralized systems.Ganache-CLI is the latest version of TestRPC and a fast and customizable blockchain emulator.
Crypto Wallet
MetaMask-extension library is a software cryptocurrency wallet used to interact with the Ethereum blockchain.
Support
If you need help using this kit, you may reach us at the OpenWeaver Community
Non-fungible tokens (NFTs) are changing the way we own things digitally. Things that are not directly interchangeable or replaceable are known as non-fungible. The non-fungible token has garnered significant attention as one of the most exciting, transformative innovations blockchain has to offer developers and businesses. NFT Generator software, lets you to create NFT collections of 10,000 or more graphic variations.
Development Environment
VsCode and Node.js are used for development and debugging. Node.js is an open-source, cross-platform, JavaScript runtime environment. It executes JavaScript code outside of a browser, whereas VsCode is used to get a typical experience of IDE for developers.
Token Generator
React Canvas adds the ability for React components to render rather than DOM. SHA1 is a cryptographic hash function for JavaScript supports UTF-8 encoding. Gif encoder is used to generate Gif from images which builds on top of previous JavaScript GIF encoders including jsgif and gifencoder.
Installation Guide
Download, extract and double-click kit_installer file to install the kit. Note: Do ensure to extract the zip file before running it.
Support
If you need help to use this kit, you can email us at kandi.support@openweaver.com or direct message us on Twitter Message Message @OpenWeaverInc.
Trending Discussions on Blockchain
Why Metamask if web3.js can interact directly with ganache?
Error: Property 'body' cannot be accessed on 'Response?' because it is potentially null
How to send a web3 transaction from a test account of RSKj regtest blockchain node
How can I convert an [u8] hex ascii representation to a u64
The transaction declared chain ID 5777, but the connected node is on 1337
How to locally unit-test Chainlink's Verifiable Random Function?
I want to get the address from mnemonic with the proper derivation path
how to sign a message with ecdsa privatekey using golang?
Flag provided but not defined: -rpc
ParserError: Source file requires different compiler version
QUESTION
Why Metamask if web3.js can interact directly with ganache?
Asked 2022-Mar-30 at 17:55I am new to blockchain app development, I saw a project where ganache accounts are imported into Metamask, then web3.js is used to access and print those accounts and balances on Frontend (user interface).
If web3.js can directly access ganache blockchain accounts and balances, why do we need Metamask in between?
ANSWER
Answered 2022-Feb-08 at 09:11If web3.js can directly acccess ganache blockchain accounts and balances, why we need metamask in between?
In this case, you don't need MetaMask to sign the transaction, as the node (Ganache) holds your private key.
But in a public environment (testnets and mainnet), the node doesn't hold your private key, so you'd need to sign the transaction using MetaMask (or any other tool that holds the private key).
QUESTION
Error: Property 'body' cannot be accessed on 'Response?' because it is potentially null
Asked 2022-Mar-29 at 00:29so I'am trying to learn dart and flutter and everything went well so far. But now I'am stuck at an error which I cannot handle. I coded a function which is supposed to asynchronously return the actual BTC price from https://blockchain.info/ticker.
Only thing it returns is errors:
1Error: Property 'body' cannot be accessed on 'Response?' because it is potentially null.
2 - 'Response' is from 'package:http/src/response.dart' ('/D:/flutter/.pub-cache/hosted/pub.dartlang.org/http-0.13.4/lib/src/response.dart').
3Try accessing using ?. instead.
4 return Text("${BTCPrice.fromJson(jsonDecode(snapshot.data.body)).eur}");
5 ^^^^
6/D:/flutter/packages/flutter/lib/src/widgets/async.dart:242:12: Context: 'data' refers to a property so it couldn't be promoted.
7See http://dart.dev/go/non-promo-property
8 final T? data;
9 ^
10
My Code:
1Error: Property 'body' cannot be accessed on 'Response?' because it is potentially null.
2 - 'Response' is from 'package:http/src/response.dart' ('/D:/flutter/.pub-cache/hosted/pub.dartlang.org/http-0.13.4/lib/src/response.dart').
3Try accessing using ?. instead.
4 return Text("${BTCPrice.fromJson(jsonDecode(snapshot.data.body)).eur}");
5 ^^^^
6/D:/flutter/packages/flutter/lib/src/widgets/async.dart:242:12: Context: 'data' refers to a property so it couldn't be promoted.
7See http://dart.dev/go/non-promo-property
8 final T? data;
9 ^
10import 'dart:convert';
11import 'package:flutter/cupertino.dart';
12import 'package:flutter/material.dart';
13import 'package:http/http.dart' as http;
14
15Future<http.Response> fetchBTCPrice() async {
16 final response = await http.get(Uri.https('blockhain.info', 'ticker'));
17 return response;
18}
19
20Widget buildBTCPrice() {
21 return FutureBuilder<http.Response>(
22 future: fetchBTCPrice(),
23 builder: (context, snapshot) {
24 if (snapshot.hasData) {
25 int? statusCode = snapshot.data?.statusCode;
26 if (statusCode == 200) {
27 return Text("${BTCPrice.fromJson(jsonDecode(snapshot.data.body)).eur}");
28 }
29 return Text('$statusCode');
30
31 } else if (snapshot.hasError) {
32 return Text('${snapshot.error}');
33 }
34 return CircularProgressIndicator();
35 },
36 );
37}
38
39class BTCPrice {
40 final double eur;
41 BTCPrice({required this.eur});
42
43 factory BTCPrice.fromJson(Map<String, dynamic> json) {
44 print(json);
45 return BTCPrice(
46 eur: json['eur']['15m']
47 );
48 }
49}
50
Last things to mention: I'am running the application on a Android Emulator powerd by Android Studio; and please feel free to hand over any advice you have (in terms of code improvement), even if it is not fixing my issue.
ANSWER
Answered 2022-Mar-29 at 00:29To get rid of that error you need to use the bang operator to tell the compiler that snapshot.data
won't be null.
1Error: Property 'body' cannot be accessed on 'Response?' because it is potentially null.
2 - 'Response' is from 'package:http/src/response.dart' ('/D:/flutter/.pub-cache/hosted/pub.dartlang.org/http-0.13.4/lib/src/response.dart').
3Try accessing using ?. instead.
4 return Text("${BTCPrice.fromJson(jsonDecode(snapshot.data.body)).eur}");
5 ^^^^
6/D:/flutter/packages/flutter/lib/src/widgets/async.dart:242:12: Context: 'data' refers to a property so it couldn't be promoted.
7See http://dart.dev/go/non-promo-property
8 final T? data;
9 ^
10import 'dart:convert';
11import 'package:flutter/cupertino.dart';
12import 'package:flutter/material.dart';
13import 'package:http/http.dart' as http;
14
15Future<http.Response> fetchBTCPrice() async {
16 final response = await http.get(Uri.https('blockhain.info', 'ticker'));
17 return response;
18}
19
20Widget buildBTCPrice() {
21 return FutureBuilder<http.Response>(
22 future: fetchBTCPrice(),
23 builder: (context, snapshot) {
24 if (snapshot.hasData) {
25 int? statusCode = snapshot.data?.statusCode;
26 if (statusCode == 200) {
27 return Text("${BTCPrice.fromJson(jsonDecode(snapshot.data.body)).eur}");
28 }
29 return Text('$statusCode');
30
31 } else if (snapshot.hasError) {
32 return Text('${snapshot.error}');
33 }
34 return CircularProgressIndicator();
35 },
36 );
37}
38
39class BTCPrice {
40 final double eur;
41 BTCPrice({required this.eur});
42
43 factory BTCPrice.fromJson(Map<String, dynamic> json) {
44 print(json);
45 return BTCPrice(
46 eur: json['eur']['15m']
47 );
48 }
49}
50if (statusCode == 200) {
51 return Text(
52 "${BTCPrice.fromJson(jsonDecode(snapshot.data!.body)).eur}"); // adding ! on data
53}
54
The unrelated error you mentioned in your comment:
unexpected character (at character 1) <html><head><title>loading...</title></head><body><script type='text/javasc... ^
would be fixed by changing your GET
request from this
1Error: Property 'body' cannot be accessed on 'Response?' because it is potentially null.
2 - 'Response' is from 'package:http/src/response.dart' ('/D:/flutter/.pub-cache/hosted/pub.dartlang.org/http-0.13.4/lib/src/response.dart').
3Try accessing using ?. instead.
4 return Text("${BTCPrice.fromJson(jsonDecode(snapshot.data.body)).eur}");
5 ^^^^
6/D:/flutter/packages/flutter/lib/src/widgets/async.dart:242:12: Context: 'data' refers to a property so it couldn't be promoted.
7See http://dart.dev/go/non-promo-property
8 final T? data;
9 ^
10import 'dart:convert';
11import 'package:flutter/cupertino.dart';
12import 'package:flutter/material.dart';
13import 'package:http/http.dart' as http;
14
15Future<http.Response> fetchBTCPrice() async {
16 final response = await http.get(Uri.https('blockhain.info', 'ticker'));
17 return response;
18}
19
20Widget buildBTCPrice() {
21 return FutureBuilder<http.Response>(
22 future: fetchBTCPrice(),
23 builder: (context, snapshot) {
24 if (snapshot.hasData) {
25 int? statusCode = snapshot.data?.statusCode;
26 if (statusCode == 200) {
27 return Text("${BTCPrice.fromJson(jsonDecode(snapshot.data.body)).eur}");
28 }
29 return Text('$statusCode');
30
31 } else if (snapshot.hasError) {
32 return Text('${snapshot.error}');
33 }
34 return CircularProgressIndicator();
35 },
36 );
37}
38
39class BTCPrice {
40 final double eur;
41 BTCPrice({required this.eur});
42
43 factory BTCPrice.fromJson(Map<String, dynamic> json) {
44 print(json);
45 return BTCPrice(
46 eur: json['eur']['15m']
47 );
48 }
49}
50if (statusCode == 200) {
51 return Text(
52 "${BTCPrice.fromJson(jsonDecode(snapshot.data!.body)).eur}"); // adding ! on data
53}
54final response = await http.get(Uri.https('blockhain.info', 'ticker'));
55
to this
1Error: Property 'body' cannot be accessed on 'Response?' because it is potentially null.
2 - 'Response' is from 'package:http/src/response.dart' ('/D:/flutter/.pub-cache/hosted/pub.dartlang.org/http-0.13.4/lib/src/response.dart').
3Try accessing using ?. instead.
4 return Text("${BTCPrice.fromJson(jsonDecode(snapshot.data.body)).eur}");
5 ^^^^
6/D:/flutter/packages/flutter/lib/src/widgets/async.dart:242:12: Context: 'data' refers to a property so it couldn't be promoted.
7See http://dart.dev/go/non-promo-property
8 final T? data;
9 ^
10import 'dart:convert';
11import 'package:flutter/cupertino.dart';
12import 'package:flutter/material.dart';
13import 'package:http/http.dart' as http;
14
15Future<http.Response> fetchBTCPrice() async {
16 final response = await http.get(Uri.https('blockhain.info', 'ticker'));
17 return response;
18}
19
20Widget buildBTCPrice() {
21 return FutureBuilder<http.Response>(
22 future: fetchBTCPrice(),
23 builder: (context, snapshot) {
24 if (snapshot.hasData) {
25 int? statusCode = snapshot.data?.statusCode;
26 if (statusCode == 200) {
27 return Text("${BTCPrice.fromJson(jsonDecode(snapshot.data.body)).eur}");
28 }
29 return Text('$statusCode');
30
31 } else if (snapshot.hasError) {
32 return Text('${snapshot.error}');
33 }
34 return CircularProgressIndicator();
35 },
36 );
37}
38
39class BTCPrice {
40 final double eur;
41 BTCPrice({required this.eur});
42
43 factory BTCPrice.fromJson(Map<String, dynamic> json) {
44 print(json);
45 return BTCPrice(
46 eur: json['eur']['15m']
47 );
48 }
49}
50if (statusCode == 200) {
51 return Text(
52 "${BTCPrice.fromJson(jsonDecode(snapshot.data!.body)).eur}"); // adding ! on data
53}
54final response = await http.get(Uri.https('blockhain.info', 'ticker'));
55final response = await http.get(Uri.parse('https://blockchain.info/ticker'));
56
QUESTION
How to send a web3 transaction from a test account of RSKj regtest blockchain node
Asked 2022-Mar-25 at 10:34I am creating a DApp that connects to a smart contract deployed on a local test RSK blockchain (regtest) run by RSKj Java app. I intend to send transactions via Web3 connected to Metamask. In DApp I am getting the accounts list by sending a Web3 request:
1const accounts = await web3.eth.getAccounts()
2
Further, accounts
will contain:
1const accounts = await web3.eth.getAccounts()
2[
3 '0xCD2a3d9F938E13CD947Ec05AbC7FE734Df8DD826',
4 '0x7986b3DF570230288501EEa3D890bd66948C9B79',
5 '0x0a3aA774752ec2042c46548456c094A76C7F3a79',
6 '0xCF7CDBbB5F7BA79d3ffe74A0bBA13FC0295F6036',
7 '0x39B12C05E8503356E3a7DF0B7B33efA4c054C409',
8 '0xc354D97642FAa06781b76Ffb6786f72cd7746C97',
9 '0xDEBe71E1dE41Fc77C44Df4b6Db940026E31b0e71',
10 '0x7857288e171C6159C5576d1bD9AC40c0c48a771C',
11 '0xa4Dea4d5C954f5FD9e87f0e9752911E83a3D18b3',
12 '0x09a1edA29F664ac8f68106F6567276dF0C65D859',
13 '0xeC4ddeB4380Ad69B3E509BaAd9f158CDF4E4681d'
14]
15
How do I import these accounts (or at least the first one of them) to Metamask in order to send transactions to the smart contract?
ANSWER
Answered 2022-Mar-25 at 10:34The first account from the list is referred as a “cow” seed in this file in RSKj. You can take the corresponding private key from there.
Do the following:
- copy the private key
c85ef7d79691fe79573b1a7064c19c1a9819ebdbd1faaab1a8ec92344438aaf4
, - open your Metamask browser plugin
- select
regtest
network - import the account
- Account icon in the upper right corner
- Import account
- ‘Paste your private key string here:’
- Set the just imported account as an active one
- Enjoy sending your transactions
QUESTION
How can I convert an [u8] hex ascii representation to a u64
Asked 2022-Mar-17 at 10:57I would like to convert my bytes array into a u64.
For example
b"00"
should return 0u64
b"0a"
should return 10u64
I am working on blockchain, so I must find something efficient.
For example, my current function is not efficient at all.
1let number_string = String::from_utf8_lossy(&my_bytes_array)
2 .to_owned()
3 .to_string();
4let number = u64::from_str_radix(&number_string , 16).unwrap();
5
I have also tried
1let number_string = String::from_utf8_lossy(&my_bytes_array)
2 .to_owned()
3 .to_string();
4let number = u64::from_str_radix(&number_string , 16).unwrap();
5let number = u64::from_le_bytes(my_bytes_array);
6
But I got this error mismatched types expected array [u8; 8], found &[u8]
ANSWER
Answered 2022-Mar-16 at 20:21How about?
1let number_string = String::from_utf8_lossy(&my_bytes_array)
2 .to_owned()
3 .to_string();
4let number = u64::from_str_radix(&number_string , 16).unwrap();
5let number = u64::from_le_bytes(my_bytes_array);
6pub fn hex_to_u64(x: &[u8]) -> Option<u64> {
7 let mut result: u64 = 0;
8 for i in x {
9 result *= 16;
10 result += (*i as char).to_digit(16)? as u64;
11 }
12 Some(result)
13}
14
QUESTION
The transaction declared chain ID 5777, but the connected node is on 1337
Asked 2022-Mar-11 at 02:52I am trying to deploy my SimpleStorage.sol contract to a ganache local chain by making a transaction using python. It seems to have trouble connecting to the chain.
1from solcx import compile_standard
2from web3 import Web3
3import json
4import os
5from dotenv import load_dotenv
6
7load_dotenv()
8
9with open("./SimpleStorage.sol", "r") as file:
10 simple_storage_file = file.read()
11
12compiled_sol = compile_standard(
13 {
14 "language": "Solidity",
15 "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
16 "settings": {
17 "outputSelection": {
18 "*": {"*": ["abi", "metadata", "evm.bytecode", "evm.sourceMap"]}
19 }
20 },
21 },
22 solc_version="0.6.0",
23)
24
25with open("compiled_code.json", "w") as file:
26 json.dump(compiled_sol, file)
27
28
29# get bytecode
30bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
31 "bytecode"
32]["object"]
33
34
35# get ABI
36abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"]
37
38# to connect to ganache blockchain
39w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:7545"))
40chain_id = 5777
41my_address = "0xca1EA31e644F13E3E36631382686fD471c62267A"
42private_key = os.getenv("PRIVATE_KEY")
43
44
45# create the contract in python
46
47SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)
48
49# get the latest transaction
50nonce = w3.eth.getTransactionCount(my_address)
51
52# 1. Build a transaction
53# 2. Sign a transaction
54# 3. Send a transaction
55
56
57transaction = SimpleStorage.constructor().buildTransaction(
58 {"chainId": chain_id, "from": my_address, "nonce": nonce}
59)
60print(transaction)
61
62
It seems to be connected to the ganache chain because it prints the nonce, but when I build and try to print the transaction here is the entire traceback call I am receiving
1from solcx import compile_standard
2from web3 import Web3
3import json
4import os
5from dotenv import load_dotenv
6
7load_dotenv()
8
9with open("./SimpleStorage.sol", "r") as file:
10 simple_storage_file = file.read()
11
12compiled_sol = compile_standard(
13 {
14 "language": "Solidity",
15 "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
16 "settings": {
17 "outputSelection": {
18 "*": {"*": ["abi", "metadata", "evm.bytecode", "evm.sourceMap"]}
19 }
20 },
21 },
22 solc_version="0.6.0",
23)
24
25with open("compiled_code.json", "w") as file:
26 json.dump(compiled_sol, file)
27
28
29# get bytecode
30bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
31 "bytecode"
32]["object"]
33
34
35# get ABI
36abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"]
37
38# to connect to ganache blockchain
39w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:7545"))
40chain_id = 5777
41my_address = "0xca1EA31e644F13E3E36631382686fD471c62267A"
42private_key = os.getenv("PRIVATE_KEY")
43
44
45# create the contract in python
46
47SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)
48
49# get the latest transaction
50nonce = w3.eth.getTransactionCount(my_address)
51
52# 1. Build a transaction
53# 2. Sign a transaction
54# 3. Send a transaction
55
56
57transaction = SimpleStorage.constructor().buildTransaction(
58 {"chainId": chain_id, "from": my_address, "nonce": nonce}
59)
60print(transaction)
61
62Traceback (most recent call last):
63File "C:\Users\evens\demos\web3_py_simple_storage\deploy.py", line
6452, in <module>
65transaction = SimpleStorage.constructor().buildTransaction(
66File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line
6718, in _wrapper
68return self.method(obj, *args, **kwargs)
69File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
70packages\web3\contract.py", line 684, in buildTransaction
71return fill_transaction_defaults(self.web3, built_transaction)
72File "cytoolz/functoolz.pyx", line 250, in
73cytoolz.functoolz.curry.__call__
74return self.func(*args, **kwargs)
75File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
76packages\web3\_utils\transactions.py", line 114, in
77fill_transaction_defaults
78default_val = default_getter(web3, transaction)
79File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
80packages\web3\_utils\transactions.py", line 60, in <lambda>
81'gas': lambda web3, tx: web3.eth.estimate_gas(tx),
82File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
83packages\web3\eth.py", line 820, in estimate_gas
84return self._estimate_gas(transaction, block_identifier)
85File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
86packages\web3\module.py", line 57, in caller
87result = w3.manager.request_blocking(method_str,
88File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
89packages\web3\manager.py", line 197, in request_blocking
90response = self._make_request(method, params)
91File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
92packages\web3\manager.py", line 150, in _make_request
93return request_func(method, params)
94File "cytoolz/functoolz.pyx", line 250, in
95cytoolz.functoolz.curry.__call__
96return self.func(*args, **kwargs)
97File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
98packages\web3\middleware\formatting.py", line 76, in
99apply_formatters
100response = make_request(method, params)
101File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
102packages\web3\middleware\gas_price_strategy.py", line 90, in
103middleware
104return make_request(method, params)
105File "cytoolz/functoolz.pyx", line 250, in
106cytoolz.functoolz.curry.__call__
107return self.func(*args, **kwargs)
108File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
109packages\web3\middleware\formatting.py", line 74, in
110apply_formatters
111response = make_request(method, formatted_params)
112File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
113packages\web3\middleware\attrdict.py", line 33, in middleware
114response = make_request(method, params)
115File "cytoolz/functoolz.pyx", line 250, in
116cytoolz.functoolz.curry.__call__
117return self.func(*args, **kwargs)
118File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
119packages\web3\middleware\formatting.py", line 74, in
120apply_formatters
121response = make_request(method, formatted_params)
122File "cytoolz/functoolz.pyx", line 250, in
123cytoolz.functoolz.curry.__call__
124return self.func(*args, **kwargs)
125File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
126packages\web3\middleware\formatting.py", line 73, in
127apply_formatters
128formatted_params = formatter(params)
129File "cytoolz/functoolz.pyx", line 503, in
130cytoolz.functoolz.Compose.__call__
131ret = PyObject_Call(self.first, args, kwargs)
132File "cytoolz/functoolz.pyx", line 250, in
133cytoolz.functoolz.curry.__call__
134return self.func(*args, **kwargs)
135File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line
13691, in wrapper
137return ReturnType(result) # type: ignore
138File "C:\Python310\lib\site-packages\eth_utils\applicators.py", line
13922, in apply_formatter_at_index
140yield formatter(item)
141File "cytoolz/functoolz.pyx", line 250, in
142cytoolz.functoolz.curry.__call__
143File "cytoolz/functoolz.pyx", line 250, in
144cytoolz.functoolz.curry.__call__
145return self.func(*args, **kwargs)
146File "C:\Python310\lib\site-packages\eth_utils\applicators.py", line
14772, in apply_formatter_if
148return formatter(value)
149File "cytoolz/functoolz.pyx", line 250, in
150cytoolz.functoolz.curry.__call__
151return self.func(*args, **kwargs)
152File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
153packages\web3\middleware\validation.py", line 57, in
154validate_chain_id
155raise ValidationError(
156web3.exceptions.ValidationError: The transaction declared chain ID
1575777, but the connected node is on 1337
158
ANSWER
Answered 2022-Jan-17 at 18:17Had this issue myself, apparently it's some sort of Ganache CLI error but the simplest fix I could find was to change the network id in Ganache through settings>server to 1337. It restarts the session so you'd then need to change the address and private key variable.
If it's the same tutorial I'm doing, you're likely to come unstuck after this... the code for transaction should be:
1from solcx import compile_standard
2from web3 import Web3
3import json
4import os
5from dotenv import load_dotenv
6
7load_dotenv()
8
9with open("./SimpleStorage.sol", "r") as file:
10 simple_storage_file = file.read()
11
12compiled_sol = compile_standard(
13 {
14 "language": "Solidity",
15 "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
16 "settings": {
17 "outputSelection": {
18 "*": {"*": ["abi", "metadata", "evm.bytecode", "evm.sourceMap"]}
19 }
20 },
21 },
22 solc_version="0.6.0",
23)
24
25with open("compiled_code.json", "w") as file:
26 json.dump(compiled_sol, file)
27
28
29# get bytecode
30bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
31 "bytecode"
32]["object"]
33
34
35# get ABI
36abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"]
37
38# to connect to ganache blockchain
39w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:7545"))
40chain_id = 5777
41my_address = "0xca1EA31e644F13E3E36631382686fD471c62267A"
42private_key = os.getenv("PRIVATE_KEY")
43
44
45# create the contract in python
46
47SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)
48
49# get the latest transaction
50nonce = w3.eth.getTransactionCount(my_address)
51
52# 1. Build a transaction
53# 2. Sign a transaction
54# 3. Send a transaction
55
56
57transaction = SimpleStorage.constructor().buildTransaction(
58 {"chainId": chain_id, "from": my_address, "nonce": nonce}
59)
60print(transaction)
61
62Traceback (most recent call last):
63File "C:\Users\evens\demos\web3_py_simple_storage\deploy.py", line
6452, in <module>
65transaction = SimpleStorage.constructor().buildTransaction(
66File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line
6718, in _wrapper
68return self.method(obj, *args, **kwargs)
69File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
70packages\web3\contract.py", line 684, in buildTransaction
71return fill_transaction_defaults(self.web3, built_transaction)
72File "cytoolz/functoolz.pyx", line 250, in
73cytoolz.functoolz.curry.__call__
74return self.func(*args, **kwargs)
75File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
76packages\web3\_utils\transactions.py", line 114, in
77fill_transaction_defaults
78default_val = default_getter(web3, transaction)
79File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
80packages\web3\_utils\transactions.py", line 60, in <lambda>
81'gas': lambda web3, tx: web3.eth.estimate_gas(tx),
82File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
83packages\web3\eth.py", line 820, in estimate_gas
84return self._estimate_gas(transaction, block_identifier)
85File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
86packages\web3\module.py", line 57, in caller
87result = w3.manager.request_blocking(method_str,
88File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
89packages\web3\manager.py", line 197, in request_blocking
90response = self._make_request(method, params)
91File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
92packages\web3\manager.py", line 150, in _make_request
93return request_func(method, params)
94File "cytoolz/functoolz.pyx", line 250, in
95cytoolz.functoolz.curry.__call__
96return self.func(*args, **kwargs)
97File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
98packages\web3\middleware\formatting.py", line 76, in
99apply_formatters
100response = make_request(method, params)
101File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
102packages\web3\middleware\gas_price_strategy.py", line 90, in
103middleware
104return make_request(method, params)
105File "cytoolz/functoolz.pyx", line 250, in
106cytoolz.functoolz.curry.__call__
107return self.func(*args, **kwargs)
108File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
109packages\web3\middleware\formatting.py", line 74, in
110apply_formatters
111response = make_request(method, formatted_params)
112File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
113packages\web3\middleware\attrdict.py", line 33, in middleware
114response = make_request(method, params)
115File "cytoolz/functoolz.pyx", line 250, in
116cytoolz.functoolz.curry.__call__
117return self.func(*args, **kwargs)
118File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
119packages\web3\middleware\formatting.py", line 74, in
120apply_formatters
121response = make_request(method, formatted_params)
122File "cytoolz/functoolz.pyx", line 250, in
123cytoolz.functoolz.curry.__call__
124return self.func(*args, **kwargs)
125File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
126packages\web3\middleware\formatting.py", line 73, in
127apply_formatters
128formatted_params = formatter(params)
129File "cytoolz/functoolz.pyx", line 503, in
130cytoolz.functoolz.Compose.__call__
131ret = PyObject_Call(self.first, args, kwargs)
132File "cytoolz/functoolz.pyx", line 250, in
133cytoolz.functoolz.curry.__call__
134return self.func(*args, **kwargs)
135File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line
13691, in wrapper
137return ReturnType(result) # type: ignore
138File "C:\Python310\lib\site-packages\eth_utils\applicators.py", line
13922, in apply_formatter_at_index
140yield formatter(item)
141File "cytoolz/functoolz.pyx", line 250, in
142cytoolz.functoolz.curry.__call__
143File "cytoolz/functoolz.pyx", line 250, in
144cytoolz.functoolz.curry.__call__
145return self.func(*args, **kwargs)
146File "C:\Python310\lib\site-packages\eth_utils\applicators.py", line
14772, in apply_formatter_if
148return formatter(value)
149File "cytoolz/functoolz.pyx", line 250, in
150cytoolz.functoolz.curry.__call__
151return self.func(*args, **kwargs)
152File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
153packages\web3\middleware\validation.py", line 57, in
154validate_chain_id
155raise ValidationError(
156web3.exceptions.ValidationError: The transaction declared chain ID
1575777, but the connected node is on 1337
158transaction =
159 SimpleStorage.constructor().buildTransaction( {
160 "gasPrice": w3.eth.gas_price,
161 "chainId": chain_id,
162 "from": my_address,
163 "nonce": nonce,
164})
165print(transaction)
166
Otherwise you get a value error if you don't set the gasPrice
QUESTION
How to locally unit-test Chainlink's Verifiable Random Function?
Asked 2022-Mar-08 at 04:12While trying to set up a basic self-hosted unit testing environment (and CI) that tests this Chainlink VRF random number contract, I am experiencing slight difficulties in how to simulate any relevant blockchains/testnets locally.
For example, I found this repository that tests Chainlinks VRF. However, for default deployment it suggests/requires a free KOVAN_RPC_URL
e.g. from Infura's site and even for "local deployment" it suggests/requires a free MAINNET_RPC_URL
from e.g. Alchemy's site.
I adopted a unit test environment from the waffle framework which is described as:
Filestructure1src____AmIRichAlready.sol
2 |____RandomNumberConsumer.sol
3 |
4test____AmIRichAlready.test.ts
5 |____mocha.opts
6package.json
7tsconfig.json
8waffle.json
9yarn.lock
10
AmIRichAlready.sol
1src____AmIRichAlready.sol
2 |____RandomNumberConsumer.sol
3 |
4test____AmIRichAlready.test.ts
5 |____mocha.opts
6package.json
7tsconfig.json
8waffle.json
9yarn.lock
10pragma solidity ^0.6.2;
11
12interface IERC20 {
13 function balanceOf(address account) external view returns (uint256);
14}
15
16contract AmIRichAlready {
17 IERC20 private tokenContract;
18 uint public richness = 1000000 * 10 ** 18;
19
20 constructor (IERC20 _tokenContract) public {
21 tokenContract = _tokenContract;
22 }
23
24 function check() public view returns (bool) {
25 uint balance = tokenContract.balanceOf(msg.sender);
26 return balance > richness;
27 }
28
29 // IS THIS NEEDED???
30 function setRichness(uint256 _richness) public {
31 richness = _richness;
32 }
33}
34
The RandomNumberConsumer.sol
filecontent is already on stackexange over here.
AmIRichAlready.test.ts
1src____AmIRichAlready.sol
2 |____RandomNumberConsumer.sol
3 |
4test____AmIRichAlready.test.ts
5 |____mocha.opts
6package.json
7tsconfig.json
8waffle.json
9yarn.lock
10pragma solidity ^0.6.2;
11
12interface IERC20 {
13 function balanceOf(address account) external view returns (uint256);
14}
15
16contract AmIRichAlready {
17 IERC20 private tokenContract;
18 uint public richness = 1000000 * 10 ** 18;
19
20 constructor (IERC20 _tokenContract) public {
21 tokenContract = _tokenContract;
22 }
23
24 function check() public view returns (bool) {
25 uint balance = tokenContract.balanceOf(msg.sender);
26 return balance > richness;
27 }
28
29 // IS THIS NEEDED???
30 function setRichness(uint256 _richness) public {
31 richness = _richness;
32 }
33}
34import {expect, use} from 'chai';
35import {Contract, utils, Wallet} from 'ethers';
36import {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';
37
38import IERC20 from '../build/IERC20.json';
39import AmIRichAlready from '../build/AmIRichAlready.json';
40
41use(solidity);
42
43describe('Am I Rich Already', () => {
44 let mockERC20: Contract;
45 let contract: Contract;
46 let vrfContract: Contract;
47 let wallet: Wallet;
48
49 beforeEach(async () => {
50 [wallet] = new MockProvider().getWallets();
51 mockERC20 = await deployMockContract(wallet, IERC20.abi);
52 contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);
53 vrfContract = await deployContract(wallet, RandomNumberConsumer);
54 });
55
56 it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () => {
57 await mockERC20.mock.balanceOf
58 .withArgs(wallet.address)
59 .returns(utils.parseEther('999999'));
60 await contract.check();
61 expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);
62 });
63
64 it('returns false if the wallet has less than 1000000 coins', async () => {
65 await mockERC20.mock.balanceOf
66 .withArgs(wallet.address)
67 .returns(utils.parseEther('999999'));
68 expect(await contract.check()).to.be.equal(false);
69 });
70
71 it('returns true if the wallet has at least 1000000 coins', async () => {
72 await mockERC20.mock.balanceOf
73 .withArgs(wallet.address)
74 .returns(utils.parseEther('1000000'));
75 expect(await contract.check()).to.be.equal(false);
76 });
77});
78
mocha.opts
1src____AmIRichAlready.sol
2 |____RandomNumberConsumer.sol
3 |
4test____AmIRichAlready.test.ts
5 |____mocha.opts
6package.json
7tsconfig.json
8waffle.json
9yarn.lock
10pragma solidity ^0.6.2;
11
12interface IERC20 {
13 function balanceOf(address account) external view returns (uint256);
14}
15
16contract AmIRichAlready {
17 IERC20 private tokenContract;
18 uint public richness = 1000000 * 10 ** 18;
19
20 constructor (IERC20 _tokenContract) public {
21 tokenContract = _tokenContract;
22 }
23
24 function check() public view returns (bool) {
25 uint balance = tokenContract.balanceOf(msg.sender);
26 return balance > richness;
27 }
28
29 // IS THIS NEEDED???
30 function setRichness(uint256 _richness) public {
31 richness = _richness;
32 }
33}
34import {expect, use} from 'chai';
35import {Contract, utils, Wallet} from 'ethers';
36import {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';
37
38import IERC20 from '../build/IERC20.json';
39import AmIRichAlready from '../build/AmIRichAlready.json';
40
41use(solidity);
42
43describe('Am I Rich Already', () => {
44 let mockERC20: Contract;
45 let contract: Contract;
46 let vrfContract: Contract;
47 let wallet: Wallet;
48
49 beforeEach(async () => {
50 [wallet] = new MockProvider().getWallets();
51 mockERC20 = await deployMockContract(wallet, IERC20.abi);
52 contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);
53 vrfContract = await deployContract(wallet, RandomNumberConsumer);
54 });
55
56 it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () => {
57 await mockERC20.mock.balanceOf
58 .withArgs(wallet.address)
59 .returns(utils.parseEther('999999'));
60 await contract.check();
61 expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);
62 });
63
64 it('returns false if the wallet has less than 1000000 coins', async () => {
65 await mockERC20.mock.balanceOf
66 .withArgs(wallet.address)
67 .returns(utils.parseEther('999999'));
68 expect(await contract.check()).to.be.equal(false);
69 });
70
71 it('returns true if the wallet has at least 1000000 coins', async () => {
72 await mockERC20.mock.balanceOf
73 .withArgs(wallet.address)
74 .returns(utils.parseEther('1000000'));
75 expect(await contract.check()).to.be.equal(false);
76 });
77});
78-r ts-node/register/transpile-only
79--timeout 50000
80--no-warnings
81test/**/*.test.{js,ts}
82
package.json
1src____AmIRichAlready.sol
2 |____RandomNumberConsumer.sol
3 |
4test____AmIRichAlready.test.ts
5 |____mocha.opts
6package.json
7tsconfig.json
8waffle.json
9yarn.lock
10pragma solidity ^0.6.2;
11
12interface IERC20 {
13 function balanceOf(address account) external view returns (uint256);
14}
15
16contract AmIRichAlready {
17 IERC20 private tokenContract;
18 uint public richness = 1000000 * 10 ** 18;
19
20 constructor (IERC20 _tokenContract) public {
21 tokenContract = _tokenContract;
22 }
23
24 function check() public view returns (bool) {
25 uint balance = tokenContract.balanceOf(msg.sender);
26 return balance > richness;
27 }
28
29 // IS THIS NEEDED???
30 function setRichness(uint256 _richness) public {
31 richness = _richness;
32 }
33}
34import {expect, use} from 'chai';
35import {Contract, utils, Wallet} from 'ethers';
36import {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';
37
38import IERC20 from '../build/IERC20.json';
39import AmIRichAlready from '../build/AmIRichAlready.json';
40
41use(solidity);
42
43describe('Am I Rich Already', () => {
44 let mockERC20: Contract;
45 let contract: Contract;
46 let vrfContract: Contract;
47 let wallet: Wallet;
48
49 beforeEach(async () => {
50 [wallet] = new MockProvider().getWallets();
51 mockERC20 = await deployMockContract(wallet, IERC20.abi);
52 contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);
53 vrfContract = await deployContract(wallet, RandomNumberConsumer);
54 });
55
56 it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () => {
57 await mockERC20.mock.balanceOf
58 .withArgs(wallet.address)
59 .returns(utils.parseEther('999999'));
60 await contract.check();
61 expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);
62 });
63
64 it('returns false if the wallet has less than 1000000 coins', async () => {
65 await mockERC20.mock.balanceOf
66 .withArgs(wallet.address)
67 .returns(utils.parseEther('999999'));
68 expect(await contract.check()).to.be.equal(false);
69 });
70
71 it('returns true if the wallet has at least 1000000 coins', async () => {
72 await mockERC20.mock.balanceOf
73 .withArgs(wallet.address)
74 .returns(utils.parseEther('1000000'));
75 expect(await contract.check()).to.be.equal(false);
76 });
77});
78-r ts-node/register/transpile-only
79--timeout 50000
80--no-warnings
81test/**/*.test.{js,ts}
82{
83 "name": "example-dynamic-mocking-and-testing-calls",
84 "version": "1.0.0",
85 "main": "index.js",
86 "license": "MIT",
87 "scripts": {
88 "test": "export NODE_ENV=test && mocha",
89 "build": "waffle",
90 "lint": "eslint '{src,test}/**/*.ts'",
91 "lint:fix": "eslint --fix '{src,test}/**/*.ts'"
92 },
93 "devDependencies": {
94 "@openzeppelin/contracts": "^4.3.1",
95 "@types/chai": "^4.2.3",
96 "@types/mocha": "^5.2.7",
97 "@typescript-eslint/eslint-plugin": "^2.30.0",
98 "@typescript-eslint/parser": "^2.30.0",
99 "chai": "^4.3.4",
100 "eslint": "^6.8.0",
101 "eslint-plugin-import": "^2.20.2",
102 "ethereum-waffle": "^3.4.0",
103 "ethers": "^5.0.17",
104 "mocha": "^7.2.0",
105 "ts-node": "^8.9.1",
106 "typescript": "^3.8.3"
107 }
108}
109
tsconfig.json
1src____AmIRichAlready.sol
2 |____RandomNumberConsumer.sol
3 |
4test____AmIRichAlready.test.ts
5 |____mocha.opts
6package.json
7tsconfig.json
8waffle.json
9yarn.lock
10pragma solidity ^0.6.2;
11
12interface IERC20 {
13 function balanceOf(address account) external view returns (uint256);
14}
15
16contract AmIRichAlready {
17 IERC20 private tokenContract;
18 uint public richness = 1000000 * 10 ** 18;
19
20 constructor (IERC20 _tokenContract) public {
21 tokenContract = _tokenContract;
22 }
23
24 function check() public view returns (bool) {
25 uint balance = tokenContract.balanceOf(msg.sender);
26 return balance > richness;
27 }
28
29 // IS THIS NEEDED???
30 function setRichness(uint256 _richness) public {
31 richness = _richness;
32 }
33}
34import {expect, use} from 'chai';
35import {Contract, utils, Wallet} from 'ethers';
36import {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';
37
38import IERC20 from '../build/IERC20.json';
39import AmIRichAlready from '../build/AmIRichAlready.json';
40
41use(solidity);
42
43describe('Am I Rich Already', () => {
44 let mockERC20: Contract;
45 let contract: Contract;
46 let vrfContract: Contract;
47 let wallet: Wallet;
48
49 beforeEach(async () => {
50 [wallet] = new MockProvider().getWallets();
51 mockERC20 = await deployMockContract(wallet, IERC20.abi);
52 contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);
53 vrfContract = await deployContract(wallet, RandomNumberConsumer);
54 });
55
56 it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () => {
57 await mockERC20.mock.balanceOf
58 .withArgs(wallet.address)
59 .returns(utils.parseEther('999999'));
60 await contract.check();
61 expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);
62 });
63
64 it('returns false if the wallet has less than 1000000 coins', async () => {
65 await mockERC20.mock.balanceOf
66 .withArgs(wallet.address)
67 .returns(utils.parseEther('999999'));
68 expect(await contract.check()).to.be.equal(false);
69 });
70
71 it('returns true if the wallet has at least 1000000 coins', async () => {
72 await mockERC20.mock.balanceOf
73 .withArgs(wallet.address)
74 .returns(utils.parseEther('1000000'));
75 expect(await contract.check()).to.be.equal(false);
76 });
77});
78-r ts-node/register/transpile-only
79--timeout 50000
80--no-warnings
81test/**/*.test.{js,ts}
82{
83 "name": "example-dynamic-mocking-and-testing-calls",
84 "version": "1.0.0",
85 "main": "index.js",
86 "license": "MIT",
87 "scripts": {
88 "test": "export NODE_ENV=test && mocha",
89 "build": "waffle",
90 "lint": "eslint '{src,test}/**/*.ts'",
91 "lint:fix": "eslint --fix '{src,test}/**/*.ts'"
92 },
93 "devDependencies": {
94 "@openzeppelin/contracts": "^4.3.1",
95 "@types/chai": "^4.2.3",
96 "@types/mocha": "^5.2.7",
97 "@typescript-eslint/eslint-plugin": "^2.30.0",
98 "@typescript-eslint/parser": "^2.30.0",
99 "chai": "^4.3.4",
100 "eslint": "^6.8.0",
101 "eslint-plugin-import": "^2.20.2",
102 "ethereum-waffle": "^3.4.0",
103 "ethers": "^5.0.17",
104 "mocha": "^7.2.0",
105 "ts-node": "^8.9.1",
106 "typescript": "^3.8.3"
107 }
108}
109{
110 "compilerOptions": {
111 "declaration": true,
112 "esModuleInterop": true,
113 "lib": [
114 "ES2018"
115 ],
116 "module": "CommonJS",
117 "moduleResolution": "node",
118 "outDir": "dist",
119 "resolveJsonModule": true,
120 "skipLibCheck": true,
121 "strict": true,
122 "target": "ES2018"
123 }
124
125 // custom test in vrfContract
126 it('Tests if a random number is returned', async () => {
127 expect(await vrfContract.getRandomNumber()).to.be.equal(7);
128 });
129}
130
waffle.json
1src____AmIRichAlready.sol
2 |____RandomNumberConsumer.sol
3 |
4test____AmIRichAlready.test.ts
5 |____mocha.opts
6package.json
7tsconfig.json
8waffle.json
9yarn.lock
10pragma solidity ^0.6.2;
11
12interface IERC20 {
13 function balanceOf(address account) external view returns (uint256);
14}
15
16contract AmIRichAlready {
17 IERC20 private tokenContract;
18 uint public richness = 1000000 * 10 ** 18;
19
20 constructor (IERC20 _tokenContract) public {
21 tokenContract = _tokenContract;
22 }
23
24 function check() public view returns (bool) {
25 uint balance = tokenContract.balanceOf(msg.sender);
26 return balance > richness;
27 }
28
29 // IS THIS NEEDED???
30 function setRichness(uint256 _richness) public {
31 richness = _richness;
32 }
33}
34import {expect, use} from 'chai';
35import {Contract, utils, Wallet} from 'ethers';
36import {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';
37
38import IERC20 from '../build/IERC20.json';
39import AmIRichAlready from '../build/AmIRichAlready.json';
40
41use(solidity);
42
43describe('Am I Rich Already', () => {
44 let mockERC20: Contract;
45 let contract: Contract;
46 let vrfContract: Contract;
47 let wallet: Wallet;
48
49 beforeEach(async () => {
50 [wallet] = new MockProvider().getWallets();
51 mockERC20 = await deployMockContract(wallet, IERC20.abi);
52 contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);
53 vrfContract = await deployContract(wallet, RandomNumberConsumer);
54 });
55
56 it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () => {
57 await mockERC20.mock.balanceOf
58 .withArgs(wallet.address)
59 .returns(utils.parseEther('999999'));
60 await contract.check();
61 expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);
62 });
63
64 it('returns false if the wallet has less than 1000000 coins', async () => {
65 await mockERC20.mock.balanceOf
66 .withArgs(wallet.address)
67 .returns(utils.parseEther('999999'));
68 expect(await contract.check()).to.be.equal(false);
69 });
70
71 it('returns true if the wallet has at least 1000000 coins', async () => {
72 await mockERC20.mock.balanceOf
73 .withArgs(wallet.address)
74 .returns(utils.parseEther('1000000'));
75 expect(await contract.check()).to.be.equal(false);
76 });
77});
78-r ts-node/register/transpile-only
79--timeout 50000
80--no-warnings
81test/**/*.test.{js,ts}
82{
83 "name": "example-dynamic-mocking-and-testing-calls",
84 "version": "1.0.0",
85 "main": "index.js",
86 "license": "MIT",
87 "scripts": {
88 "test": "export NODE_ENV=test && mocha",
89 "build": "waffle",
90 "lint": "eslint '{src,test}/**/*.ts'",
91 "lint:fix": "eslint --fix '{src,test}/**/*.ts'"
92 },
93 "devDependencies": {
94 "@openzeppelin/contracts": "^4.3.1",
95 "@types/chai": "^4.2.3",
96 "@types/mocha": "^5.2.7",
97 "@typescript-eslint/eslint-plugin": "^2.30.0",
98 "@typescript-eslint/parser": "^2.30.0",
99 "chai": "^4.3.4",
100 "eslint": "^6.8.0",
101 "eslint-plugin-import": "^2.20.2",
102 "ethereum-waffle": "^3.4.0",
103 "ethers": "^5.0.17",
104 "mocha": "^7.2.0",
105 "ts-node": "^8.9.1",
106 "typescript": "^3.8.3"
107 }
108}
109{
110 "compilerOptions": {
111 "declaration": true,
112 "esModuleInterop": true,
113 "lib": [
114 "ES2018"
115 ],
116 "module": "CommonJS",
117 "moduleResolution": "node",
118 "outDir": "dist",
119 "resolveJsonModule": true,
120 "skipLibCheck": true,
121 "strict": true,
122 "target": "ES2018"
123 }
124
125 // custom test in vrfContract
126 it('Tests if a random number is returned', async () => {
127 expect(await vrfContract.getRandomNumber()).to.be.equal(7);
128 });
129}
130{
131 "compilerType": "solcjs",
132 "compilerVersion": "0.6.2",
133 "sourceDirectory": "./src",
134 "outputDirectory": "./build"
135}
136
The yarn.lock
file content is a bit large, and it's auto-generated, so you can find it on the Waffle framework repository. Similarly, the package.json
can be found here, in the same repository.
One can also simply clone the repo with the specified filestructure here, and run the tests with the following commands:
1src____AmIRichAlready.sol
2 |____RandomNumberConsumer.sol
3 |
4test____AmIRichAlready.test.ts
5 |____mocha.opts
6package.json
7tsconfig.json
8waffle.json
9yarn.lock
10pragma solidity ^0.6.2;
11
12interface IERC20 {
13 function balanceOf(address account) external view returns (uint256);
14}
15
16contract AmIRichAlready {
17 IERC20 private tokenContract;
18 uint public richness = 1000000 * 10 ** 18;
19
20 constructor (IERC20 _tokenContract) public {
21 tokenContract = _tokenContract;
22 }
23
24 function check() public view returns (bool) {
25 uint balance = tokenContract.balanceOf(msg.sender);
26 return balance > richness;
27 }
28
29 // IS THIS NEEDED???
30 function setRichness(uint256 _richness) public {
31 richness = _richness;
32 }
33}
34import {expect, use} from 'chai';
35import {Contract, utils, Wallet} from 'ethers';
36import {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';
37
38import IERC20 from '../build/IERC20.json';
39import AmIRichAlready from '../build/AmIRichAlready.json';
40
41use(solidity);
42
43describe('Am I Rich Already', () => {
44 let mockERC20: Contract;
45 let contract: Contract;
46 let vrfContract: Contract;
47 let wallet: Wallet;
48
49 beforeEach(async () => {
50 [wallet] = new MockProvider().getWallets();
51 mockERC20 = await deployMockContract(wallet, IERC20.abi);
52 contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);
53 vrfContract = await deployContract(wallet, RandomNumberConsumer);
54 });
55
56 it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () => {
57 await mockERC20.mock.balanceOf
58 .withArgs(wallet.address)
59 .returns(utils.parseEther('999999'));
60 await contract.check();
61 expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);
62 });
63
64 it('returns false if the wallet has less than 1000000 coins', async () => {
65 await mockERC20.mock.balanceOf
66 .withArgs(wallet.address)
67 .returns(utils.parseEther('999999'));
68 expect(await contract.check()).to.be.equal(false);
69 });
70
71 it('returns true if the wallet has at least 1000000 coins', async () => {
72 await mockERC20.mock.balanceOf
73 .withArgs(wallet.address)
74 .returns(utils.parseEther('1000000'));
75 expect(await contract.check()).to.be.equal(false);
76 });
77});
78-r ts-node/register/transpile-only
79--timeout 50000
80--no-warnings
81test/**/*.test.{js,ts}
82{
83 "name": "example-dynamic-mocking-and-testing-calls",
84 "version": "1.0.0",
85 "main": "index.js",
86 "license": "MIT",
87 "scripts": {
88 "test": "export NODE_ENV=test && mocha",
89 "build": "waffle",
90 "lint": "eslint '{src,test}/**/*.ts'",
91 "lint:fix": "eslint --fix '{src,test}/**/*.ts'"
92 },
93 "devDependencies": {
94 "@openzeppelin/contracts": "^4.3.1",
95 "@types/chai": "^4.2.3",
96 "@types/mocha": "^5.2.7",
97 "@typescript-eslint/eslint-plugin": "^2.30.0",
98 "@typescript-eslint/parser": "^2.30.0",
99 "chai": "^4.3.4",
100 "eslint": "^6.8.0",
101 "eslint-plugin-import": "^2.20.2",
102 "ethereum-waffle": "^3.4.0",
103 "ethers": "^5.0.17",
104 "mocha": "^7.2.0",
105 "ts-node": "^8.9.1",
106 "typescript": "^3.8.3"
107 }
108}
109{
110 "compilerOptions": {
111 "declaration": true,
112 "esModuleInterop": true,
113 "lib": [
114 "ES2018"
115 ],
116 "module": "CommonJS",
117 "moduleResolution": "node",
118 "outDir": "dist",
119 "resolveJsonModule": true,
120 "skipLibCheck": true,
121 "strict": true,
122 "target": "ES2018"
123 }
124
125 // custom test in vrfContract
126 it('Tests if a random number is returned', async () => {
127 expect(await vrfContract.getRandomNumber()).to.be.equal(7);
128 });
129}
130{
131 "compilerType": "solcjs",
132 "compilerVersion": "0.6.2",
133 "sourceDirectory": "./src",
134 "outputDirectory": "./build"
135}
136git clone git@github.com:a-t-2/chainlink.git
137git clone git@github.com:a-t-2/test_vrf3.git
138cd test_vrf3
139sudo apt install npm
140npm install
141npm audit fix
142npm install --save-dev ethereum-waffle
143npm install @openzeppelin/contracts -D
144npm i chai -D
145npm i mocha -D
146rm -r build
147npx waffle
148npx mocha
149npm test
150
This will test the AmIRichAlready.sol
file and output:
1src____AmIRichAlready.sol
2 |____RandomNumberConsumer.sol
3 |
4test____AmIRichAlready.test.ts
5 |____mocha.opts
6package.json
7tsconfig.json
8waffle.json
9yarn.lock
10pragma solidity ^0.6.2;
11
12interface IERC20 {
13 function balanceOf(address account) external view returns (uint256);
14}
15
16contract AmIRichAlready {
17 IERC20 private tokenContract;
18 uint public richness = 1000000 * 10 ** 18;
19
20 constructor (IERC20 _tokenContract) public {
21 tokenContract = _tokenContract;
22 }
23
24 function check() public view returns (bool) {
25 uint balance = tokenContract.balanceOf(msg.sender);
26 return balance > richness;
27 }
28
29 // IS THIS NEEDED???
30 function setRichness(uint256 _richness) public {
31 richness = _richness;
32 }
33}
34import {expect, use} from 'chai';
35import {Contract, utils, Wallet} from 'ethers';
36import {deployContract, deployMockContract, MockProvider, solidity} from 'ethereum-waffle';
37
38import IERC20 from '../build/IERC20.json';
39import AmIRichAlready from '../build/AmIRichAlready.json';
40
41use(solidity);
42
43describe('Am I Rich Already', () => {
44 let mockERC20: Contract;
45 let contract: Contract;
46 let vrfContract: Contract;
47 let wallet: Wallet;
48
49 beforeEach(async () => {
50 [wallet] = new MockProvider().getWallets();
51 mockERC20 = await deployMockContract(wallet, IERC20.abi);
52 contract = await deployContract(wallet, AmIRichAlready, [mockERC20.address]);
53 vrfContract = await deployContract(wallet, RandomNumberConsumer);
54 });
55
56 it('checks if contract called balanceOf with certain wallet on the ERC20 token', async () => {
57 await mockERC20.mock.balanceOf
58 .withArgs(wallet.address)
59 .returns(utils.parseEther('999999'));
60 await contract.check();
61 expect('balanceOf').to.be.calledOnContractWith(mockERC20, [wallet.address]);
62 });
63
64 it('returns false if the wallet has less than 1000000 coins', async () => {
65 await mockERC20.mock.balanceOf
66 .withArgs(wallet.address)
67 .returns(utils.parseEther('999999'));
68 expect(await contract.check()).to.be.equal(false);
69 });
70
71 it('returns true if the wallet has at least 1000000 coins', async () => {
72 await mockERC20.mock.balanceOf
73 .withArgs(wallet.address)
74 .returns(utils.parseEther('1000000'));
75 expect(await contract.check()).to.be.equal(false);
76 });
77});
78-r ts-node/register/transpile-only
79--timeout 50000
80--no-warnings
81test/**/*.test.{js,ts}
82{
83 "name": "example-dynamic-mocking-and-testing-calls",
84 "version": "1.0.0",
85 "main": "index.js",
86 "license": "MIT",
87 "scripts": {
88 "test": "export NODE_ENV=test && mocha",
89 "build": "waffle",
90 "lint": "eslint '{src,test}/**/*.ts'",
91 "lint:fix": "eslint --fix '{src,test}/**/*.ts'"
92 },
93 "devDependencies": {
94 "@openzeppelin/contracts": "^4.3.1",
95 "@types/chai": "^4.2.3",
96 "@types/mocha": "^5.2.7",
97 "@typescript-eslint/eslint-plugin": "^2.30.0",
98 "@typescript-eslint/parser": "^2.30.0",
99 "chai": "^4.3.4",
100 "eslint": "^6.8.0",
101 "eslint-plugin-import": "^2.20.2",
102 "ethereum-waffle": "^3.4.0",
103 "ethers": "^5.0.17",
104 "mocha": "^7.2.0",
105 "ts-node": "^8.9.1",
106 "typescript": "^3.8.3"
107 }
108}
109{
110 "compilerOptions": {
111 "declaration": true,
112 "esModuleInterop": true,
113 "lib": [
114 "ES2018"
115 ],
116 "module": "CommonJS",
117 "moduleResolution": "node",
118 "outDir": "dist",
119 "resolveJsonModule": true,
120 "skipLibCheck": true,
121 "strict": true,
122 "target": "ES2018"
123 }
124
125 // custom test in vrfContract
126 it('Tests if a random number is returned', async () => {
127 expect(await vrfContract.getRandomNumber()).to.be.equal(7);
128 });
129}
130{
131 "compilerType": "solcjs",
132 "compilerVersion": "0.6.2",
133 "sourceDirectory": "./src",
134 "outputDirectory": "./build"
135}
136git clone git@github.com:a-t-2/chainlink.git
137git clone git@github.com:a-t-2/test_vrf3.git
138cd test_vrf3
139sudo apt install npm
140npm install
141npm audit fix
142npm install --save-dev ethereum-waffle
143npm install @openzeppelin/contracts -D
144npm i chai -D
145npm i mocha -D
146rm -r build
147npx waffle
148npx mocha
149npm test
150 Am I Rich Already
151 ✓ checks if contract called balanceOf with certain wallet on the ERC20 token (249ms)
152 ✓ returns false if the wallet has less than 1000000 coins (190ms)
153 ✓ returns true if the wallet has at least 1000000 coins (159ms)
154 Tests if a random number is returned:
155 Error: cannot estimate gas; transaction may fail or may require manual gas limit (error={"name":"RuntimeError","results":{"0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92":{"error":"revert","program_counter":609,"return":"0x"}},"hashes":["0x0a0b028de6cf6e8446853a300061305501136cefa5f5eb3e96afd95dbd73dd92"],"message":"VM Exception while processing transaction: revert"}, tx={"data":"0xdbdff2c1","to":{},"from":"0x17ec8597ff92C3F44523bDc65BF0f1bE632917ff","gasPrice":{"type":"BigNumber","hex":"0x77359400"},"type":0,"nonce":{},"gasLimit":{},"chainId":{}}, code=UNPREDICTABLE_GAS_LIMIT, version=abstract-signer/5.4.1)
156 at Logger.makeError (node_modules/@ethersproject/logger/src.ts/index.ts:225:28)
157 at Logger.throwError (node_modules/@ethersproject/logger/src.ts/index.ts:237:20)
158 at /home/name/git/trucol/tested/new_test/test_vrf3/node_modules/@ethersproject/abstract-signer/src.ts/index.ts:301:31
159 at process._tickCallback (internal/process/next_tick.js:68:7)
160
161
162
163 3 passing (4s)
164
Which set of files, file structure and commands do I need to automatically test whether the getRandomNumber()
contract returns an integer if sufficient "gas" is provided, and an error otherwise?
ANSWER
Answered 2021-Sep-09 at 04:35to test locally you need to make use of mocks which can simulate having an oracle network. Because you're working locally, a Chainlink node doesn't know about your local blockchain, so you can't actually do proper VRF requests. Note you can try deploy a local Chainlink node and a local blockchain and have them talk, but it isn't fully supported yet so you may get mixed results. Anyway, as per the hardhat starter kit that you linked, you can set the defaultNetwork to be 'hardhat' in the hardhat.config.js file, then when you deploy and run the integration tests (yarn test-integration), it will use mocks to mock up the VRF node, and to test the requesting of a random number. See the test here, and the mock contracts and linktoken get deployed here
QUESTION
I want to get the address from mnemonic with the proper derivation path
Asked 2022-Feb-23 at 00:41I am very new to blockchain programming and programming in general. I want to generate my SOL address using the mnemonic seed phrase with the derivation path "m/44'/501'/0'/0". I can't find a proper BIP44 module for python where you can specify the derivation path.
ANSWER
Answered 2022-Feb-23 at 00:41After a long search through the internet, I have finally found a way of solving my problem that I want to share with you.
1from bip_utils import *
2
3MNEMONIC = "...12 words phrase..."
4
5seed_bytes = Bip39SeedGenerator(MNEMONIC).Generate("")
6
7bip44_mst_ctx = Bip44.FromSeed(seed_bytes, Bip44Coins.SOLANA)
8
9bip44_acc_ctx = bip44_mst_ctx.Purpose().Coin().Account(0)
10
11bip44_chg_ctx = bip44_acc_ctx.Change(Bip44Changes.CHAIN_EXT)
12
13print(bip44_chg_ctx.PublicKey().ToAddress())
14
This code outputs the first address of your mnemonic. This is only for Sollet and Phantom wallet!
If you are using Solflare you can cut the line bip44_chg_ctx = bip44_acc_ctx.Change(Bip44Changes.CHAIN_EXT)
out!
QUESTION
how to sign a message with ecdsa privatekey using golang?
Asked 2022-Feb-20 at 14:48I am trying to sign a message in go
generated via hd wallet's private key using cosmos sdk. Below is the equivalent implementation in python which generates the signed message / signature as expected when submitted/verified is working properly but unable to get it working wtih Go
implementation. Any inputs for equivalent golang version of the python implementation is much appreciated. Thank you.
Python version uses sha256 , ecdsa but when using the equivalent cyrpto/ecdsa doesn't return valid signature.
Python
1 def test_sign_message(self):
2 """ Tests the ability of the signer to sing message """
3
4 # Loading up the signer object to use for the operation
5 signer: TestSigners = TestSigners.from_mnemonic("blast about old claw current first paste risk involve victory edit current")
6 sample_payload_to_sign = "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842'
7 # print("test".encode("UTF-8").hex())
8 s = signer.sign(sample_payload_to_sign)
9 print(s)
10
11
12from typing import List, Tuple, Dict, Union, Any
13from hdwallet.hdwallet import HDWallet
14from ecdsa.util import sigencode_der
15from ecdsa.curves import SECP256k1
16from ecdsa.keys import SigningKey
17import mnemonic
18import hashlib
19import ecdsa
20
21
22class TestSigners():
23
24 HD_WALLET_PARAMS: Dict[str, Tuple[int, bool]] = {
25 "purpose": (44, True),
26 "coinType": (1022, True),
27 "account": (0, True),
28 "change": (0, False),
29 }
30
31 def __init__(
32 self,
33 seed: Union[bytes, bytearray, str]
34 ) -> None:
35 """ Instantiates a new signer object from the seed phrase
36
37 Args:
38 seed (Union[bytes, bytearray, str]): The seed phrase used to generate the public and
39 private keys.
40 """
41
42 self.seed: Union[bytes, bytearray] = seed if isinstance(seed, (bytes, bytearray)) else bytearray.fromhex(seed)
43
44 @classmethod
45 def from_mnemonic(
46 cls,
47 mnemonic_phrase: Union[str, List[str], Tuple[str]]
48 ) -> 'Signer':
49 """
50 Instantiates a new Signer object from the mnemonic phrase passed.
51
52 Args:
53 mnemonic_phrase (Union[str, :obj:`list` of :obj:`str`, :obj:`tuple` of :obj:`str`):
54 A string, list, or a tuple of the mnemonic phrase. If the argument is passed as an
55 iterable, then it will be joined with a space.
56
57 Returns:
58 Signer: A new signer initalized through the mnemonic phrase.
59 """
60
61 # If the supplied mnemonic phrase is a list then convert it to a string
62 if isinstance(mnemonic_phrase, (list, tuple)):
63 mnemonic_string: str = " ".join(mnemonic_phrase)
64 else:
65 mnemonic_string: str = mnemonic_phrase
66
67 mnemonic_string: str = " ".join(mnemonic_phrase) if isinstance(mnemonic_phrase,
68 (list, tuple)) else mnemonic_phrase
69
70 return cls(mnemonic.Mnemonic.to_seed(mnemonic_string))
71
72 def public_key(
73 self,
74 index: int = 0
75 ) -> str:
76 """
77 Gets the public key for the signer for the specified account index
78
79 Args:
80 index (int): The account index to get the public keys for.
81
82 Returns:
83 str: A string of the public key for the wallet
84 """
85
86 return str(self.hdwallet(index).public_key())
87
88 def private_key(
89 self,
90 index: int = 0
91 ) -> str:
92 """
93 Gets the private key for the signer for the specified account index
94
95 Args:
96 index (int): The account index to get the private keys for.
97
98 Returns:
99 str: A string of the private key for the wallet
100 """
101
102 return str(self.hdwallet(index).private_key())
103
104 def hdwallet(
105 self,
106 index: int = 0
107 ) -> HDWallet:
108 """
109 Creates an HDWallet object suitable for the Radix blockchain with the passed account index.
110
111 Args:
112 index (int): The account index to create the HDWallet object for.
113
114 Returns:
115 HDWallet: An HD wallet object created with the Radix Parameters for a given account
116 index.
117 """
118
119 hdwallet: HDWallet = HDWallet()
120 hdwallet.from_seed(seed=self.seed.hex())
121 for _, values_tuple in self.HD_WALLET_PARAMS.items():
122 value, hardened = values_tuple
123 hdwallet.from_index(value, hardened=hardened)
124 hdwallet.from_index(index, True)
125
126 return hdwallet
127
128 def sign(
129 self,
130 data: str,
131 index: int = 0
132 ) -> str:
133 """
134 Signs the given data using the private keys for the account at the specified account index.
135
136 Arguments:
137 data (str): A string of the data which we wish to sign.
138 index (int): The account index to get the private keys for.
139
140 Returns:
141 str: A string of the signed data
142 """
143
144 signing_key: SigningKey = ecdsa.SigningKey.from_string( # type: ignore
145 string=bytearray.fromhex(self.private_key(index)),
146 curve=SECP256k1,
147 hashfunc=hashlib.sha256
148 )
149
150 return signing_key.sign_digest( # type: ignore
151 digest=bytearray.fromhex(data),
152 sigencode=sigencode_der
153 ).hex()
154
GO ( Not Working )
1 def test_sign_message(self):
2 """ Tests the ability of the signer to sing message """
3
4 # Loading up the signer object to use for the operation
5 signer: TestSigners = TestSigners.from_mnemonic("blast about old claw current first paste risk involve victory edit current")
6 sample_payload_to_sign = "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842'
7 # print("test".encode("UTF-8").hex())
8 s = signer.sign(sample_payload_to_sign)
9 print(s)
10
11
12from typing import List, Tuple, Dict, Union, Any
13from hdwallet.hdwallet import HDWallet
14from ecdsa.util import sigencode_der
15from ecdsa.curves import SECP256k1
16from ecdsa.keys import SigningKey
17import mnemonic
18import hashlib
19import ecdsa
20
21
22class TestSigners():
23
24 HD_WALLET_PARAMS: Dict[str, Tuple[int, bool]] = {
25 "purpose": (44, True),
26 "coinType": (1022, True),
27 "account": (0, True),
28 "change": (0, False),
29 }
30
31 def __init__(
32 self,
33 seed: Union[bytes, bytearray, str]
34 ) -> None:
35 """ Instantiates a new signer object from the seed phrase
36
37 Args:
38 seed (Union[bytes, bytearray, str]): The seed phrase used to generate the public and
39 private keys.
40 """
41
42 self.seed: Union[bytes, bytearray] = seed if isinstance(seed, (bytes, bytearray)) else bytearray.fromhex(seed)
43
44 @classmethod
45 def from_mnemonic(
46 cls,
47 mnemonic_phrase: Union[str, List[str], Tuple[str]]
48 ) -> 'Signer':
49 """
50 Instantiates a new Signer object from the mnemonic phrase passed.
51
52 Args:
53 mnemonic_phrase (Union[str, :obj:`list` of :obj:`str`, :obj:`tuple` of :obj:`str`):
54 A string, list, or a tuple of the mnemonic phrase. If the argument is passed as an
55 iterable, then it will be joined with a space.
56
57 Returns:
58 Signer: A new signer initalized through the mnemonic phrase.
59 """
60
61 # If the supplied mnemonic phrase is a list then convert it to a string
62 if isinstance(mnemonic_phrase, (list, tuple)):
63 mnemonic_string: str = " ".join(mnemonic_phrase)
64 else:
65 mnemonic_string: str = mnemonic_phrase
66
67 mnemonic_string: str = " ".join(mnemonic_phrase) if isinstance(mnemonic_phrase,
68 (list, tuple)) else mnemonic_phrase
69
70 return cls(mnemonic.Mnemonic.to_seed(mnemonic_string))
71
72 def public_key(
73 self,
74 index: int = 0
75 ) -> str:
76 """
77 Gets the public key for the signer for the specified account index
78
79 Args:
80 index (int): The account index to get the public keys for.
81
82 Returns:
83 str: A string of the public key for the wallet
84 """
85
86 return str(self.hdwallet(index).public_key())
87
88 def private_key(
89 self,
90 index: int = 0
91 ) -> str:
92 """
93 Gets the private key for the signer for the specified account index
94
95 Args:
96 index (int): The account index to get the private keys for.
97
98 Returns:
99 str: A string of the private key for the wallet
100 """
101
102 return str(self.hdwallet(index).private_key())
103
104 def hdwallet(
105 self,
106 index: int = 0
107 ) -> HDWallet:
108 """
109 Creates an HDWallet object suitable for the Radix blockchain with the passed account index.
110
111 Args:
112 index (int): The account index to create the HDWallet object for.
113
114 Returns:
115 HDWallet: An HD wallet object created with the Radix Parameters for a given account
116 index.
117 """
118
119 hdwallet: HDWallet = HDWallet()
120 hdwallet.from_seed(seed=self.seed.hex())
121 for _, values_tuple in self.HD_WALLET_PARAMS.items():
122 value, hardened = values_tuple
123 hdwallet.from_index(value, hardened=hardened)
124 hdwallet.from_index(index, True)
125
126 return hdwallet
127
128 def sign(
129 self,
130 data: str,
131 index: int = 0
132 ) -> str:
133 """
134 Signs the given data using the private keys for the account at the specified account index.
135
136 Arguments:
137 data (str): A string of the data which we wish to sign.
138 index (int): The account index to get the private keys for.
139
140 Returns:
141 str: A string of the signed data
142 """
143
144 signing_key: SigningKey = ecdsa.SigningKey.from_string( # type: ignore
145 string=bytearray.fromhex(self.private_key(index)),
146 curve=SECP256k1,
147 hashfunc=hashlib.sha256
148 )
149
150 return signing_key.sign_digest( # type: ignore
151 digest=bytearray.fromhex(data),
152 sigencode=sigencode_der
153 ).hex()
154package main
155
156import (
157 "encoding/hex"
158 "fmt"
159 "log"
160
161 "github.com/cosmos/cosmos-sdk/crypto/hd"
162 "github.com/cosmos/go-bip39"
163 "github.com/decred/dcrd/bech32"
164 "github.com/tendermint/tendermint/crypto/secp256k1"
165)
166
167func main() {
168
169 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
170 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
171
172 master, ch := hd.ComputeMastersFromSeed(seed)
173 path := "m/44'/1022'/0'/0/0'"
174 priv, err := hd.DerivePrivateKeyForPath(master, ch, path)
175 if err != nil {
176 t.Fatal(err)
177 }
178 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/118'/0'/0/0'
179 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a
180
181 var privKey = secp256k1.PrivKey(priv)
182 pubKey := privKey.PubKey()
183 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8
184
185 //str := "test"
186 str := "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842"
187 //hx := hex.EncodeToString([]byte(str))
188 //fmt.Println(hx)
189 sign, err := privKey.Sign([]byte(str))
190 if err != nil {
191 return
192 }
193
194 fmt.Println(hex.EncodeToString(sign))
195}
196
ANSWER
Answered 2022-Feb-20 at 14:48Both codes return hex encoded as private key
1 def test_sign_message(self):
2 """ Tests the ability of the signer to sing message """
3
4 # Loading up the signer object to use for the operation
5 signer: TestSigners = TestSigners.from_mnemonic("blast about old claw current first paste risk involve victory edit current")
6 sample_payload_to_sign = "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842'
7 # print("test".encode("UTF-8").hex())
8 s = signer.sign(sample_payload_to_sign)
9 print(s)
10
11
12from typing import List, Tuple, Dict, Union, Any
13from hdwallet.hdwallet import HDWallet
14from ecdsa.util import sigencode_der
15from ecdsa.curves import SECP256k1
16from ecdsa.keys import SigningKey
17import mnemonic
18import hashlib
19import ecdsa
20
21
22class TestSigners():
23
24 HD_WALLET_PARAMS: Dict[str, Tuple[int, bool]] = {
25 "purpose": (44, True),
26 "coinType": (1022, True),
27 "account": (0, True),
28 "change": (0, False),
29 }
30
31 def __init__(
32 self,
33 seed: Union[bytes, bytearray, str]
34 ) -> None:
35 """ Instantiates a new signer object from the seed phrase
36
37 Args:
38 seed (Union[bytes, bytearray, str]): The seed phrase used to generate the public and
39 private keys.
40 """
41
42 self.seed: Union[bytes, bytearray] = seed if isinstance(seed, (bytes, bytearray)) else bytearray.fromhex(seed)
43
44 @classmethod
45 def from_mnemonic(
46 cls,
47 mnemonic_phrase: Union[str, List[str], Tuple[str]]
48 ) -> 'Signer':
49 """
50 Instantiates a new Signer object from the mnemonic phrase passed.
51
52 Args:
53 mnemonic_phrase (Union[str, :obj:`list` of :obj:`str`, :obj:`tuple` of :obj:`str`):
54 A string, list, or a tuple of the mnemonic phrase. If the argument is passed as an
55 iterable, then it will be joined with a space.
56
57 Returns:
58 Signer: A new signer initalized through the mnemonic phrase.
59 """
60
61 # If the supplied mnemonic phrase is a list then convert it to a string
62 if isinstance(mnemonic_phrase, (list, tuple)):
63 mnemonic_string: str = " ".join(mnemonic_phrase)
64 else:
65 mnemonic_string: str = mnemonic_phrase
66
67 mnemonic_string: str = " ".join(mnemonic_phrase) if isinstance(mnemonic_phrase,
68 (list, tuple)) else mnemonic_phrase
69
70 return cls(mnemonic.Mnemonic.to_seed(mnemonic_string))
71
72 def public_key(
73 self,
74 index: int = 0
75 ) -> str:
76 """
77 Gets the public key for the signer for the specified account index
78
79 Args:
80 index (int): The account index to get the public keys for.
81
82 Returns:
83 str: A string of the public key for the wallet
84 """
85
86 return str(self.hdwallet(index).public_key())
87
88 def private_key(
89 self,
90 index: int = 0
91 ) -> str:
92 """
93 Gets the private key for the signer for the specified account index
94
95 Args:
96 index (int): The account index to get the private keys for.
97
98 Returns:
99 str: A string of the private key for the wallet
100 """
101
102 return str(self.hdwallet(index).private_key())
103
104 def hdwallet(
105 self,
106 index: int = 0
107 ) -> HDWallet:
108 """
109 Creates an HDWallet object suitable for the Radix blockchain with the passed account index.
110
111 Args:
112 index (int): The account index to create the HDWallet object for.
113
114 Returns:
115 HDWallet: An HD wallet object created with the Radix Parameters for a given account
116 index.
117 """
118
119 hdwallet: HDWallet = HDWallet()
120 hdwallet.from_seed(seed=self.seed.hex())
121 for _, values_tuple in self.HD_WALLET_PARAMS.items():
122 value, hardened = values_tuple
123 hdwallet.from_index(value, hardened=hardened)
124 hdwallet.from_index(index, True)
125
126 return hdwallet
127
128 def sign(
129 self,
130 data: str,
131 index: int = 0
132 ) -> str:
133 """
134 Signs the given data using the private keys for the account at the specified account index.
135
136 Arguments:
137 data (str): A string of the data which we wish to sign.
138 index (int): The account index to get the private keys for.
139
140 Returns:
141 str: A string of the signed data
142 """
143
144 signing_key: SigningKey = ecdsa.SigningKey.from_string( # type: ignore
145 string=bytearray.fromhex(self.private_key(index)),
146 curve=SECP256k1,
147 hashfunc=hashlib.sha256
148 )
149
150 return signing_key.sign_digest( # type: ignore
151 digest=bytearray.fromhex(data),
152 sigencode=sigencode_der
153 ).hex()
154package main
155
156import (
157 "encoding/hex"
158 "fmt"
159 "log"
160
161 "github.com/cosmos/cosmos-sdk/crypto/hd"
162 "github.com/cosmos/go-bip39"
163 "github.com/decred/dcrd/bech32"
164 "github.com/tendermint/tendermint/crypto/secp256k1"
165)
166
167func main() {
168
169 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
170 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
171
172 master, ch := hd.ComputeMastersFromSeed(seed)
173 path := "m/44'/1022'/0'/0/0'"
174 priv, err := hd.DerivePrivateKeyForPath(master, ch, path)
175 if err != nil {
176 t.Fatal(err)
177 }
178 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/118'/0'/0/0'
179 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a
180
181 var privKey = secp256k1.PrivKey(priv)
182 pubKey := privKey.PubKey()
183 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8
184
185 //str := "test"
186 str := "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842"
187 //hx := hex.EncodeToString([]byte(str))
188 //fmt.Println(hx)
189 sign, err := privKey.Sign([]byte(str))
190 if err != nil {
191 return
192 }
193
194 fmt.Println(hex.EncodeToString(sign))
195}
19633f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
197
and as compressed public key
1 def test_sign_message(self):
2 """ Tests the ability of the signer to sing message """
3
4 # Loading up the signer object to use for the operation
5 signer: TestSigners = TestSigners.from_mnemonic("blast about old claw current first paste risk involve victory edit current")
6 sample_payload_to_sign = "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842'
7 # print("test".encode("UTF-8").hex())
8 s = signer.sign(sample_payload_to_sign)
9 print(s)
10
11
12from typing import List, Tuple, Dict, Union, Any
13from hdwallet.hdwallet import HDWallet
14from ecdsa.util import sigencode_der
15from ecdsa.curves import SECP256k1
16from ecdsa.keys import SigningKey
17import mnemonic
18import hashlib
19import ecdsa
20
21
22class TestSigners():
23
24 HD_WALLET_PARAMS: Dict[str, Tuple[int, bool]] = {
25 "purpose": (44, True),
26 "coinType": (1022, True),
27 "account": (0, True),
28 "change": (0, False),
29 }
30
31 def __init__(
32 self,
33 seed: Union[bytes, bytearray, str]
34 ) -> None:
35 """ Instantiates a new signer object from the seed phrase
36
37 Args:
38 seed (Union[bytes, bytearray, str]): The seed phrase used to generate the public and
39 private keys.
40 """
41
42 self.seed: Union[bytes, bytearray] = seed if isinstance(seed, (bytes, bytearray)) else bytearray.fromhex(seed)
43
44 @classmethod
45 def from_mnemonic(
46 cls,
47 mnemonic_phrase: Union[str, List[str], Tuple[str]]
48 ) -> 'Signer':
49 """
50 Instantiates a new Signer object from the mnemonic phrase passed.
51
52 Args:
53 mnemonic_phrase (Union[str, :obj:`list` of :obj:`str`, :obj:`tuple` of :obj:`str`):
54 A string, list, or a tuple of the mnemonic phrase. If the argument is passed as an
55 iterable, then it will be joined with a space.
56
57 Returns:
58 Signer: A new signer initalized through the mnemonic phrase.
59 """
60
61 # If the supplied mnemonic phrase is a list then convert it to a string
62 if isinstance(mnemonic_phrase, (list, tuple)):
63 mnemonic_string: str = " ".join(mnemonic_phrase)
64 else:
65 mnemonic_string: str = mnemonic_phrase
66
67 mnemonic_string: str = " ".join(mnemonic_phrase) if isinstance(mnemonic_phrase,
68 (list, tuple)) else mnemonic_phrase
69
70 return cls(mnemonic.Mnemonic.to_seed(mnemonic_string))
71
72 def public_key(
73 self,
74 index: int = 0
75 ) -> str:
76 """
77 Gets the public key for the signer for the specified account index
78
79 Args:
80 index (int): The account index to get the public keys for.
81
82 Returns:
83 str: A string of the public key for the wallet
84 """
85
86 return str(self.hdwallet(index).public_key())
87
88 def private_key(
89 self,
90 index: int = 0
91 ) -> str:
92 """
93 Gets the private key for the signer for the specified account index
94
95 Args:
96 index (int): The account index to get the private keys for.
97
98 Returns:
99 str: A string of the private key for the wallet
100 """
101
102 return str(self.hdwallet(index).private_key())
103
104 def hdwallet(
105 self,
106 index: int = 0
107 ) -> HDWallet:
108 """
109 Creates an HDWallet object suitable for the Radix blockchain with the passed account index.
110
111 Args:
112 index (int): The account index to create the HDWallet object for.
113
114 Returns:
115 HDWallet: An HD wallet object created with the Radix Parameters for a given account
116 index.
117 """
118
119 hdwallet: HDWallet = HDWallet()
120 hdwallet.from_seed(seed=self.seed.hex())
121 for _, values_tuple in self.HD_WALLET_PARAMS.items():
122 value, hardened = values_tuple
123 hdwallet.from_index(value, hardened=hardened)
124 hdwallet.from_index(index, True)
125
126 return hdwallet
127
128 def sign(
129 self,
130 data: str,
131 index: int = 0
132 ) -> str:
133 """
134 Signs the given data using the private keys for the account at the specified account index.
135
136 Arguments:
137 data (str): A string of the data which we wish to sign.
138 index (int): The account index to get the private keys for.
139
140 Returns:
141 str: A string of the signed data
142 """
143
144 signing_key: SigningKey = ecdsa.SigningKey.from_string( # type: ignore
145 string=bytearray.fromhex(self.private_key(index)),
146 curve=SECP256k1,
147 hashfunc=hashlib.sha256
148 )
149
150 return signing_key.sign_digest( # type: ignore
151 digest=bytearray.fromhex(data),
152 sigencode=sigencode_der
153 ).hex()
154package main
155
156import (
157 "encoding/hex"
158 "fmt"
159 "log"
160
161 "github.com/cosmos/cosmos-sdk/crypto/hd"
162 "github.com/cosmos/go-bip39"
163 "github.com/decred/dcrd/bech32"
164 "github.com/tendermint/tendermint/crypto/secp256k1"
165)
166
167func main() {
168
169 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
170 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
171
172 master, ch := hd.ComputeMastersFromSeed(seed)
173 path := "m/44'/1022'/0'/0/0'"
174 priv, err := hd.DerivePrivateKeyForPath(master, ch, path)
175 if err != nil {
176 t.Fatal(err)
177 }
178 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/118'/0'/0/0'
179 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a
180
181 var privKey = secp256k1.PrivKey(priv)
182 pubKey := privKey.PubKey()
183 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8
184
185 //str := "test"
186 str := "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842"
187 //hx := hex.EncodeToString([]byte(str))
188 //fmt.Println(hx)
189 sign, err := privKey.Sign([]byte(str))
190 if err != nil {
191 return
192 }
193
194 fmt.Println(hex.EncodeToString(sign))
195}
19633f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
197026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
198
Since both codes provide the same keys, the issue must be with signing!
As test message for signing the UTF8 encoding of test
is used, whose SHA256 hash is hex encoded 9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
.
Remark 1: If a double SHA256 hashing is used as noted in the comment, the SHA256 hash of test
is to be used as test message instead of test
. Apart from that the further processing is the same.
The Python and Go code are currently incompatible because they differ in signing and signature format:
With regard to signing: In the Python code, the hashed message is passed. This is correct because
sign_digest()
does not hash the message (see here), and thus the hashed message is signed.
In contrast,sign()
in the Go code hashes the message (see here), so the message itself must be passed for the processing to be functionally identical to the Python code.With regard to the signature format: the Python code uses the ASN.1/DER format, while the Go code uses the IEEE P1363 format.
Therefore, a conversion from IEEE P1363 to ASN.1/DER must be performed in the Go code:
With this, the fixed Go code is:
1 def test_sign_message(self):
2 """ Tests the ability of the signer to sing message """
3
4 # Loading up the signer object to use for the operation
5 signer: TestSigners = TestSigners.from_mnemonic("blast about old claw current first paste risk involve victory edit current")
6 sample_payload_to_sign = "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842'
7 # print("test".encode("UTF-8").hex())
8 s = signer.sign(sample_payload_to_sign)
9 print(s)
10
11
12from typing import List, Tuple, Dict, Union, Any
13from hdwallet.hdwallet import HDWallet
14from ecdsa.util import sigencode_der
15from ecdsa.curves import SECP256k1
16from ecdsa.keys import SigningKey
17import mnemonic
18import hashlib
19import ecdsa
20
21
22class TestSigners():
23
24 HD_WALLET_PARAMS: Dict[str, Tuple[int, bool]] = {
25 "purpose": (44, True),
26 "coinType": (1022, True),
27 "account": (0, True),
28 "change": (0, False),
29 }
30
31 def __init__(
32 self,
33 seed: Union[bytes, bytearray, str]
34 ) -> None:
35 """ Instantiates a new signer object from the seed phrase
36
37 Args:
38 seed (Union[bytes, bytearray, str]): The seed phrase used to generate the public and
39 private keys.
40 """
41
42 self.seed: Union[bytes, bytearray] = seed if isinstance(seed, (bytes, bytearray)) else bytearray.fromhex(seed)
43
44 @classmethod
45 def from_mnemonic(
46 cls,
47 mnemonic_phrase: Union[str, List[str], Tuple[str]]
48 ) -> 'Signer':
49 """
50 Instantiates a new Signer object from the mnemonic phrase passed.
51
52 Args:
53 mnemonic_phrase (Union[str, :obj:`list` of :obj:`str`, :obj:`tuple` of :obj:`str`):
54 A string, list, or a tuple of the mnemonic phrase. If the argument is passed as an
55 iterable, then it will be joined with a space.
56
57 Returns:
58 Signer: A new signer initalized through the mnemonic phrase.
59 """
60
61 # If the supplied mnemonic phrase is a list then convert it to a string
62 if isinstance(mnemonic_phrase, (list, tuple)):
63 mnemonic_string: str = " ".join(mnemonic_phrase)
64 else:
65 mnemonic_string: str = mnemonic_phrase
66
67 mnemonic_string: str = " ".join(mnemonic_phrase) if isinstance(mnemonic_phrase,
68 (list, tuple)) else mnemonic_phrase
69
70 return cls(mnemonic.Mnemonic.to_seed(mnemonic_string))
71
72 def public_key(
73 self,
74 index: int = 0
75 ) -> str:
76 """
77 Gets the public key for the signer for the specified account index
78
79 Args:
80 index (int): The account index to get the public keys for.
81
82 Returns:
83 str: A string of the public key for the wallet
84 """
85
86 return str(self.hdwallet(index).public_key())
87
88 def private_key(
89 self,
90 index: int = 0
91 ) -> str:
92 """
93 Gets the private key for the signer for the specified account index
94
95 Args:
96 index (int): The account index to get the private keys for.
97
98 Returns:
99 str: A string of the private key for the wallet
100 """
101
102 return str(self.hdwallet(index).private_key())
103
104 def hdwallet(
105 self,
106 index: int = 0
107 ) -> HDWallet:
108 """
109 Creates an HDWallet object suitable for the Radix blockchain with the passed account index.
110
111 Args:
112 index (int): The account index to create the HDWallet object for.
113
114 Returns:
115 HDWallet: An HD wallet object created with the Radix Parameters for a given account
116 index.
117 """
118
119 hdwallet: HDWallet = HDWallet()
120 hdwallet.from_seed(seed=self.seed.hex())
121 for _, values_tuple in self.HD_WALLET_PARAMS.items():
122 value, hardened = values_tuple
123 hdwallet.from_index(value, hardened=hardened)
124 hdwallet.from_index(index, True)
125
126 return hdwallet
127
128 def sign(
129 self,
130 data: str,
131 index: int = 0
132 ) -> str:
133 """
134 Signs the given data using the private keys for the account at the specified account index.
135
136 Arguments:
137 data (str): A string of the data which we wish to sign.
138 index (int): The account index to get the private keys for.
139
140 Returns:
141 str: A string of the signed data
142 """
143
144 signing_key: SigningKey = ecdsa.SigningKey.from_string( # type: ignore
145 string=bytearray.fromhex(self.private_key(index)),
146 curve=SECP256k1,
147 hashfunc=hashlib.sha256
148 )
149
150 return signing_key.sign_digest( # type: ignore
151 digest=bytearray.fromhex(data),
152 sigencode=sigencode_der
153 ).hex()
154package main
155
156import (
157 "encoding/hex"
158 "fmt"
159 "log"
160
161 "github.com/cosmos/cosmos-sdk/crypto/hd"
162 "github.com/cosmos/go-bip39"
163 "github.com/decred/dcrd/bech32"
164 "github.com/tendermint/tendermint/crypto/secp256k1"
165)
166
167func main() {
168
169 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
170 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
171
172 master, ch := hd.ComputeMastersFromSeed(seed)
173 path := "m/44'/1022'/0'/0/0'"
174 priv, err := hd.DerivePrivateKeyForPath(master, ch, path)
175 if err != nil {
176 t.Fatal(err)
177 }
178 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/118'/0'/0/0'
179 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a
180
181 var privKey = secp256k1.PrivKey(priv)
182 pubKey := privKey.PubKey()
183 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8
184
185 //str := "test"
186 str := "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842"
187 //hx := hex.EncodeToString([]byte(str))
188 //fmt.Println(hx)
189 sign, err := privKey.Sign([]byte(str))
190 if err != nil {
191 return
192 }
193
194 fmt.Println(hex.EncodeToString(sign))
195}
19633f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
197026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
198package main
199
200import (
201 "encoding/hex"
202 "fmt"
203
204 "math/big"
205
206 "github.com/cosmos/cosmos-sdk/crypto/hd"
207 "github.com/cosmos/go-bip39"
208 "github.com/tendermint/tendermint/crypto/secp256k1"
209
210 //"github.com/btcsuite/btcd/btcec"
211 "golang.org/x/crypto/cryptobyte"
212 "golang.org/x/crypto/cryptobyte/asn1"
213)
214
215func main() {
216
217 //
218 // Derive private and public key (this part works)
219 //
220 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
221 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
222
223 master, ch := hd.ComputeMastersFromSeed(seed)
224 path := "m/44'/1022'/0'/0/0'"
225 priv, _ := hd.DerivePrivateKeyForPath(master, ch, path)
226 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/1022'/0'/0/0'
227 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 33f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
228
229 var privKey = secp256k1.PrivKey(priv)
230 pubKey := privKey.PubKey()
231 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
232
233 //
234 // Sign (this part needs to be fixed)
235 //
236 data := "test"
237
238 signature, _ := privKey.Sign([]byte(data))
239 fmt.Println(hex.EncodeToString(signature))
240
241 rVal := new(big.Int)
242 rVal.SetBytes(signature[0:32])
243 sVal := new(big.Int)
244 sVal.SetBytes(signature[32:64])
245 var b cryptobyte.Builder
246 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
247 b.AddASN1BigInt(rVal)
248 b.AddASN1BigInt(sVal)
249 })
250 signatureDER, _ := b.Bytes()
251 fmt.Println("Signature, DER: ", hex.EncodeToString(signatureDER))
252
253 /*
254 hash, _ := hex.DecodeString("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")
255
256 // Sign without hashing
257 privateKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), priv)
258 signature, _ := privateKey.Sign(hash[:])
259
260 // Convert to ASN1/DER
261 rVal := new(big.Int)
262 rVal.SetBytes(signature.R.Bytes())
263 sVal := new(big.Int)
264 sVal.SetBytes(signature.S.Bytes())
265 var b cryptobyte.Builder
266 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
267 b.AddASN1BigInt(rVal)
268 b.AddASN1BigInt(sVal)
269 })
270 signatureDER, _ := b.Bytes()
271 fmt.Println("Signature, DER: ", hex.EncodeToString(signatureDER))
272 */
273}
274
Remark 2: If the original message is not available in the Go code, but only the hash, a function that does not hash is needed for signing.
The tendermint/crypto/secp256k1 package does not support this, but tendermint/crypto/secp256k1 uses internally btcsuite/btcd/btcec which does.
This is implemented in the commented-out code.
The output is:
1 def test_sign_message(self):
2 """ Tests the ability of the signer to sing message """
3
4 # Loading up the signer object to use for the operation
5 signer: TestSigners = TestSigners.from_mnemonic("blast about old claw current first paste risk involve victory edit current")
6 sample_payload_to_sign = "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842'
7 # print("test".encode("UTF-8").hex())
8 s = signer.sign(sample_payload_to_sign)
9 print(s)
10
11
12from typing import List, Tuple, Dict, Union, Any
13from hdwallet.hdwallet import HDWallet
14from ecdsa.util import sigencode_der
15from ecdsa.curves import SECP256k1
16from ecdsa.keys import SigningKey
17import mnemonic
18import hashlib
19import ecdsa
20
21
22class TestSigners():
23
24 HD_WALLET_PARAMS: Dict[str, Tuple[int, bool]] = {
25 "purpose": (44, True),
26 "coinType": (1022, True),
27 "account": (0, True),
28 "change": (0, False),
29 }
30
31 def __init__(
32 self,
33 seed: Union[bytes, bytearray, str]
34 ) -> None:
35 """ Instantiates a new signer object from the seed phrase
36
37 Args:
38 seed (Union[bytes, bytearray, str]): The seed phrase used to generate the public and
39 private keys.
40 """
41
42 self.seed: Union[bytes, bytearray] = seed if isinstance(seed, (bytes, bytearray)) else bytearray.fromhex(seed)
43
44 @classmethod
45 def from_mnemonic(
46 cls,
47 mnemonic_phrase: Union[str, List[str], Tuple[str]]
48 ) -> 'Signer':
49 """
50 Instantiates a new Signer object from the mnemonic phrase passed.
51
52 Args:
53 mnemonic_phrase (Union[str, :obj:`list` of :obj:`str`, :obj:`tuple` of :obj:`str`):
54 A string, list, or a tuple of the mnemonic phrase. If the argument is passed as an
55 iterable, then it will be joined with a space.
56
57 Returns:
58 Signer: A new signer initalized through the mnemonic phrase.
59 """
60
61 # If the supplied mnemonic phrase is a list then convert it to a string
62 if isinstance(mnemonic_phrase, (list, tuple)):
63 mnemonic_string: str = " ".join(mnemonic_phrase)
64 else:
65 mnemonic_string: str = mnemonic_phrase
66
67 mnemonic_string: str = " ".join(mnemonic_phrase) if isinstance(mnemonic_phrase,
68 (list, tuple)) else mnemonic_phrase
69
70 return cls(mnemonic.Mnemonic.to_seed(mnemonic_string))
71
72 def public_key(
73 self,
74 index: int = 0
75 ) -> str:
76 """
77 Gets the public key for the signer for the specified account index
78
79 Args:
80 index (int): The account index to get the public keys for.
81
82 Returns:
83 str: A string of the public key for the wallet
84 """
85
86 return str(self.hdwallet(index).public_key())
87
88 def private_key(
89 self,
90 index: int = 0
91 ) -> str:
92 """
93 Gets the private key for the signer for the specified account index
94
95 Args:
96 index (int): The account index to get the private keys for.
97
98 Returns:
99 str: A string of the private key for the wallet
100 """
101
102 return str(self.hdwallet(index).private_key())
103
104 def hdwallet(
105 self,
106 index: int = 0
107 ) -> HDWallet:
108 """
109 Creates an HDWallet object suitable for the Radix blockchain with the passed account index.
110
111 Args:
112 index (int): The account index to create the HDWallet object for.
113
114 Returns:
115 HDWallet: An HD wallet object created with the Radix Parameters for a given account
116 index.
117 """
118
119 hdwallet: HDWallet = HDWallet()
120 hdwallet.from_seed(seed=self.seed.hex())
121 for _, values_tuple in self.HD_WALLET_PARAMS.items():
122 value, hardened = values_tuple
123 hdwallet.from_index(value, hardened=hardened)
124 hdwallet.from_index(index, True)
125
126 return hdwallet
127
128 def sign(
129 self,
130 data: str,
131 index: int = 0
132 ) -> str:
133 """
134 Signs the given data using the private keys for the account at the specified account index.
135
136 Arguments:
137 data (str): A string of the data which we wish to sign.
138 index (int): The account index to get the private keys for.
139
140 Returns:
141 str: A string of the signed data
142 """
143
144 signing_key: SigningKey = ecdsa.SigningKey.from_string( # type: ignore
145 string=bytearray.fromhex(self.private_key(index)),
146 curve=SECP256k1,
147 hashfunc=hashlib.sha256
148 )
149
150 return signing_key.sign_digest( # type: ignore
151 digest=bytearray.fromhex(data),
152 sigencode=sigencode_der
153 ).hex()
154package main
155
156import (
157 "encoding/hex"
158 "fmt"
159 "log"
160
161 "github.com/cosmos/cosmos-sdk/crypto/hd"
162 "github.com/cosmos/go-bip39"
163 "github.com/decred/dcrd/bech32"
164 "github.com/tendermint/tendermint/crypto/secp256k1"
165)
166
167func main() {
168
169 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
170 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
171
172 master, ch := hd.ComputeMastersFromSeed(seed)
173 path := "m/44'/1022'/0'/0/0'"
174 priv, err := hd.DerivePrivateKeyForPath(master, ch, path)
175 if err != nil {
176 t.Fatal(err)
177 }
178 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/118'/0'/0/0'
179 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a
180
181 var privKey = secp256k1.PrivKey(priv)
182 pubKey := privKey.PubKey()
183 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8
184
185 //str := "test"
186 str := "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842"
187 //hx := hex.EncodeToString([]byte(str))
188 //fmt.Println(hx)
189 sign, err := privKey.Sign([]byte(str))
190 if err != nil {
191 return
192 }
193
194 fmt.Println(hex.EncodeToString(sign))
195}
19633f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
197026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
198package main
199
200import (
201 "encoding/hex"
202 "fmt"
203
204 "math/big"
205
206 "github.com/cosmos/cosmos-sdk/crypto/hd"
207 "github.com/cosmos/go-bip39"
208 "github.com/tendermint/tendermint/crypto/secp256k1"
209
210 //"github.com/btcsuite/btcd/btcec"
211 "golang.org/x/crypto/cryptobyte"
212 "golang.org/x/crypto/cryptobyte/asn1"
213)
214
215func main() {
216
217 //
218 // Derive private and public key (this part works)
219 //
220 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
221 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
222
223 master, ch := hd.ComputeMastersFromSeed(seed)
224 path := "m/44'/1022'/0'/0/0'"
225 priv, _ := hd.DerivePrivateKeyForPath(master, ch, path)
226 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/1022'/0'/0/0'
227 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 33f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
228
229 var privKey = secp256k1.PrivKey(priv)
230 pubKey := privKey.PubKey()
231 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
232
233 //
234 // Sign (this part needs to be fixed)
235 //
236 data := "test"
237
238 signature, _ := privKey.Sign([]byte(data))
239 fmt.Println(hex.EncodeToString(signature))
240
241 rVal := new(big.Int)
242 rVal.SetBytes(signature[0:32])
243 sVal := new(big.Int)
244 sVal.SetBytes(signature[32:64])
245 var b cryptobyte.Builder
246 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
247 b.AddASN1BigInt(rVal)
248 b.AddASN1BigInt(sVal)
249 })
250 signatureDER, _ := b.Bytes()
251 fmt.Println("Signature, DER: ", hex.EncodeToString(signatureDER))
252
253 /*
254 hash, _ := hex.DecodeString("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")
255
256 // Sign without hashing
257 privateKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), priv)
258 signature, _ := privateKey.Sign(hash[:])
259
260 // Convert to ASN1/DER
261 rVal := new(big.Int)
262 rVal.SetBytes(signature.R.Bytes())
263 sVal := new(big.Int)
264 sVal.SetBytes(signature.S.Bytes())
265 var b cryptobyte.Builder
266 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
267 b.AddASN1BigInt(rVal)
268 b.AddASN1BigInt(sVal)
269 })
270 signatureDER, _ := b.Bytes()
271 fmt.Println("Signature, DER: ", hex.EncodeToString(signatureDER))
272 */
273}
274Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
275Derivation Path: m/44'/1022'/0'/0/0'
276Private Key: 33f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
277Public Key: 026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
27857624717f71fae8b5917cde0f82dfe6c2e2104183ba01c6a1c9f0a8e66d3303e5035b52876d833522aace232c1d231b3aeeff303cf02d1677a240102365ce71b
279Signature, DER: 3044022057624717f71fae8b5917cde0f82dfe6c2e2104183ba01c6a1c9f0a8e66d3303e02205035b52876d833522aace232c1d231b3aeeff303cf02d1677a240102365ce71b
280
Test:
Since the Python code generates a non-deterministic signature, verification by comparing the signatures is not possible.
Instead, a possible test is to check the signatures of both codes with the same verification code.
For this purpose, in the method sign()
of the Python code the lines
1 def test_sign_message(self):
2 """ Tests the ability of the signer to sing message """
3
4 # Loading up the signer object to use for the operation
5 signer: TestSigners = TestSigners.from_mnemonic("blast about old claw current first paste risk involve victory edit current")
6 sample_payload_to_sign = "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842'
7 # print("test".encode("UTF-8").hex())
8 s = signer.sign(sample_payload_to_sign)
9 print(s)
10
11
12from typing import List, Tuple, Dict, Union, Any
13from hdwallet.hdwallet import HDWallet
14from ecdsa.util import sigencode_der
15from ecdsa.curves import SECP256k1
16from ecdsa.keys import SigningKey
17import mnemonic
18import hashlib
19import ecdsa
20
21
22class TestSigners():
23
24 HD_WALLET_PARAMS: Dict[str, Tuple[int, bool]] = {
25 "purpose": (44, True),
26 "coinType": (1022, True),
27 "account": (0, True),
28 "change": (0, False),
29 }
30
31 def __init__(
32 self,
33 seed: Union[bytes, bytearray, str]
34 ) -> None:
35 """ Instantiates a new signer object from the seed phrase
36
37 Args:
38 seed (Union[bytes, bytearray, str]): The seed phrase used to generate the public and
39 private keys.
40 """
41
42 self.seed: Union[bytes, bytearray] = seed if isinstance(seed, (bytes, bytearray)) else bytearray.fromhex(seed)
43
44 @classmethod
45 def from_mnemonic(
46 cls,
47 mnemonic_phrase: Union[str, List[str], Tuple[str]]
48 ) -> 'Signer':
49 """
50 Instantiates a new Signer object from the mnemonic phrase passed.
51
52 Args:
53 mnemonic_phrase (Union[str, :obj:`list` of :obj:`str`, :obj:`tuple` of :obj:`str`):
54 A string, list, or a tuple of the mnemonic phrase. If the argument is passed as an
55 iterable, then it will be joined with a space.
56
57 Returns:
58 Signer: A new signer initalized through the mnemonic phrase.
59 """
60
61 # If the supplied mnemonic phrase is a list then convert it to a string
62 if isinstance(mnemonic_phrase, (list, tuple)):
63 mnemonic_string: str = " ".join(mnemonic_phrase)
64 else:
65 mnemonic_string: str = mnemonic_phrase
66
67 mnemonic_string: str = " ".join(mnemonic_phrase) if isinstance(mnemonic_phrase,
68 (list, tuple)) else mnemonic_phrase
69
70 return cls(mnemonic.Mnemonic.to_seed(mnemonic_string))
71
72 def public_key(
73 self,
74 index: int = 0
75 ) -> str:
76 """
77 Gets the public key for the signer for the specified account index
78
79 Args:
80 index (int): The account index to get the public keys for.
81
82 Returns:
83 str: A string of the public key for the wallet
84 """
85
86 return str(self.hdwallet(index).public_key())
87
88 def private_key(
89 self,
90 index: int = 0
91 ) -> str:
92 """
93 Gets the private key for the signer for the specified account index
94
95 Args:
96 index (int): The account index to get the private keys for.
97
98 Returns:
99 str: A string of the private key for the wallet
100 """
101
102 return str(self.hdwallet(index).private_key())
103
104 def hdwallet(
105 self,
106 index: int = 0
107 ) -> HDWallet:
108 """
109 Creates an HDWallet object suitable for the Radix blockchain with the passed account index.
110
111 Args:
112 index (int): The account index to create the HDWallet object for.
113
114 Returns:
115 HDWallet: An HD wallet object created with the Radix Parameters for a given account
116 index.
117 """
118
119 hdwallet: HDWallet = HDWallet()
120 hdwallet.from_seed(seed=self.seed.hex())
121 for _, values_tuple in self.HD_WALLET_PARAMS.items():
122 value, hardened = values_tuple
123 hdwallet.from_index(value, hardened=hardened)
124 hdwallet.from_index(index, True)
125
126 return hdwallet
127
128 def sign(
129 self,
130 data: str,
131 index: int = 0
132 ) -> str:
133 """
134 Signs the given data using the private keys for the account at the specified account index.
135
136 Arguments:
137 data (str): A string of the data which we wish to sign.
138 index (int): The account index to get the private keys for.
139
140 Returns:
141 str: A string of the signed data
142 """
143
144 signing_key: SigningKey = ecdsa.SigningKey.from_string( # type: ignore
145 string=bytearray.fromhex(self.private_key(index)),
146 curve=SECP256k1,
147 hashfunc=hashlib.sha256
148 )
149
150 return signing_key.sign_digest( # type: ignore
151 digest=bytearray.fromhex(data),
152 sigencode=sigencode_der
153 ).hex()
154package main
155
156import (
157 "encoding/hex"
158 "fmt"
159 "log"
160
161 "github.com/cosmos/cosmos-sdk/crypto/hd"
162 "github.com/cosmos/go-bip39"
163 "github.com/decred/dcrd/bech32"
164 "github.com/tendermint/tendermint/crypto/secp256k1"
165)
166
167func main() {
168
169 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
170 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
171
172 master, ch := hd.ComputeMastersFromSeed(seed)
173 path := "m/44'/1022'/0'/0/0'"
174 priv, err := hd.DerivePrivateKeyForPath(master, ch, path)
175 if err != nil {
176 t.Fatal(err)
177 }
178 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/118'/0'/0/0'
179 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a
180
181 var privKey = secp256k1.PrivKey(priv)
182 pubKey := privKey.PubKey()
183 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8
184
185 //str := "test"
186 str := "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842"
187 //hx := hex.EncodeToString([]byte(str))
188 //fmt.Println(hx)
189 sign, err := privKey.Sign([]byte(str))
190 if err != nil {
191 return
192 }
193
194 fmt.Println(hex.EncodeToString(sign))
195}
19633f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
197026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
198package main
199
200import (
201 "encoding/hex"
202 "fmt"
203
204 "math/big"
205
206 "github.com/cosmos/cosmos-sdk/crypto/hd"
207 "github.com/cosmos/go-bip39"
208 "github.com/tendermint/tendermint/crypto/secp256k1"
209
210 //"github.com/btcsuite/btcd/btcec"
211 "golang.org/x/crypto/cryptobyte"
212 "golang.org/x/crypto/cryptobyte/asn1"
213)
214
215func main() {
216
217 //
218 // Derive private and public key (this part works)
219 //
220 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
221 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
222
223 master, ch := hd.ComputeMastersFromSeed(seed)
224 path := "m/44'/1022'/0'/0/0'"
225 priv, _ := hd.DerivePrivateKeyForPath(master, ch, path)
226 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/1022'/0'/0/0'
227 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 33f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
228
229 var privKey = secp256k1.PrivKey(priv)
230 pubKey := privKey.PubKey()
231 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
232
233 //
234 // Sign (this part needs to be fixed)
235 //
236 data := "test"
237
238 signature, _ := privKey.Sign([]byte(data))
239 fmt.Println(hex.EncodeToString(signature))
240
241 rVal := new(big.Int)
242 rVal.SetBytes(signature[0:32])
243 sVal := new(big.Int)
244 sVal.SetBytes(signature[32:64])
245 var b cryptobyte.Builder
246 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
247 b.AddASN1BigInt(rVal)
248 b.AddASN1BigInt(sVal)
249 })
250 signatureDER, _ := b.Bytes()
251 fmt.Println("Signature, DER: ", hex.EncodeToString(signatureDER))
252
253 /*
254 hash, _ := hex.DecodeString("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")
255
256 // Sign without hashing
257 privateKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), priv)
258 signature, _ := privateKey.Sign(hash[:])
259
260 // Convert to ASN1/DER
261 rVal := new(big.Int)
262 rVal.SetBytes(signature.R.Bytes())
263 sVal := new(big.Int)
264 sVal.SetBytes(signature.S.Bytes())
265 var b cryptobyte.Builder
266 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
267 b.AddASN1BigInt(rVal)
268 b.AddASN1BigInt(sVal)
269 })
270 signatureDER, _ := b.Bytes()
271 fmt.Println("Signature, DER: ", hex.EncodeToString(signatureDER))
272 */
273}
274Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
275Derivation Path: m/44'/1022'/0'/0/0'
276Private Key: 33f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
277Public Key: 026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
27857624717f71fae8b5917cde0f82dfe6c2e2104183ba01c6a1c9f0a8e66d3303e5035b52876d833522aace232c1d231b3aeeff303cf02d1677a240102365ce71b
279Signature, DER: 3044022057624717f71fae8b5917cde0f82dfe6c2e2104183ba01c6a1c9f0a8e66d3303e02205035b52876d833522aace232c1d231b3aeeff303cf02d1677a240102365ce71b
280return signing_key.sign_digest( # type: ignore
281 digest=bytearray.fromhex(data),
282 sigencode=sigencode_der
283).hex()
284
can be replaced by
1 def test_sign_message(self):
2 """ Tests the ability of the signer to sing message """
3
4 # Loading up the signer object to use for the operation
5 signer: TestSigners = TestSigners.from_mnemonic("blast about old claw current first paste risk involve victory edit current")
6 sample_payload_to_sign = "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842'
7 # print("test".encode("UTF-8").hex())
8 s = signer.sign(sample_payload_to_sign)
9 print(s)
10
11
12from typing import List, Tuple, Dict, Union, Any
13from hdwallet.hdwallet import HDWallet
14from ecdsa.util import sigencode_der
15from ecdsa.curves import SECP256k1
16from ecdsa.keys import SigningKey
17import mnemonic
18import hashlib
19import ecdsa
20
21
22class TestSigners():
23
24 HD_WALLET_PARAMS: Dict[str, Tuple[int, bool]] = {
25 "purpose": (44, True),
26 "coinType": (1022, True),
27 "account": (0, True),
28 "change": (0, False),
29 }
30
31 def __init__(
32 self,
33 seed: Union[bytes, bytearray, str]
34 ) -> None:
35 """ Instantiates a new signer object from the seed phrase
36
37 Args:
38 seed (Union[bytes, bytearray, str]): The seed phrase used to generate the public and
39 private keys.
40 """
41
42 self.seed: Union[bytes, bytearray] = seed if isinstance(seed, (bytes, bytearray)) else bytearray.fromhex(seed)
43
44 @classmethod
45 def from_mnemonic(
46 cls,
47 mnemonic_phrase: Union[str, List[str], Tuple[str]]
48 ) -> 'Signer':
49 """
50 Instantiates a new Signer object from the mnemonic phrase passed.
51
52 Args:
53 mnemonic_phrase (Union[str, :obj:`list` of :obj:`str`, :obj:`tuple` of :obj:`str`):
54 A string, list, or a tuple of the mnemonic phrase. If the argument is passed as an
55 iterable, then it will be joined with a space.
56
57 Returns:
58 Signer: A new signer initalized through the mnemonic phrase.
59 """
60
61 # If the supplied mnemonic phrase is a list then convert it to a string
62 if isinstance(mnemonic_phrase, (list, tuple)):
63 mnemonic_string: str = " ".join(mnemonic_phrase)
64 else:
65 mnemonic_string: str = mnemonic_phrase
66
67 mnemonic_string: str = " ".join(mnemonic_phrase) if isinstance(mnemonic_phrase,
68 (list, tuple)) else mnemonic_phrase
69
70 return cls(mnemonic.Mnemonic.to_seed(mnemonic_string))
71
72 def public_key(
73 self,
74 index: int = 0
75 ) -> str:
76 """
77 Gets the public key for the signer for the specified account index
78
79 Args:
80 index (int): The account index to get the public keys for.
81
82 Returns:
83 str: A string of the public key for the wallet
84 """
85
86 return str(self.hdwallet(index).public_key())
87
88 def private_key(
89 self,
90 index: int = 0
91 ) -> str:
92 """
93 Gets the private key for the signer for the specified account index
94
95 Args:
96 index (int): The account index to get the private keys for.
97
98 Returns:
99 str: A string of the private key for the wallet
100 """
101
102 return str(self.hdwallet(index).private_key())
103
104 def hdwallet(
105 self,
106 index: int = 0
107 ) -> HDWallet:
108 """
109 Creates an HDWallet object suitable for the Radix blockchain with the passed account index.
110
111 Args:
112 index (int): The account index to create the HDWallet object for.
113
114 Returns:
115 HDWallet: An HD wallet object created with the Radix Parameters for a given account
116 index.
117 """
118
119 hdwallet: HDWallet = HDWallet()
120 hdwallet.from_seed(seed=self.seed.hex())
121 for _, values_tuple in self.HD_WALLET_PARAMS.items():
122 value, hardened = values_tuple
123 hdwallet.from_index(value, hardened=hardened)
124 hdwallet.from_index(index, True)
125
126 return hdwallet
127
128 def sign(
129 self,
130 data: str,
131 index: int = 0
132 ) -> str:
133 """
134 Signs the given data using the private keys for the account at the specified account index.
135
136 Arguments:
137 data (str): A string of the data which we wish to sign.
138 index (int): The account index to get the private keys for.
139
140 Returns:
141 str: A string of the signed data
142 """
143
144 signing_key: SigningKey = ecdsa.SigningKey.from_string( # type: ignore
145 string=bytearray.fromhex(self.private_key(index)),
146 curve=SECP256k1,
147 hashfunc=hashlib.sha256
148 )
149
150 return signing_key.sign_digest( # type: ignore
151 digest=bytearray.fromhex(data),
152 sigencode=sigencode_der
153 ).hex()
154package main
155
156import (
157 "encoding/hex"
158 "fmt"
159 "log"
160
161 "github.com/cosmos/cosmos-sdk/crypto/hd"
162 "github.com/cosmos/go-bip39"
163 "github.com/decred/dcrd/bech32"
164 "github.com/tendermint/tendermint/crypto/secp256k1"
165)
166
167func main() {
168
169 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
170 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
171
172 master, ch := hd.ComputeMastersFromSeed(seed)
173 path := "m/44'/1022'/0'/0/0'"
174 priv, err := hd.DerivePrivateKeyForPath(master, ch, path)
175 if err != nil {
176 t.Fatal(err)
177 }
178 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/118'/0'/0/0'
179 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 69668f2378b43009b16b5c6eb5e405d9224ca2a326a65a17919e567105fa4e5a
180
181 var privKey = secp256k1.PrivKey(priv)
182 pubKey := privKey.PubKey()
183 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 03de79435cbc8a799efc24cdce7d3b180fb014d5f19949fb8d61de3f21b9f6c1f8
184
185 //str := "test"
186 str := "75628d14409a5126e6c882d05422c06f5eccaa192c082a9a5695a8e707109842"
187 //hx := hex.EncodeToString([]byte(str))
188 //fmt.Println(hx)
189 sign, err := privKey.Sign([]byte(str))
190 if err != nil {
191 return
192 }
193
194 fmt.Println(hex.EncodeToString(sign))
195}
19633f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
197026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
198package main
199
200import (
201 "encoding/hex"
202 "fmt"
203
204 "math/big"
205
206 "github.com/cosmos/cosmos-sdk/crypto/hd"
207 "github.com/cosmos/go-bip39"
208 "github.com/tendermint/tendermint/crypto/secp256k1"
209
210 //"github.com/btcsuite/btcd/btcec"
211 "golang.org/x/crypto/cryptobyte"
212 "golang.org/x/crypto/cryptobyte/asn1"
213)
214
215func main() {
216
217 //
218 // Derive private and public key (this part works)
219 //
220 seed := bip39.NewSeed("blast about old claw current first paste risk involve victory edit current", "")
221 fmt.Println("Seed: ", hex.EncodeToString(seed)) // Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
222
223 master, ch := hd.ComputeMastersFromSeed(seed)
224 path := "m/44'/1022'/0'/0/0'"
225 priv, _ := hd.DerivePrivateKeyForPath(master, ch, path)
226 fmt.Println("Derivation Path: ", path) // Derivation Path: m/44'/1022'/0'/0/0'
227 fmt.Println("Private Key: ", hex.EncodeToString(priv)) // Private Key: 33f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
228
229 var privKey = secp256k1.PrivKey(priv)
230 pubKey := privKey.PubKey()
231 fmt.Println("Public Key: ", hex.EncodeToString(pubKey.Bytes())) // Public Key: 026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
232
233 //
234 // Sign (this part needs to be fixed)
235 //
236 data := "test"
237
238 signature, _ := privKey.Sign([]byte(data))
239 fmt.Println(hex.EncodeToString(signature))
240
241 rVal := new(big.Int)
242 rVal.SetBytes(signature[0:32])
243 sVal := new(big.Int)
244 sVal.SetBytes(signature[32:64])
245 var b cryptobyte.Builder
246 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
247 b.AddASN1BigInt(rVal)
248 b.AddASN1BigInt(sVal)
249 })
250 signatureDER, _ := b.Bytes()
251 fmt.Println("Signature, DER: ", hex.EncodeToString(signatureDER))
252
253 /*
254 hash, _ := hex.DecodeString("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08")
255
256 // Sign without hashing
257 privateKey, _ := btcec.PrivKeyFromBytes(btcec.S256(), priv)
258 signature, _ := privateKey.Sign(hash[:])
259
260 // Convert to ASN1/DER
261 rVal := new(big.Int)
262 rVal.SetBytes(signature.R.Bytes())
263 sVal := new(big.Int)
264 sVal.SetBytes(signature.S.Bytes())
265 var b cryptobyte.Builder
266 b.AddASN1(asn1.SEQUENCE, func(b *cryptobyte.Builder) {
267 b.AddASN1BigInt(rVal)
268 b.AddASN1BigInt(sVal)
269 })
270 signatureDER, _ := b.Bytes()
271 fmt.Println("Signature, DER: ", hex.EncodeToString(signatureDER))
272 */
273}
274Seed: dd5ffa7088c0fa4c665085bca7096a61e42ba92e7243a8ad7fbc6975a4aeea1845c6b668ebacd024fd2ca215c6cd510be7a9815528016af3a5e6f47d1cca30dd
275Derivation Path: m/44'/1022'/0'/0/0'
276Private Key: 33f34dad4bc0ce9dc320863509aed43cab33a93a29752779ae0df6dbbea33e56
277Public Key: 026557fe37d5cab1cc8edf474f4baff67dbb2305f1764e42d31b09f83296f5de2b
27857624717f71fae8b5917cde0f82dfe6c2e2104183ba01c6a1c9f0a8e66d3303e5035b52876d833522aace232c1d231b3aeeff303cf02d1677a240102365ce71b
279Signature, DER: 3044022057624717f71fae8b5917cde0f82dfe6c2e2104183ba01c6a1c9f0a8e66d3303e02205035b52876d833522aace232c1d231b3aeeff303cf02d1677a240102365ce71b
280return signing_key.sign_digest( # type: ignore
281 digest=bytearray.fromhex(data),
282 sigencode=sigencode_der
283).hex()
284from ecdsa.util import sigdecode_der
285signature = signing_key.sign_digest( # from Python Code
286 digest=bytearray.fromhex(data),
287 sigencode=sigencode_der
288)
289#signature = bytes.fromhex('3044022057624717f71fae8b5917cde0f82dfe6c2e2104183ba01c6a1c9f0a8e66d3303e02205035b52876d833522aace232c1d231b3aeeff303cf02d1677a240102365ce71b') # from Go code
290verifying_key = signing_key.verifying_key
291verified = verifying_key.verify_digest(signature, digest=bytearray.fromhex(data), sigdecode=sigdecode_der)
292print(verified)
293return signature.hex()
294
The test shows that both, the Python and Go code signatures are successfully verified, proving that the signature generated with the Go code is valid.
Remark 3: The Python code generates a non-deterministic signature, i.e. the signature is different even with identical input data.
In contrast, the Go code generates a deterministic signature, i.e. the signature is the same for identical input data (see here).
If the Go code should also generate a non-deterministic signature, other libraries must be used on the Go side (but this might not actually be necessary, since the non-deterministic and the deterministic variant are established algorithms and generate valid signatures in accordance with the above test).
QUESTION
Flag provided but not defined: -rpc
Asked 2022-Feb-19 at 20:07Am starting off in blockchain development using the book Mastering Blockchain - A deep dive into distributed ledgers, consensus protocols, smart contracts, DApps, cryptocurrencies, Ethereum,
Am using WSL with geth version 1.10.9.
1$geth version
2Geth
3Version: 1.10.9-stable
4Git Commit: eae3b1946a276ac099e0018fc792d9e8c3bfda6d
5Architecture: amd64
6Go Version: go1.17
7Operating System: linux
8GOPATH=
9GOROOT=go
10
Am trying to start geth, but am getting the error that the --rpc flag is not defined.
This is the command I am trying to run:
geth --datadir ~/etherprivate/ --networkid 786 --rpc --rpcapi 'web3,eth,net,debug,personal' --rpccorsdomain '*'
Any help on how I can solve it?
ANSWER
Answered 2021-Oct-11 at 23:20It appears 1.10.9-stable version has a problem and is returning a -rpc error. GETH 1.10.8-stable version works fine when running the geth command with --rpc
QUESTION
ParserError: Source file requires different compiler version
Asked 2022-Feb-08 at 13:18I tried all that you mentioned in the discussion here (in other questions) and at https://github.com/smartcontractkit/full-blockchain-solidity-course-py/discussions/522 , however it is not solving the issue for me, I also noticed that the current compiler version remains (current compiler is 0.6.12+commit.27d51765.Windows.msvc). But when I right click and select Solidty:Compiler information, it shows 0.8.0.
from output:
1Retrieving compiler information:
2Compiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang
3
Not sure if that is related to the issue I face. Anyways starting with the problem I see when running brownie compile. I get the error below:
error in terminal:
1Retrieving compiler information:
2Compiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang
3PS D:\Python projects\Solidity dev\demo\smartcontract-lottery> brownie compile
4INFO: Could not find files for the given pattern(s).
5Brownie v1.17.2 - Python development framework for Ethereum
6
7Compiling contracts...
8 Solc version: 0.6.12
9 Optimizer: Enabled Runs: 200
10 EVM Version: Istanbul
11CompilerError: solc returned the following errors:
12
13C:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
14pragma solidity ^0.8.0;
15^---------------------^
16
17C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
18pragma solidity ^0.8.0;
19^---------------------^
20
21PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
22
My .sol file is Lottery.sol:
1Retrieving compiler information:
2Compiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang
3PS D:\Python projects\Solidity dev\demo\smartcontract-lottery> brownie compile
4INFO: Could not find files for the given pattern(s).
5Brownie v1.17.2 - Python development framework for Ethereum
6
7Compiling contracts...
8 Solc version: 0.6.12
9 Optimizer: Enabled Runs: 200
10 EVM Version: Istanbul
11CompilerError: solc returned the following errors:
12
13C:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
14pragma solidity ^0.8.0;
15^---------------------^
16
17C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
18pragma solidity ^0.8.0;
19^---------------------^
20
21PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
22// SPDX-License-Identifier: MIT
23pragma solidity ^0.6.0;
24
25import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
26import "@openzeppelin/contracts/access/Ownable.sol";
27import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
28
29contract Lottery is VRFConsumerBase, Ownable {
30 uint256 usdEntryFee;
31 address payable[] public players;
32 address payable public recentWinner;
33 uint256 public randomness;
34 AggregatorV3Interface internal ethUsdPriceFeed;
35 enum LOTTERY_STATE {
36 OPEN,
37 CLOSED,
38 CALCULATING_WINNER
39 }
40
41 LOTTERY_STATE public lottery_state;
42 uint256 public fee;
43 bytes32 public keyhash;
44
45 constructor(
46 address _priceFeedAddress,
47 address _vrfCoordinator,
48 address _link,
49 uint256 _fee,
50 bytes32 _keyhash
51 ) public VRFConsumerBase(_vrfCoordinator, _link) {
52 usdEntryFee = 50 * (10**18);
53 ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
54 lottery_state = LOTTERY_STATE.CLOSED;
55 fee = _fee;
56 keyhash = _keyhash;
57 }
58
59 function enter() public payable {
60 //$50 min
61 require(lottery_state == LOTTERY_STATE.OPEN);
62 require(msg.value >= getEntranceFee(), "Not enough ETH!");
63 players.push(payable(msg.sender));
64 }
65
66 function getEntranceFee() public view returns (uint256) {
67 (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
68 uint256 adjustedPrice = uint256(price) * 10**12; //18 decimals
69 //$50, 2000 ETH
70 //50/2000
71 //50*10000/2000
72 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
73 return costToEnter;
74 }
75
76 function startLottery() public onlyOwner {
77 require(
78 lottery_state == LOTTERY_STATE.CLOSED,
79 "cant start a new lottery yet"
80 );
81 lottery_state = LOTTERY_STATE.OPEN;
82 }
83
84 function endLottery() public onlyOwner {
85 lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
86 bytes32 requestId = requestRandomness(keyhash, fee);
87 }
88
89 function FulfillRandomness(bytes32 _requestId, uint256 _randomness)
90 internal
91 override
92 {
93 require(
94 lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
95 "you arent there yet!"
96 );
97
98 require(_randomness > 0, "random not found");
99 uint256 indexOfWinner = _randomness % players.length;
100 recentWinner = players[indexOfWinner];
101 recentWinner.transfer(address(this).balance);
102
103 //reset
104
105 players = new address payable[](0);
106 lottery_state = LOTTERY_STATE.CLOSED;
107 randomness = _randomness;
108 }
109}
110
111
I also tried to google some solutions so my settings.json file is a bit different but that didnt help too.
settings.json:
1Retrieving compiler information:
2Compiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang
3PS D:\Python projects\Solidity dev\demo\smartcontract-lottery> brownie compile
4INFO: Could not find files for the given pattern(s).
5Brownie v1.17.2 - Python development framework for Ethereum
6
7Compiling contracts...
8 Solc version: 0.6.12
9 Optimizer: Enabled Runs: 200
10 EVM Version: Istanbul
11CompilerError: solc returned the following errors:
12
13C:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
14pragma solidity ^0.8.0;
15^---------------------^
16
17C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
18pragma solidity ^0.8.0;
19^---------------------^
20
21PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
22// SPDX-License-Identifier: MIT
23pragma solidity ^0.6.0;
24
25import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
26import "@openzeppelin/contracts/access/Ownable.sol";
27import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
28
29contract Lottery is VRFConsumerBase, Ownable {
30 uint256 usdEntryFee;
31 address payable[] public players;
32 address payable public recentWinner;
33 uint256 public randomness;
34 AggregatorV3Interface internal ethUsdPriceFeed;
35 enum LOTTERY_STATE {
36 OPEN,
37 CLOSED,
38 CALCULATING_WINNER
39 }
40
41 LOTTERY_STATE public lottery_state;
42 uint256 public fee;
43 bytes32 public keyhash;
44
45 constructor(
46 address _priceFeedAddress,
47 address _vrfCoordinator,
48 address _link,
49 uint256 _fee,
50 bytes32 _keyhash
51 ) public VRFConsumerBase(_vrfCoordinator, _link) {
52 usdEntryFee = 50 * (10**18);
53 ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
54 lottery_state = LOTTERY_STATE.CLOSED;
55 fee = _fee;
56 keyhash = _keyhash;
57 }
58
59 function enter() public payable {
60 //$50 min
61 require(lottery_state == LOTTERY_STATE.OPEN);
62 require(msg.value >= getEntranceFee(), "Not enough ETH!");
63 players.push(payable(msg.sender));
64 }
65
66 function getEntranceFee() public view returns (uint256) {
67 (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
68 uint256 adjustedPrice = uint256(price) * 10**12; //18 decimals
69 //$50, 2000 ETH
70 //50/2000
71 //50*10000/2000
72 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
73 return costToEnter;
74 }
75
76 function startLottery() public onlyOwner {
77 require(
78 lottery_state == LOTTERY_STATE.CLOSED,
79 "cant start a new lottery yet"
80 );
81 lottery_state = LOTTERY_STATE.OPEN;
82 }
83
84 function endLottery() public onlyOwner {
85 lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
86 bytes32 requestId = requestRandomness(keyhash, fee);
87 }
88
89 function FulfillRandomness(bytes32 _requestId, uint256 _randomness)
90 internal
91 override
92 {
93 require(
94 lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
95 "you arent there yet!"
96 );
97
98 require(_randomness > 0, "random not found");
99 uint256 indexOfWinner = _randomness % players.length;
100 recentWinner = players[indexOfWinner];
101 recentWinner.transfer(address(this).balance);
102
103 //reset
104
105 players = new address payable[](0);
106 lottery_state = LOTTERY_STATE.CLOSED;
107 randomness = _randomness;
108 }
109}
110
111{
112 "solidity.compileUsingRemoteVersion": "v0.8.0+commit.c7dfd78e",
113 "solidity.defaultCompiler": "remote",
114 "solidity.compileUsingLocalVersion": "d:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery\\soljson-v0.8.0+commit.c7dfd78e.js"
115 // "solidity.compileUsingRemoteVersion": "v0.7.4+commit.3f05b770",
116 // "solidity.enableLocalNodeCompiler": false
117}
118
In the brownie-config.yaml, I tried all the versions of openzepplin contracts too from old to latest (4.4.0, 4.3.0,4.3.2 etc), but same error.
brownie-config.yaml
1Retrieving compiler information:
2Compiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang
3PS D:\Python projects\Solidity dev\demo\smartcontract-lottery> brownie compile
4INFO: Could not find files for the given pattern(s).
5Brownie v1.17.2 - Python development framework for Ethereum
6
7Compiling contracts...
8 Solc version: 0.6.12
9 Optimizer: Enabled Runs: 200
10 EVM Version: Istanbul
11CompilerError: solc returned the following errors:
12
13C:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
14pragma solidity ^0.8.0;
15^---------------------^
16
17C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
18pragma solidity ^0.8.0;
19^---------------------^
20
21PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
22// SPDX-License-Identifier: MIT
23pragma solidity ^0.6.0;
24
25import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
26import "@openzeppelin/contracts/access/Ownable.sol";
27import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
28
29contract Lottery is VRFConsumerBase, Ownable {
30 uint256 usdEntryFee;
31 address payable[] public players;
32 address payable public recentWinner;
33 uint256 public randomness;
34 AggregatorV3Interface internal ethUsdPriceFeed;
35 enum LOTTERY_STATE {
36 OPEN,
37 CLOSED,
38 CALCULATING_WINNER
39 }
40
41 LOTTERY_STATE public lottery_state;
42 uint256 public fee;
43 bytes32 public keyhash;
44
45 constructor(
46 address _priceFeedAddress,
47 address _vrfCoordinator,
48 address _link,
49 uint256 _fee,
50 bytes32 _keyhash
51 ) public VRFConsumerBase(_vrfCoordinator, _link) {
52 usdEntryFee = 50 * (10**18);
53 ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
54 lottery_state = LOTTERY_STATE.CLOSED;
55 fee = _fee;
56 keyhash = _keyhash;
57 }
58
59 function enter() public payable {
60 //$50 min
61 require(lottery_state == LOTTERY_STATE.OPEN);
62 require(msg.value >= getEntranceFee(), "Not enough ETH!");
63 players.push(payable(msg.sender));
64 }
65
66 function getEntranceFee() public view returns (uint256) {
67 (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
68 uint256 adjustedPrice = uint256(price) * 10**12; //18 decimals
69 //$50, 2000 ETH
70 //50/2000
71 //50*10000/2000
72 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
73 return costToEnter;
74 }
75
76 function startLottery() public onlyOwner {
77 require(
78 lottery_state == LOTTERY_STATE.CLOSED,
79 "cant start a new lottery yet"
80 );
81 lottery_state = LOTTERY_STATE.OPEN;
82 }
83
84 function endLottery() public onlyOwner {
85 lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
86 bytes32 requestId = requestRandomness(keyhash, fee);
87 }
88
89 function FulfillRandomness(bytes32 _requestId, uint256 _randomness)
90 internal
91 override
92 {
93 require(
94 lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
95 "you arent there yet!"
96 );
97
98 require(_randomness > 0, "random not found");
99 uint256 indexOfWinner = _randomness % players.length;
100 recentWinner = players[indexOfWinner];
101 recentWinner.transfer(address(this).balance);
102
103 //reset
104
105 players = new address payable[](0);
106 lottery_state = LOTTERY_STATE.CLOSED;
107 randomness = _randomness;
108 }
109}
110
111{
112 "solidity.compileUsingRemoteVersion": "v0.8.0+commit.c7dfd78e",
113 "solidity.defaultCompiler": "remote",
114 "solidity.compileUsingLocalVersion": "d:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery\\soljson-v0.8.0+commit.c7dfd78e.js"
115 // "solidity.compileUsingRemoteVersion": "v0.7.4+commit.3f05b770",
116 // "solidity.enableLocalNodeCompiler": false
117}
118dependencies:
119 - smartcontractkit/chainlink-brownie-contracts@1.1.1
120 - OpenZeppelin/openzeppelin-contracts@4.3.0
121compiler:
122 solc:
123 remappings:
124 - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1'
125 - '@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.3.0'
126networks:
127 mainnet-fork:
128 eth_usd_price_feed: '0xaEA2808407B7319A31A383B6F8B60f04BCa23cE2'
129
I also tried to change the compiler in lottery.sol file with
1Retrieving compiler information:
2Compiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang
3PS D:\Python projects\Solidity dev\demo\smartcontract-lottery> brownie compile
4INFO: Could not find files for the given pattern(s).
5Brownie v1.17.2 - Python development framework for Ethereum
6
7Compiling contracts...
8 Solc version: 0.6.12
9 Optimizer: Enabled Runs: 200
10 EVM Version: Istanbul
11CompilerError: solc returned the following errors:
12
13C:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
14pragma solidity ^0.8.0;
15^---------------------^
16
17C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
18pragma solidity ^0.8.0;
19^---------------------^
20
21PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
22// SPDX-License-Identifier: MIT
23pragma solidity ^0.6.0;
24
25import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
26import "@openzeppelin/contracts/access/Ownable.sol";
27import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
28
29contract Lottery is VRFConsumerBase, Ownable {
30 uint256 usdEntryFee;
31 address payable[] public players;
32 address payable public recentWinner;
33 uint256 public randomness;
34 AggregatorV3Interface internal ethUsdPriceFeed;
35 enum LOTTERY_STATE {
36 OPEN,
37 CLOSED,
38 CALCULATING_WINNER
39 }
40
41 LOTTERY_STATE public lottery_state;
42 uint256 public fee;
43 bytes32 public keyhash;
44
45 constructor(
46 address _priceFeedAddress,
47 address _vrfCoordinator,
48 address _link,
49 uint256 _fee,
50 bytes32 _keyhash
51 ) public VRFConsumerBase(_vrfCoordinator, _link) {
52 usdEntryFee = 50 * (10**18);
53 ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
54 lottery_state = LOTTERY_STATE.CLOSED;
55 fee = _fee;
56 keyhash = _keyhash;
57 }
58
59 function enter() public payable {
60 //$50 min
61 require(lottery_state == LOTTERY_STATE.OPEN);
62 require(msg.value >= getEntranceFee(), "Not enough ETH!");
63 players.push(payable(msg.sender));
64 }
65
66 function getEntranceFee() public view returns (uint256) {
67 (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
68 uint256 adjustedPrice = uint256(price) * 10**12; //18 decimals
69 //$50, 2000 ETH
70 //50/2000
71 //50*10000/2000
72 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
73 return costToEnter;
74 }
75
76 function startLottery() public onlyOwner {
77 require(
78 lottery_state == LOTTERY_STATE.CLOSED,
79 "cant start a new lottery yet"
80 );
81 lottery_state = LOTTERY_STATE.OPEN;
82 }
83
84 function endLottery() public onlyOwner {
85 lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
86 bytes32 requestId = requestRandomness(keyhash, fee);
87 }
88
89 function FulfillRandomness(bytes32 _requestId, uint256 _randomness)
90 internal
91 override
92 {
93 require(
94 lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
95 "you arent there yet!"
96 );
97
98 require(_randomness > 0, "random not found");
99 uint256 indexOfWinner = _randomness % players.length;
100 recentWinner = players[indexOfWinner];
101 recentWinner.transfer(address(this).balance);
102
103 //reset
104
105 players = new address payable[](0);
106 lottery_state = LOTTERY_STATE.CLOSED;
107 randomness = _randomness;
108 }
109}
110
111{
112 "solidity.compileUsingRemoteVersion": "v0.8.0+commit.c7dfd78e",
113 "solidity.defaultCompiler": "remote",
114 "solidity.compileUsingLocalVersion": "d:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery\\soljson-v0.8.0+commit.c7dfd78e.js"
115 // "solidity.compileUsingRemoteVersion": "v0.7.4+commit.3f05b770",
116 // "solidity.enableLocalNodeCompiler": false
117}
118dependencies:
119 - smartcontractkit/chainlink-brownie-contracts@1.1.1
120 - OpenZeppelin/openzeppelin-contracts@4.3.0
121compiler:
122 solc:
123 remappings:
124 - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1'
125 - '@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.3.0'
126networks:
127 mainnet-fork:
128 eth_usd_price_feed: '0xaEA2808407B7319A31A383B6F8B60f04BCa23cE2'
129// SPDX-License-Identifier: MIT
130pragma solidity ^0.8.0;
131
Now I get a different error. Completely lost here :(
terminal:
1Retrieving compiler information:
2Compiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang
3PS D:\Python projects\Solidity dev\demo\smartcontract-lottery> brownie compile
4INFO: Could not find files for the given pattern(s).
5Brownie v1.17.2 - Python development framework for Ethereum
6
7Compiling contracts...
8 Solc version: 0.6.12
9 Optimizer: Enabled Runs: 200
10 EVM Version: Istanbul
11CompilerError: solc returned the following errors:
12
13C:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
14pragma solidity ^0.8.0;
15^---------------------^
16
17C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
18pragma solidity ^0.8.0;
19^---------------------^
20
21PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
22// SPDX-License-Identifier: MIT
23pragma solidity ^0.6.0;
24
25import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
26import "@openzeppelin/contracts/access/Ownable.sol";
27import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
28
29contract Lottery is VRFConsumerBase, Ownable {
30 uint256 usdEntryFee;
31 address payable[] public players;
32 address payable public recentWinner;
33 uint256 public randomness;
34 AggregatorV3Interface internal ethUsdPriceFeed;
35 enum LOTTERY_STATE {
36 OPEN,
37 CLOSED,
38 CALCULATING_WINNER
39 }
40
41 LOTTERY_STATE public lottery_state;
42 uint256 public fee;
43 bytes32 public keyhash;
44
45 constructor(
46 address _priceFeedAddress,
47 address _vrfCoordinator,
48 address _link,
49 uint256 _fee,
50 bytes32 _keyhash
51 ) public VRFConsumerBase(_vrfCoordinator, _link) {
52 usdEntryFee = 50 * (10**18);
53 ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
54 lottery_state = LOTTERY_STATE.CLOSED;
55 fee = _fee;
56 keyhash = _keyhash;
57 }
58
59 function enter() public payable {
60 //$50 min
61 require(lottery_state == LOTTERY_STATE.OPEN);
62 require(msg.value >= getEntranceFee(), "Not enough ETH!");
63 players.push(payable(msg.sender));
64 }
65
66 function getEntranceFee() public view returns (uint256) {
67 (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
68 uint256 adjustedPrice = uint256(price) * 10**12; //18 decimals
69 //$50, 2000 ETH
70 //50/2000
71 //50*10000/2000
72 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
73 return costToEnter;
74 }
75
76 function startLottery() public onlyOwner {
77 require(
78 lottery_state == LOTTERY_STATE.CLOSED,
79 "cant start a new lottery yet"
80 );
81 lottery_state = LOTTERY_STATE.OPEN;
82 }
83
84 function endLottery() public onlyOwner {
85 lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
86 bytes32 requestId = requestRandomness(keyhash, fee);
87 }
88
89 function FulfillRandomness(bytes32 _requestId, uint256 _randomness)
90 internal
91 override
92 {
93 require(
94 lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
95 "you arent there yet!"
96 );
97
98 require(_randomness > 0, "random not found");
99 uint256 indexOfWinner = _randomness % players.length;
100 recentWinner = players[indexOfWinner];
101 recentWinner.transfer(address(this).balance);
102
103 //reset
104
105 players = new address payable[](0);
106 lottery_state = LOTTERY_STATE.CLOSED;
107 randomness = _randomness;
108 }
109}
110
111{
112 "solidity.compileUsingRemoteVersion": "v0.8.0+commit.c7dfd78e",
113 "solidity.defaultCompiler": "remote",
114 "solidity.compileUsingLocalVersion": "d:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery\\soljson-v0.8.0+commit.c7dfd78e.js"
115 // "solidity.compileUsingRemoteVersion": "v0.7.4+commit.3f05b770",
116 // "solidity.enableLocalNodeCompiler": false
117}
118dependencies:
119 - smartcontractkit/chainlink-brownie-contracts@1.1.1
120 - OpenZeppelin/openzeppelin-contracts@4.3.0
121compiler:
122 solc:
123 remappings:
124 - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1'
125 - '@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.3.0'
126networks:
127 mainnet-fork:
128 eth_usd_price_feed: '0xaEA2808407B7319A31A383B6F8B60f04BCa23cE2'
129// SPDX-License-Identifier: MIT
130pragma solidity ^0.8.0;
131INFO: Could not find files for the given pattern(s).
132Brownie v1.17.2 - Python development framework for Ethereum
133
134Compiling contracts...
135 Solc version: 0.8.11
136 Optimizer: Enabled Runs: 200
137 EVM Version: Istanbul
138CompilerError: solc returned the following errors:
139
140ParserError: Source file requires different compiler version (current compiler is 0.8.11+commit.d7f03943.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
141 --> C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol:2:1:
142 |
1432 | pragma solidity ^0.6.0;
144 | ^^^^^^^^^^^^^^^^^^^^^^^
145
146PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
147
I am very new to programing in solidity and this is the first course I am following, I don't want to give up so easily, any help is much appreciated.
ANSWER
Answered 2022-Jan-02 at 03:09i had the same issue. i had this compiler setting:
1Retrieving compiler information:
2Compiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang
3PS D:\Python projects\Solidity dev\demo\smartcontract-lottery> brownie compile
4INFO: Could not find files for the given pattern(s).
5Brownie v1.17.2 - Python development framework for Ethereum
6
7Compiling contracts...
8 Solc version: 0.6.12
9 Optimizer: Enabled Runs: 200
10 EVM Version: Istanbul
11CompilerError: solc returned the following errors:
12
13C:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
14pragma solidity ^0.8.0;
15^---------------------^
16
17C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
18pragma solidity ^0.8.0;
19^---------------------^
20
21PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
22// SPDX-License-Identifier: MIT
23pragma solidity ^0.6.0;
24
25import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
26import "@openzeppelin/contracts/access/Ownable.sol";
27import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
28
29contract Lottery is VRFConsumerBase, Ownable {
30 uint256 usdEntryFee;
31 address payable[] public players;
32 address payable public recentWinner;
33 uint256 public randomness;
34 AggregatorV3Interface internal ethUsdPriceFeed;
35 enum LOTTERY_STATE {
36 OPEN,
37 CLOSED,
38 CALCULATING_WINNER
39 }
40
41 LOTTERY_STATE public lottery_state;
42 uint256 public fee;
43 bytes32 public keyhash;
44
45 constructor(
46 address _priceFeedAddress,
47 address _vrfCoordinator,
48 address _link,
49 uint256 _fee,
50 bytes32 _keyhash
51 ) public VRFConsumerBase(_vrfCoordinator, _link) {
52 usdEntryFee = 50 * (10**18);
53 ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
54 lottery_state = LOTTERY_STATE.CLOSED;
55 fee = _fee;
56 keyhash = _keyhash;
57 }
58
59 function enter() public payable {
60 //$50 min
61 require(lottery_state == LOTTERY_STATE.OPEN);
62 require(msg.value >= getEntranceFee(), "Not enough ETH!");
63 players.push(payable(msg.sender));
64 }
65
66 function getEntranceFee() public view returns (uint256) {
67 (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
68 uint256 adjustedPrice = uint256(price) * 10**12; //18 decimals
69 //$50, 2000 ETH
70 //50/2000
71 //50*10000/2000
72 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
73 return costToEnter;
74 }
75
76 function startLottery() public onlyOwner {
77 require(
78 lottery_state == LOTTERY_STATE.CLOSED,
79 "cant start a new lottery yet"
80 );
81 lottery_state = LOTTERY_STATE.OPEN;
82 }
83
84 function endLottery() public onlyOwner {
85 lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
86 bytes32 requestId = requestRandomness(keyhash, fee);
87 }
88
89 function FulfillRandomness(bytes32 _requestId, uint256 _randomness)
90 internal
91 override
92 {
93 require(
94 lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
95 "you arent there yet!"
96 );
97
98 require(_randomness > 0, "random not found");
99 uint256 indexOfWinner = _randomness % players.length;
100 recentWinner = players[indexOfWinner];
101 recentWinner.transfer(address(this).balance);
102
103 //reset
104
105 players = new address payable[](0);
106 lottery_state = LOTTERY_STATE.CLOSED;
107 randomness = _randomness;
108 }
109}
110
111{
112 "solidity.compileUsingRemoteVersion": "v0.8.0+commit.c7dfd78e",
113 "solidity.defaultCompiler": "remote",
114 "solidity.compileUsingLocalVersion": "d:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery\\soljson-v0.8.0+commit.c7dfd78e.js"
115 // "solidity.compileUsingRemoteVersion": "v0.7.4+commit.3f05b770",
116 // "solidity.enableLocalNodeCompiler": false
117}
118dependencies:
119 - smartcontractkit/chainlink-brownie-contracts@1.1.1
120 - OpenZeppelin/openzeppelin-contracts@4.3.0
121compiler:
122 solc:
123 remappings:
124 - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1'
125 - '@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.3.0'
126networks:
127 mainnet-fork:
128 eth_usd_price_feed: '0xaEA2808407B7319A31A383B6F8B60f04BCa23cE2'
129// SPDX-License-Identifier: MIT
130pragma solidity ^0.8.0;
131INFO: Could not find files for the given pattern(s).
132Brownie v1.17.2 - Python development framework for Ethereum
133
134Compiling contracts...
135 Solc version: 0.8.11
136 Optimizer: Enabled Runs: 200
137 EVM Version: Istanbul
138CompilerError: solc returned the following errors:
139
140ParserError: Source file requires different compiler version (current compiler is 0.8.11+commit.d7f03943.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
141 --> C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol:2:1:
142 |
1432 | pragma solidity ^0.6.0;
144 | ^^^^^^^^^^^^^^^^^^^^^^^
145
146PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
147pragma solidity >=0.4.22 <0.9.0;
148
Since we are importing from openzeppelin
, I visied github repo and saw that it uses pragma solidity ^0.8.0;
So changed my setting to
1Retrieving compiler information:
2Compiler using remote version: 'v0.8.0+commit.c7dfd78e', solidity version: 0.8.0+commit.c7dfd78e.Emscripten.clang
3PS D:\Python projects\Solidity dev\demo\smartcontract-lottery> brownie compile
4INFO: Could not find files for the given pattern(s).
5Brownie v1.17.2 - Python development framework for Ethereum
6
7Compiling contracts...
8 Solc version: 0.6.12
9 Optimizer: Enabled Runs: 200
10 EVM Version: Istanbul
11CompilerError: solc returned the following errors:
12
13C:/Users/rosne/.brownie/packages/OpenZeppelin/openzeppelin-contracts@4.3.0/contracts/access/Ownable.sol:3:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
14pragma solidity ^0.8.0;
15^---------------------^
16
17C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.8/VRFConsumerBase.sol:2:1: ParserError: Source file requires different compiler version (current compiler is 0.6.12+commit.27d51765.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
18pragma solidity ^0.8.0;
19^---------------------^
20
21PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
22// SPDX-License-Identifier: MIT
23pragma solidity ^0.6.0;
24
25import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
26import "@openzeppelin/contracts/access/Ownable.sol";
27import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
28
29contract Lottery is VRFConsumerBase, Ownable {
30 uint256 usdEntryFee;
31 address payable[] public players;
32 address payable public recentWinner;
33 uint256 public randomness;
34 AggregatorV3Interface internal ethUsdPriceFeed;
35 enum LOTTERY_STATE {
36 OPEN,
37 CLOSED,
38 CALCULATING_WINNER
39 }
40
41 LOTTERY_STATE public lottery_state;
42 uint256 public fee;
43 bytes32 public keyhash;
44
45 constructor(
46 address _priceFeedAddress,
47 address _vrfCoordinator,
48 address _link,
49 uint256 _fee,
50 bytes32 _keyhash
51 ) public VRFConsumerBase(_vrfCoordinator, _link) {
52 usdEntryFee = 50 * (10**18);
53 ethUsdPriceFeed = AggregatorV3Interface(_priceFeedAddress);
54 lottery_state = LOTTERY_STATE.CLOSED;
55 fee = _fee;
56 keyhash = _keyhash;
57 }
58
59 function enter() public payable {
60 //$50 min
61 require(lottery_state == LOTTERY_STATE.OPEN);
62 require(msg.value >= getEntranceFee(), "Not enough ETH!");
63 players.push(payable(msg.sender));
64 }
65
66 function getEntranceFee() public view returns (uint256) {
67 (, int256 price, , , ) = ethUsdPriceFeed.latestRoundData();
68 uint256 adjustedPrice = uint256(price) * 10**12; //18 decimals
69 //$50, 2000 ETH
70 //50/2000
71 //50*10000/2000
72 uint256 costToEnter = (usdEntryFee * 10**18) / adjustedPrice;
73 return costToEnter;
74 }
75
76 function startLottery() public onlyOwner {
77 require(
78 lottery_state == LOTTERY_STATE.CLOSED,
79 "cant start a new lottery yet"
80 );
81 lottery_state = LOTTERY_STATE.OPEN;
82 }
83
84 function endLottery() public onlyOwner {
85 lottery_state = LOTTERY_STATE.CALCULATING_WINNER;
86 bytes32 requestId = requestRandomness(keyhash, fee);
87 }
88
89 function FulfillRandomness(bytes32 _requestId, uint256 _randomness)
90 internal
91 override
92 {
93 require(
94 lottery_state == LOTTERY_STATE.CALCULATING_WINNER,
95 "you arent there yet!"
96 );
97
98 require(_randomness > 0, "random not found");
99 uint256 indexOfWinner = _randomness % players.length;
100 recentWinner = players[indexOfWinner];
101 recentWinner.transfer(address(this).balance);
102
103 //reset
104
105 players = new address payable[](0);
106 lottery_state = LOTTERY_STATE.CLOSED;
107 randomness = _randomness;
108 }
109}
110
111{
112 "solidity.compileUsingRemoteVersion": "v0.8.0+commit.c7dfd78e",
113 "solidity.defaultCompiler": "remote",
114 "solidity.compileUsingLocalVersion": "d:\\Python projects\\Solidity dev\\demo\\smartcontract-lottery\\soljson-v0.8.0+commit.c7dfd78e.js"
115 // "solidity.compileUsingRemoteVersion": "v0.7.4+commit.3f05b770",
116 // "solidity.enableLocalNodeCompiler": false
117}
118dependencies:
119 - smartcontractkit/chainlink-brownie-contracts@1.1.1
120 - OpenZeppelin/openzeppelin-contracts@4.3.0
121compiler:
122 solc:
123 remappings:
124 - '@chainlink=smartcontractkit/chainlink-brownie-contracts@0.2.1'
125 - '@openzeppelin=OpenZeppelin/openzeppelin-contracts@4.3.0'
126networks:
127 mainnet-fork:
128 eth_usd_price_feed: '0xaEA2808407B7319A31A383B6F8B60f04BCa23cE2'
129// SPDX-License-Identifier: MIT
130pragma solidity ^0.8.0;
131INFO: Could not find files for the given pattern(s).
132Brownie v1.17.2 - Python development framework for Ethereum
133
134Compiling contracts...
135 Solc version: 0.8.11
136 Optimizer: Enabled Runs: 200
137 EVM Version: Istanbul
138CompilerError: solc returned the following errors:
139
140ParserError: Source file requires different compiler version (current compiler is 0.8.11+commit.d7f03943.Windows.msvc) - note that nightly builds are considered to be strictly less than the released version
141 --> C:/Users/rosne/.brownie/packages/smartcontractkit/chainlink-brownie-contracts@0.2.1/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol:2:1:
142 |
1432 | pragma solidity ^0.6.0;
144 | ^^^^^^^^^^^^^^^^^^^^^^^
145
146PS D:\Python projects\Solidity dev\demo\smartcontract-lottery>
147pragma solidity >=0.4.22 <0.9.0;
148 pragma solidity >=0.4.22 <0.8.0;
149
Community Discussions contain sources that include Stack Exchange Network