关于智能合约:使用Python开发DeFi项目

40次阅读

共计 12262 个字符,预计需要花费 31 分钟才能阅读完成。

原文链接:https://blog.chain.link/develop-python-defi-project/
原文题目:Develop a DeFi Project Using Python
原文作者:Patrick Collins

In this tutorial, we’ll walk through how to develop a DeFi project in Python. Decentralized finance (DeFi) is one of the most significant advancements of the blockchain and smart contract world and is often referred to as“the new fintech”. Right now, smart contract development is dominated by JavaScript, partially because JavaScript is the most commonly used language on the planet, and it’s easier to build full-stack applications with the“JavaScript everywhere”mentality that comes with Node.js. However, this isn’t the case with the fintech world of quantitative analysts, stock traders, and hedge funds. A majority of these fintech technology companies use Python for a variety of reasons:
在本文教程中,咱们将具体介绍如何应用 Python 开发 DeFi 我的项目。去中心化金融(DeFi)是区块链和智能合约世界里最重要的提高之一,且经常被称作“新金融科技”。目前,智能合约的开发由 JavaScript 语言主导,局部起因在于 JavaScript 是地球上最罕用的语言,而且因为 Node.js 带来的“JavaScript 无处不在”的思维,使得构建全栈应用程序变得更加容易。然而,对金融科技界中的定量分析师,股票交易员和对冲基金来说,状况则有所不同。大多数金融科技公司中出于各种起因而抉择应用 Python:

  • Great developer experience
  • Powerful AI and machine learning
  • Bundled fintech packages
  • Comprehensive analytic tools
  • Reliability in production settings
  • 杰出的开发者体验
  • 弱小的 AI 和机器学习反对
  • 配套的金融科技软件工具包
  • 全面的剖析工具
  • 生产环境中的可靠性


Source: eFinancialCareers
起源:eFinancialCareers

There is a reason why so many data scientists, academics, and fintech institutions use Python. Some projects in the DeFi space, like yearn.finance, share this sentiment and have built their entire DeFi platforms with Python and Solidity. It’s because of libraries and frameworks like web3.py and Brownie that we are able to see these projects come to life. Brownie is a Truffle-like framework (they are both quite“sweet”) that maintains your deployments, scripts, testing, and allows you to make an end-to-end backend.
为什么有泛滥数据科学家,学者和金融科技机构应用 Python 是有肯定起因的。DeFi 畛域中的某些我的项目,如 yearn.finance,也认可这种想法,并曾经应用 Python 和 Solidity 构建了他们的整个 DeFi 平台。因为有了 web3.py 和 Brownie 之类的库和框架,咱们才可能有机会看到这些我的项目的诞生。Brownie 是一个相似 Truffle 的框架(它们都十分“甜”,注:Brownie- 布朗尼蛋糕;Truffle- 松露),可能反对我的项目部署,编写脚本,测试等,且可能进行端到端的后端开发。

Web3.py and Brownie also come with“mixes”where you can pre-open a project with some boilerplate code. This is what we will work with today, the Chainlink Brownie mix.
Web3.py 和 Brownie 也能“混合”应用,你能够事后关上一个我的项目并在其中应用一些样板代码。这就是咱们明天将要应用的 Chainlink Brownie mix。

Now why do we want to use Chainlink + Python? Just as Python is the de facto programming language for fintech, Chainlink is the de facto oracle solution for feeding off-chain data into DeFi smart contracts, currently securing more than $7B in value for top DeFi protocols. The combination of these two technologies offers a powerful framework for securely decentralizing the fintech landscape.
当初咱们为什么要应用 Chainlink + Python?正如 Python 是金融科技领域中的首选编程语言,Chainlink 事实上也是将链下数据带到 DeFi 智能合约中的首选预言机解决方案,以后正守护着超过 70 亿美金的顶级 DeFi 协定的价值。这两种技术的联合为平安去中心化金融科技领域提供了弱小的框架撑持。

Here’s a quick look at some of what Chainlink enabled in 2020.
上面是 Chainlink 在 2020 年启用的一些性能疾速概览。

Chainlink Network stats 2020
2020 年 Chainlink 网络统计数据

To get started building your DeFi app with Brownie and Python, you first need to install Python. It is not recommended to have Python below version 3.4 at this point, so please upgrade if you have an older version than 3.4. You can see your version of Python and verify it’s correctly installed by running:
要开始应用 Brownie 和 Python 构建 DeFi 利用,首先须要装置 Python。目前倡议 Python 的版本不低于 3.4,因而,如果你应用的版本低于 3.4,请先进行降级。你能够通过运行以下命令查看你的 Python 版本并验证它是否已正确装置:

python --version

Or, if with python3:
或者,如果用的是 Python3:

python3 --version

You’ll also need to have Ganache installed. Ganache is a one-click-blockchain written in Python that allows you to easily spin up a local blockchain. Though you do have to download it with npm and node.js, this will be the only piece of JavaScript that you have to interact with.
你还须要装置 Ganache。Ganache 是用 Python 编写的一键式区块链,它可让你很容易启动一个本地区块链。但你必须通过 npmnode.js来下载它,这将是惟一须要与之交互的 JavaScript 相干的内容。

First, you’ll need node.js and npm installed. Node.js comes installed with npm. Once you download it, you can check to see if it was done properly by running:
首先,须要装置 node.js 和 npm。Node.js 会随 npm 一起装置。下载后,能够通过运行以下命令来查看它是否正确装置:

npm -v

Then, you can install Ganache via the command line.
而后你就能够通过命令行装置 Ganache。

npm install -g ganache-cli

Once you have those installed, we will install eth-brownie the same way we install all Python repos, with pip!
装置完这些后,咱们就像装置其余所有的 Python 安装包一样,将以 pip 的形式装置eth-brownie

pip install eth-brownie

Or if with pip3:
或者,如果应用的是pip3

pip3 install eth-brownie

You’ll know you’ve done it right if you run brownie in your terminal, and you get an output similar to:
如果你能在终端执行 brownie 命令,就示意装置胜利,并且失去的输入相似于:

Brownie v1.13.0 - Python development framework for Ethereum
Usage:  brownie <command> [<args>...] [options <args>]
Commands:
  init               Initialize a new brownie project
  bake               Initialize from a brownie-mix template
  pm                 Install and manage external packages
  compile            Compile the contract source files
  console            Load the console
  test               Run test cases in the tests/ folder
  run                Run a script in the scripts/ folder
  accounts           Manage local accounts
  networks           Manage network settings
  gui                Load the GUI to view opcodes and test coverage
  analyze            Find security vulnerabilities using the MythX API
Options:
  --help -h          Display this message
  --version          Show version and exit
Type 'brownie <command> --help' for specific options and more information about
each command.

Also, you’ll need a MetaMask or other Ethereum wallet. If you’ve never used an ETH wallet before, you can watch this video to help you get set up. Please note this also shows getting testnet ETH for Ropsten, which Chainlink doesn’t support anymore. If you follow along, please use Kovan.
另外,你还须要一个 MetaMask 或其余以太坊钱包。如果你以前从未应用过 ETH 钱包,则能够观看上面的视频辅助设置。须要留神的是,这个视频也展现了在 Ropsten 网络上获取 ETH 测试代币,但 Chainlink 曾经不再反对了。如果你想依照视频操作,请应用 Kovan 测试网络。

https://www.youtube.com/watch?v=4ZgFijd02Jo

And last, be sure to have some testnet LINK and Kovan ETH in your ETH wallet. You can find some in the LINK faucet and ETH Kovan faucet.
最初,请确保你的 ETH 钱包中有一些测试网 LINK 代币和 Kovan 测试网 ETH 代币。你能够在 LINK 水龙头和 ETH Kovan 水龙头中获取一些。

Starting a Chainlink Project

开启一个 Chainlink 我的项目

To get started with Brownie, we can use what’s called a Brownie mix to give us boilerplate code. In this example, we will be deploying a simple Chainlink Price Feed as a way to learn about the Brownie framework. Let’s bake the chainlink-mix.
要开始应用 Brownie,咱们能够应用 Brownie mix 为咱们提供样板代码。在本文的示例中,咱们将部署一个简略的 Chainlink Price Feed,来理解 Brownie 框架。当初咱们就开始创作 chainlink-mix 我的项目吧。

brownie bake chainlink-mix
cd chainlink

This will place us into a new project with some default code already built for us. If we run ls we can see what the layout of the file looks like:
咱们会进入到一个蕴含一些默认代码的新我的项目。如果运行 ls 命令,咱们能够看到文件的布局如下:

  • build : This is where the project keeps track of your deployed smart contracts and compiled contracts
  • build:这是我的项目用来跟踪已部署的智能合约和已编译合约的文件夹
  • contracts : The source code of your contracts, typically written in Solidity or Vyper
  • contracts:合约的源代码,通常以 Solidity 或 Vyper 语言编写
  • interfaces : A layout of interfaces you’ll need to work with deployed contracts. Every interaction with a contract needs an ABI and an address. Interfaces are great ways to get a contract’s ABI
  • interfaces:和已部署合约交互所须要的接口文件夹。每次与合约的交互都须要一个 ABI 和合约地址。接口是获取合约的 ABI 的好办法
  • scripts : Scripts we create to automate processes of working with our contracts
  • scripts:咱们创立的用于主动执行合约流程的脚本
  • tests : Tests
  • tests:测试文件
  • brownie-config.yaml : This is where we have all the information for Brownie to understand how to work with our smart contract. What blockchain do we want to deploy to? Are there any special parameters we want to set? All these are set in the config file.
  • brownie-config.yaml:这个文件为 Brownie 提供了了解如何看待咱们的智能合约所须要的所有信息。咱们想部署到什么区块链网络?咱们要设置任何非凡参数吗?所有这些内容都在此配置文件中设置。

requirements.txt , README.md , LICENSE , and .gitignore can be ignored for now. You’ll find out what they are for as you practice.
requirements.txt , README.md , LICENSE , 以及 .gitignore 等文件当初能够疏忽。你将在练习过程中理解它们的用处。

Setting Up Environment Variables

设置环境变量

Even though we just installed Ganache to do local testing, we also want to be able to connect to the ETH mainnet and testnets so we can deploy them on real testnets. To do this, we need to set our WEB3_INFURA_PROJECT_ID. You can get an Infura ID for free from the Infura site. You can use other web3 providers or your own node as well, but you’ll have to do a little more configuration for that.
In your brownie-config.yaml file, you can set a network with a host key, and define the URL that you’d like to connect to if you’d rather not use MetaMask.
尽管咱们刚刚装置好了 Ganache 进行本地测试,咱们仍心愿可能连贯到以太坊主网和测试网,这样咱们就能够将合约部署在实在的测试网上。为此,咱们须要设置 WEB3_INFURA_PROJECT_ID 字段。你能够从 Infura 网站收费取得一个 Infura ID,也能够应用其余 web3 providers 或者本人的节点,然而你须要做更多配置。
brownie-config.yaml 文件中,你能够设定带有 host 字段的网络配置,如果不想应用 MetaMask,还能够定义要连贯的 URL。

Now that you have your web3 ID, we need to have our private key as an environment variable, so that we can use our account with our wallet. If you’re using MetaMask, look for export key. With MetaMask, you may have to add 0x to the start of your private key. It is recommended to use a different account than your main account when testing and exporting your key, just in case.
当初有了 web3 ID,咱们须要将私钥作为环境变量来应用,这样咱们能够在钱包中应用咱们的帐户。如果你应用的是 MetaMask,请找到 export key选项(以导出私钥)。应用 MetaMask 的话,你可能必须在私钥的结尾增加0x。为了以防万一,倡议在测试和导出密钥时应用与主帐户不同的帐户。

Now, to make them environment variables just run the following in your terminal:
当初,要使它们成为环境变量,只需在终端中运行以下命令:

export PRIVATE_KEY=0x96789…..
export WEB3_INFURA_PROJECT_ID=’dog cat mouse….’

If you run printenv and see your environment variables there, you’ll know you’ve done it right.
终端运行 printenv 命令,并在输入中看到下面配置的环境变量,就示意你做对了。

You can learn more about setting environment variables here.
能够在此处理解更多无关设置环境变量的信息。

Deploy Your Smart Contract

部署你的智能合约

Now that we have everything set up, we can even go ahead and deploy a smart contract to the Kovan testnet!
当初咱们曾经实现了所有设置,咱们将进一步把智能合约部署到 Kovan 测试网上!

In our scripts folder, we have a script called deploy_price_consumer_v3.py. This will deploy our smart contract that reads the price of Ethereum in USD.
scripts 文件夹中,咱们有一个名为 deploy_price_consumer_v3.py 的脚本。这将部署咱们的智能合约,该合约会读取以美元计价的以太坊的价格数据。

If you want to see an easier walkthrough of what this contract does and how to deploy it, feel free to check out the Chainlink tutorial on deploying a price feed contract.
如果你想看到一个更加易懂的论述该合约的性能以及如何部署它的教程,随时查看 Chainlink 的部署喂价合约的教程。

Just use brownie run to use the deploy script:
只需应用 brownie run 命令即可应用此部署脚本:

brownie run scripts/price_feed_scripts/deploy_price_consumer_v3.py --network kovan

You’ll see something like this:
你会看到以下输入内容:

Running 'scripts/price_feed_scripts/deploy_price_consumer_v3.py::main'...
Transaction sent: 0x23d1dfa3937e0cfbab58f8d5ecabe2bfffc28bbe2349527dabe9289e747bac56
Gas price: 20.0 gwei   Gas limit: 145600   Nonce: 1339
PriceFeed.constructor confirmed - Block: 22721813   Gas used: 132364 (90.91%)
PriceFeed deployed at: 0x6B2305935DbC77662811ff817cF3Aa54fc585816

If this worked properly, we can go to Kovan Etherscan and find the contract we deployed. The link above shows the contract deployed in this example.
如果脚本工作失常,咱们能够到 Kovan 区块浏览器上查看咱们部署的合约。下面的链接显示了此示例中部署的合约。

Read Your Smart Contract

读取你的智能合约

Now that we have deployed a smart contract, we can read the price of ETH from the contract we just deployed. We will be using another script that we have:
当初咱们曾经部署好了智能合约,咱们能够从刚刚部署的合约中读取以太坊的价格。咱们将应用另一个脚本:

brownie run scripts/price_feed_scripts/read_price_feed.py --network kovan

And we will get an output like:
咱们将失去如下输入:

Brownie v1.12.2 - Python development framework for Ethereum
ChainlinkProject is the active project.
Running 'scripts/price_feed_scripts/read_price_feed.py::main'...
Reading data from 0x5A….
122322000000

Where 122322000000 is the current price of ETH in USD! Solidity doesn’t understand decimals, and we know that Chainlink Price Feeds have 8 decimals, so the price is $1,223.22.
其中 122322000000 是 ETH 以后的美元价格!Solidity 无奈了解小数,而咱们晓得 Chainlink 喂价具备 8 位小数,因而价格为 $ 1,223.22。

And you’ve just deployed your first smart contract using Python with Brownie!
至此你就实现了应用 Python 和 Brownie 部署你的第一个智能合约!

Testing Your Smart Contract

测试你的智能合约

This is also a great example of how to test smart contracts. We use mocks objects to test even locally!
这也是一个很好的对于如何测试智能合约的例子。咱们甚至能够应用模仿对象在本地进行测试!

Simply run:
只需运行:

brownie test

And your tests will run on a local Ganache instance!
你的测试将在本地 Ganache 实例上运行!

You can also test on testnets with something like:
你还能够应用以下内容在测试网上进行测试:

brownie test --network kovan

The tests have some functionality that know if you’re working on a testnet or not. If you are working locally, it deploys dummy or“mocks”of the oracle code, so that we can test from them.
这些测试具备一些能够通晓你是否正在应用测试网的性能。如果你在本地工作,它将部署预言机代码的虚构对象或“模仿对象”,因而咱们能够通过它们进行测试。

Going Further

更进一步

Now that you know how to deploy smart contracts with Python, you can begin building on top of this framework to do more interesting things. Python has powerful packages like Numpy, Scikit, Pandas, and TensorFlow to do quantitative work, machine learning, and more. Being able to finally combine these technologies together is a recipe for success in the new age of fintech: decentralized finance.
当初你晓得了如何应用 Python 来部署智能合约,就能够开始基于此框架进行构建以做更多乏味的事件。Python 具备诸如 Numpy,Scikit,Pandas 和 TensorFlow 等弱小的软件包,能够用于定量工作,机器学习等等。最终将这些技术联合在一起是在金融科技新时代胜利的秘诀:去中心化金融。

Chainlink is a flexible framework for bringing external financial data and systems on-chain and integrates seamlessly with data-focused packages like Numpy and Pandas. If you’re a developer and want to quickly get your application connected to Chainlink, visit the developer documentation and join the technical discussion in Discord. If you build something great with Python, Chainlink, and Brownie, be sure to tag us with @chainlink so we can check out all the cool work you do!
Chainlink 是一个灵便的框架,用于将内部金融数据和零碎引入到链上,并无缝集成这些与以数据为核心的软件包,如 Numpy 和 Pandas。如果你是开发者,并且心愿疾速将你的利用连贯到 Chainlink,请拜访开发者文档并退出 Discord 中的技术探讨。如果你应用 Python,Chainlink 和 Brownie 构建了很棒的货色,请确保应用 @chainlink 来标记咱们,便于咱们知悉所做的所有的杰出的工作!

Website | Twitter | Reddit | YouTube | Telegram | Events | GitHub | Price Feeds | DeFi

正文完
 0