Skip to content

Commit

Permalink
Merge branch 'main' of github.com:Dapp-Learning-DAO/Dapp-Learning
Browse files Browse the repository at this point in the history
  • Loading branch information
hotaplayer committed May 5, 2023
2 parents c3c98c4 + 60beec7 commit 5d05940
Show file tree
Hide file tree
Showing 20 changed files with 1,528 additions and 70 deletions.
4 changes: 2 additions & 2 deletions README-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ DAPP架构请参考文章--[从架构维度看Web2.0与Web3.0应用之别](https
3. [Curve](defi/Curve/README.md)
4. [Compound](defi/Compound/readme.md)
5. [Aave](https://docs.aave.com/portal/)
6. [Liquity](defi/Liquity/readme.md)
6. [Liquity](defi/Liquity/)
7. [Euler](defi/Euler/readme.md)
8. [SNX](https://github.com/Synthetixio)
9. [YFI](https://yearn.finance/)
Expand All @@ -233,7 +233,7 @@ DAPP架构请参考文章--[从架构维度看Web2.0与Web3.0应用之别](https
12. [OPYN](https://v2.opyn.co/)
13. [Alchemix](https://github.com/alchemix-finance/alchemix-protocol)
14. [AMPL](https://roninchow.gitbook.io/ampleforth-cn/technology) [👉 认领这个 Task](https://github.com/rebase-network/Dapp-Learning/issues/new)
15. [RAI](https://www.youtube.com/watch?v=ADK91Zw4sJA&list=PL-GxJch-YeZerVVV8dY8qU2VkJfbnSfdN&index=3)
15. [RAI](defi/RAI/)
16. [DYDX](https://dydx.exchange/)[👉 认领这个 Task](https://github.com/rebase-network/Dapp-Learning/issues/new)
17. [INDEX](https://mp.weixin.qq.com/s/PXOY3G6AIbhzRUptjYoWIw)[👉 认领这个 Task](https://github.com/rebase-network/Dapp-Learning/issues/new)
18. [DODO](https://dodoex.github.io/docs/zh/docs/tradeApi) [👉 认领这个 Task](https://github.com/rebase-network/Dapp-Learning/issues/new)
Expand Down
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ You can refer to our study group's learning roadmap, which is better with the vi
03. [Curve](defi/Curve/README.md)
04. [Compound](defi/Compound/readme.md)
05. [Aave](https://docs.aave.com/portal/)
06. [Liquity](defi/Liquity/readme.md)
06. [Liquity](defi/Liquity/)
07. [Euler](defi/Euler/readme.md)
08. [SNX](https://github.com/Synthetixio) [👉 Pick up this Task](https://github.com/Dapp-Learning-DAO/Dapp-Learning/issues/new)
09. [YFI](https://yearn.finance/)
Expand All @@ -227,7 +227,7 @@ You can refer to our study group's learning roadmap, which is better with the vi
12. [OPYN](https://v2.opyn.co/)
13. [Alchemix](https://github.com/alchemix-finance/alchemix-protocol)
14. [AMPL](https://roninchow.gitbook.io/ampleforth-cn/technology) [👉 Pick up this Task](https://github.com/Dapp-Learning-DAO/Dapp-Learning/issues/new)
15. [RAI](https://www.youtube.com/watch?v=ADK91Zw4sJA& list=PL-GxJch-YeZerVVV8dY8qU2VkJfbnSfdN&index=3)
15. [RAI](defi/RAI/)
16. [DYDX](https://dydx.exchange/)[👉 Pick up this Task](https://github.com/Dapp-Learning-DAO/Dapp-Learning/issues/new)
17. [INDEX](https://mp.weixin.qq.com/s/PXOY3G6AIbhzRUptjYoWIw)[👉 Pick up this Task](https://github.com/Dapp-Learning-DAO/Dapp-Learning/issues/new)
18. [DODO Trading API](https://dodoex.github.io/docs/zh/docs/tradeApi) [👉 Pick up this Task](https://github.com/Dapp-Learning-DAO/Dapp-Learning/issues/new)
Expand All @@ -249,6 +249,7 @@ You can refer to our study group's learning roadmap, which is better with the vi
- 04. [Rarible](https://docs.rarible.org/overview/union/)
- 05. [Zora](https://docs.zora.co/)
- 06. [Alchemy](https://www.alchemy.com/nft-api)
- 07. [Infura](https://www.infura.io/platform/nft-api)

## DAO advanced tasks

Expand Down
27 changes: 21 additions & 6 deletions basic/02-web3js-transaction/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ const contractOfIncrementer = require('./compile');
require('dotenv').config();
const privatekey = process.env.PRIVATE_KEY;

function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}

/*
-- Define Provider --
*/
Expand Down Expand Up @@ -155,21 +159,29 @@ const Trans = async () => {
// goerli don't support http protocol to event listen, need to use websocket
// more details , please refer to https://medium.com/blockcentric/listening-for-smart-contract-events-on-public-blockchains-fdb5a8ac8b9a
const web3Socket = new Web3(
new Web3.providers.WebsocketProvider(
'wss://goerli.infura.io/ws/v3/' + process.env.INFURA_ID
)
);
incrementer = new web3Socket.eth.Contract(abi, createReceipt.contractAddress);

// listen to Increment event only once
incrementer.once('Increment', (error, event) => {
console.log('I am a onetime event listner, I am going to die now');
});

// listen to Increment event continuously
incrementer.events.Increment(() => {
console.log('I am a longlive event listener, I get a event now');
});
web3Socket.eth.subscribe('logs',{
address: createReceipt.contractAddress,
topics: []
},(error,result) => {
if(error){
console.error(error)
}
}
).on("data", (event) => {
console.log("New event: ", event);
})
.on("error", (error) => {
console.error("Error: ", error);
});

for (let step = 0; step < 3; step++) {
incrementTransaction = await web3.eth.accounts.signTransaction(
Expand All @@ -183,6 +195,9 @@ const Trans = async () => {

await web3.eth.sendSignedTransaction(incrementTransaction.rawTransaction);

console.log("Waiting for events")
await sleep(3000);

if (step == 2) {
// clear all the listeners
web3Socket.eth.clearSubscriptions();
Expand Down
30 changes: 29 additions & 1 deletion basic/14-chainlink-price-feed/README-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

区块链是非常安全可靠的价值交换网络,但却无法安全防篡改地获取链下数据或将数据发送至链下系统。使用 Chainlink 预言机喂价, 通过预言机网络在链上直接获取实时金融市场价格数据

首先,我们可以在[这里](https://docs.chain.link/data-feeds/price-feeds/addresses)找到各个网络的喂价合约地址。然后,以ETH_USD为例,表示一个ETH能兑换多少USD,注意不要理解反了,不是ETH per USD的意思。接下来无论链上还是链下,我们都需要通过读取喂价器合约的方式获取价格信息。

## 测试流程

### 配置私钥
Expand All @@ -28,7 +30,7 @@ npx hardhat run scripts/01-PriceConsumerV3Deploy.js --network goerli
```

### 链下调用喂价机

#### 获取最新数据
```js
// ./UsingDataFeedsByEthers.js
require('dotenv').config();
Expand Down Expand Up @@ -74,6 +76,29 @@ Latest Round Data [
- 完整示例看这里 [:point_right: UsingDataFeedsByEthers.js](./UsingDataFeedsByEthers.js)


#### 链下获取历史数据

Chainlink链上Api提供两个接口:
- latestRoundData:获取最新价格数据
- getRoundData:获取历史价格数据

首先,了解什么round。chainlink会将链下聚合器的数据持续更新到链上,每次更新,就会更新roundId。更新的间隔是不定时的,快则几分钟更新一次,慢则几个小时,甚至几天更新一次价格。

其次,roundId的构成,由两部分:phaseId和aggregatorRoundId. roundId生成方式如下:
```
roundId = (phaseId << 64) | aggregatorRoundId
```
其中:
- phaseId表示历史上聚合器的版本,从1开始,每次聚合器更新,就会让phase+1.
- aggregatorRoundId表示对应聚合器版本下的轮数,每次更新一次喂价器数据,就会让这个编号加1.

所以,遍历历史数据的思路如下:
- 先根据latestRoundData,读取最新的phaseId.
- phaseId从1开始,然后遍历aggregatorRoundId,也从1开始,如果遇到revert错误,就将phaseId+1.

可以参考例子:[ethers获取历史数据](./scripts/04-HistoryData.js)



### Chainlink VRF

Expand Down Expand Up @@ -154,3 +179,6 @@ SubscriptionId=ddddd
- https://learnblockchain.cn/article/2558
- https://learnblockchain.cn/article/1056
- https://mp.weixin.qq.com/s/h0uTWY7vzd-CMdr1pE7_YQ
- https://docs.chain.link/data-feeds/examples
- https://docs.chain.link/data-feeds/historical-data
- https://docs.chain.link/data-feeds/price-feeds/addresses
8 changes: 4 additions & 4 deletions basic/14-chainlink-price-feed/hardhat.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,10 @@ module.exports = {
// url: mainnetRpcUrl
// }
},
goerli: {
url: 'https://goerli.infura.io/v3/' + process.env.INFURA_ID, //<---- YOUR INFURA ID! (or it won't work)
accounts: [mnemonic()],
},
// goerli: {
// url: 'https://goerli.infura.io/v3/' + process.env.INFURA_ID, //<---- YOUR INFURA ID! (or it won't work)
// accounts: [mnemonic()],
// },
},
namedAccounts: {
deployer: {
Expand Down
3 changes: 2 additions & 1 deletion basic/14-chainlink-price-feed/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"dependencies": {
"@chainlink/contracts": "^0.4.0",
"@nomiclabs/hardhat-etherscan": "^3.0.1",
"dotenv": "^10.0.0"
"dotenv": "^10.0.0",
"moment": "^2.29.4"
}
}
129 changes: 129 additions & 0 deletions basic/14-chainlink-price-feed/scripts/04-HistoryData.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
// We require the Hardhat Runtime Environment explicitly here. This is optional
// but useful for running the script in a standalone fashion through `node <script>`.
//
// You can also run a script with `npx hardhat run <script>`. If you do that, Hardhat
// will compile your contracts, add the Hardhat Runtime Environment's members to the
// global scope, and execute the script.

const moment = require('moment');

const aggregatorV3InterfaceABI = [
{
inputs: [],
name: "decimals",
outputs: [{ internalType: "uint8", name: "", type: "uint8" }],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "description",
outputs: [{ internalType: "string", name: "", type: "string" }],
stateMutability: "view",
type: "function",
},
{
inputs: [{ internalType: "uint80", name: "_roundId", type: "uint80" }],
name: "getRoundData",
outputs: [
{ internalType: "uint80", name: "roundId", type: "uint80" },
{ internalType: "int256", name: "answer", type: "int256" },
{ internalType: "uint256", name: "startedAt", type: "uint256" },
{ internalType: "uint256", name: "updatedAt", type: "uint256" },
{ internalType: "uint80", name: "answeredInRound", type: "uint80" },
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "latestRoundData",
outputs: [
{ internalType: "uint80", name: "roundId", type: "uint80" },
{ internalType: "int256", name: "answer", type: "int256" },
{ internalType: "uint256", name: "startedAt", type: "uint256" },
{ internalType: "uint256", name: "updatedAt", type: "uint256" },
{ internalType: "uint80", name: "answeredInRound", type: "uint80" },
],
stateMutability: "view",
type: "function",
},
{
inputs: [],
name: "version",
outputs: [{ internalType: "uint256", name: "", type: "uint256" }],
stateMutability: "view",
type: "function",
},
]

async function main() {

const { ethers, BigNumber } = require("ethers") // for nodejs only

const provider = new ethers.providers.JsonRpcProvider("https://rpc.ankr.com/eth_sepolia")
//eth_usd: one eth worths how many usd
const addr = "0x694AA1769357215DE4FAC081bf1f309aDC325306"
const priceFeed = new ethers.Contract(addr, aggregatorV3InterfaceABI, provider)

//1. 获取最新的round
const latestRound = await priceFeed.latestRoundData();

//see https://docs.chain.link/data-feeds/historical-data
const mask = BigNumber.from('0xFFFFFFFFFFFFFFFF');//right most 64bits with 1

const latestPhaseId = latestRound.roundId.shr(64);
const latestAggregatorRoundId = latestRound.roundId.and(mask);

console.log('latesPhaseId '+latestPhaseId.toString())
console.log('latestAggregatorRoundId '+latestAggregatorRoundId.toString())

for (var phase = BigNumber.from(1);phase.lte(latestPhaseId);phase=phase.add(1)){
for (var agRound = BigNumber.from(1); agRound.lte(mask) ; agRound=agRound.add(1)){

const [inPhase, roundData] = await downloadRoundData(priceFeed, phase, agRound);
if (!inPhase){
console.log('should start a new phase')
break;
}
processRoundData(phase, agRound, roundData)
await new Promise(r => setTimeout(r, 1000));

}
}
}

async function downloadRoundData(priceFeed, phase, agRound){
const roundId = phase.shl(64).or(agRound);
const maxRetries = 10
var tries = 1;
while (tries <= maxRetries){
try{
const roundData = await priceFeed.getRoundData(roundId);
return [true, roundData] //still same phase, rounddata
}
catch(e){
if(e.message.includes('Transaction reverted')){
return [false, undefined]//out of the current phase, should start new one
} else{
console.log(e.message)
tries++;//just retry, may be network connection issues
await new Promise(r => setTimeout(r, 1000));
}
}
}
throw Error('Totally failed. dont know why');


}
function processRoundData(phase, agRound, roundData){
//Todo:insert it into database
//目前只是打印
console.log(`phase:${phase}, agRound:${agRound}`);
console.log(`answer:${ethers.utils.formatUnits(roundData.answer, 8)}`);
console.log(`updatedAt:${moment(roundData.updatedAt*1000).format('YYYY-MM-DD HH:mm:ss')}`);

}


main()
12 changes: 6 additions & 6 deletions basic/38-ether-rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions basic/43-EVM/etk/GasOptimizedForSudo.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ runtimeStart:
swap1 #0 returndatasize success 0 returndatasize
dup1 #0 0 returndatasize success 0 returndatasize
returndatacopy #success 0 returndatasize
push1 labelreturn #labelreturn success 0 returndatasize
push1 labelreturn-runtimeStart #labelreturn success 0 returndatasize
jumpi #0 returndatasize
revert #
labelreturn:
Expand Down Expand Up @@ -147,4 +147,4 @@ function cloneETHPair(
instance := create(0, ptr, 0x7c)
}
}
```
```
Loading

0 comments on commit 5d05940

Please sign in to comment.