原文链接: 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是地球上最常用的语言

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

Source: 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

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 Network stats 2020

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 --version

Or, if with 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编写的一键式区块链,它可让你很容易启动一个本地区块链。但你必须通过 npm

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

npm -v

Then, you can install Ganache via the command line.

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  [...] [options ]
  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
  --help -h          Display this message
  --version          Show version and exit
Type 'brownie  --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.


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


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 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
  • 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
  • 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

, and .gitignore
can be ignored for now. You’ll find out what they are for as you practice. requirements.txt
, 以及 .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
文件中,你可以设定带有 host

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!

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.
文件夹中,我们有一个名为 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.

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….

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!

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!
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.

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

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