使用Python开发DeFi项目

  • Chainlink
  • 更新于 2021-02-22 10:47
  • 阅读 3577

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

原文链接: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和机器学习支持
  • 配套的金融科技软件工具包
  • 全面的分析工具
  • 生产环境中的可靠性

image.png 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.pyBrownie之类的库和框架,我们才能够有机会看到这些项目的诞生。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年启用的一些功能快速概览。

image.png

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

本文首发于:https://blog.chain.link/develop-python-defi-project/

点赞 1
收藏 4
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
Chainlink
Chainlink
顶尖的智能合约去中心化预言机网络解决方案 https://chain.link/