Skip to content

Commit

Permalink
Merge pull request #1017 from yanyanho/main
Browse files Browse the repository at this point in the history
add 1inch script
  • Loading branch information
yanyanho authored Feb 6, 2024
2 parents 4b7c272 + 5c2c58f commit cf77de8
Show file tree
Hide file tree
Showing 19 changed files with 507 additions and 67 deletions.
18 changes: 14 additions & 4 deletions basic/13-decentralized-exchange/EtherDelta/README-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ EtherDelta 实现了简单的 token 合约,类似 ERC20 标准合约,用于

#### 交易流程

1. 卖家挂单 `order()`,以挂单信息转换为 hash,作为键,存入 `orders` 合约变量
2. 买家吃单 `trade()`,传入指定的挂单 hash
1. 卖家(maker)挂单 `order()`,以挂单信息转换为 hash,作为键,存入 `orders` 合约变量
2. 买家(taker)吃单 `trade()`,传入指定的挂单 hash, 并且需要拿到maker的订单签名信息。且支持部分成交。

#### constructor

Expand All @@ -82,11 +82,21 @@ mapping(address => mapping(bytes32 => bool)) public orders; // 挂单列表 (tru
mapping(address => mapping(bytes32 => uint256)) public orderFills; // 每一笔挂单完成的数量 (amount of order that has been filled)
```

## todo list
#### 手续费逻辑

手续费都是收取maker的 tokenGet(即要买入的token)
```
//0 = regular user (pays take fee and make fee)
//1 = market maker silver (pays take fee, no make fee, gets rebate)
//2 = market maker gold (pays take fee, no make fee, gets entire counterparty's take fee as rebate)
```
普通用户,需要付take fee和maker fee
白银用户,付taker费用,并且有手续费返现
黄金用户,付taker费用,但是可以获取对手方taker费用返现

### 测试流程补全

目前只实现了核心功能的测试,还有部分测试流程未升级,老测试文件参见 `./backup/test.old.js`
目前只实现了核心功能的测试,还有部分测试流程未升级,老测试文件参见 `../backup/etherdelta/test.old.js`
**老版测试文件部分测试有误,建议以当前测试文件为准**

## 参考链接
Expand Down
2 changes: 1 addition & 1 deletion basic/13-decentralized-exchange/EtherDelta/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ mapping(address => mapping(bytes32 => uint256)) public orderFills; // amount of

### Test Process Description

At present, only the core functions have been tested, and part of the test process has not been upgraded. See `./backup/test.old.js` for the old test file
At present, only the core functions have been tested, and part of the test process has not been upgraded. See `../backup/etherdelta/test.old.js` for the old test file
**Some tests in the original test file are incorrect. You are advised to use the current test file**

## Refer to the link
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -232,12 +232,8 @@ contract EtherDelta {
address give
);
event Deposit(address token, address user, uint256 amount, uint256 balance);
event Withdraw(
address token,
address user,
uint256 amount,
uint256 balance
);

event Withdraw(address token, address user, uint256 amount, uint256 balance);

modifier adminOnly {
require(msg.sender == admin, "No permission");
Expand Down Expand Up @@ -449,25 +445,33 @@ contract EtherDelta {
uint256 feeMakeXfer = SafeMath.mul(amount, feeMake) / (1 ether);
uint256 feeTakeXfer = SafeMath.mul(amount, feeTake) / (1 ether);
uint256 feeRebateXfer = 0;

//0 = regular user (pays take fee and make fee)
//1 = market maker silver (pays take fee, no make fee, gets rebate)
//2 = market maker gold (pays take fee, no make fee, gets entire counterparty's take fee as rebate)
if (accountLevelsAddr != address(0)) {
uint256 accountLevel = AccountLevels(accountLevelsAddr)
.accountLevel(user);
if (accountLevel == 1)
feeRebateXfer = SafeMath.mul(amount, feeRebate) / (1 ether);
if (accountLevel == 2) feeRebateXfer = feeTakeXfer;
}
// 对taker收费
tokens[tokenGet][msg.sender] = SafeMath.sub(
tokens[tokenGet][msg.sender],
SafeMath.add(amount, feeTakeXfer)
);
//对maker收费
tokens[tokenGet][user] = SafeMath.add(
tokens[tokenGet][user],
SafeMath.sub(SafeMath.add(amount, feeRebateXfer), feeMakeXfer)
);
//feeAccount 账户收费
tokens[tokenGet][feeAccount] = SafeMath.add(
tokens[tokenGet][feeAccount],
SafeMath.sub(SafeMath.add(feeMakeXfer, feeTakeXfer), feeRebateXfer)
);
// 对maker买入token收费,
tokens[tokenGive][user] = SafeMath.sub(
tokens[tokenGive][user],
SafeMath.mul(amountGive, amount) / amountGet
Expand Down
10 changes: 7 additions & 3 deletions basic/13-decentralized-exchange/README-CN.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
中文 / [English](https://github.com/Dapp-Learning-DAO/Dapp-Learning/blob/main/basic/13-decentralized-exchange/README.md)
## 简介
本样例主要介绍 etherdelta 合约逻辑, 演示对 etherdelta 合约的基本使用.

有去中心化交易所, 有 etherdelta 订单薄模式和uniswap的AMM做市商模式。
待集成 0x & bancor & kyber
去中心化交易所, 有 etherdelta 订单薄模式和uniswap的AMM做市商模式。
其他类型有 0x & bancor & 1inch
了解etherdelta交易所是了解其他订单薄模式交易所的基础。而了解uniswap v1是了解AMM的基础。

### EtherDelta
本样例主要介绍 etherdelta 合约逻辑, 演示对 etherdelta 合约的基本使用.

[详情参见 EtherDelta解析和测试 :point_right:](./EtherDelta/README.md)

Expand All @@ -15,6 +16,9 @@

[详情参见 uniswap-v1-like :point_right:](./uniswap-v1-like/README.md)


### backup
为了方便演示以及兼容hardhat我们做了微调。 backup 目录是原版代码。
## 参考链接

https://github.com/etherdelta/smart_contract/blob/master/etherdelta.sol
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,20 +120,7 @@ contract Exchange is ERC20 {
return getAmount(_tokenSold, tokenReserve, address(this).balance);
}

// 使用eth购买token
// 拆分为 ethToToken 和 ethToTokenSwap
// function ethToTokenSwap(uint256 _minTokens) public payable {
// uint256 tokenReserve = getReserve();
// uint256 tokensBought = getAmount(
// msg.value,
// address(this).balance - msg.value,
// tokenReserve
// );

// require(tokensBought >= _minTokens, "insufficient output amount");

// IERC20(tokenAddress).transfer(msg.sender, tokensBought);
// }


function ethToToken(uint256 _minTokens, address recipient) private {
uint256 tokenReserve = getReserve();
Expand Down
3 changes: 2 additions & 1 deletion defi/0x-protocal/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ https://docs.0x.org/0x-api-swap/guides/accessing-rfq-liquidity-on-0x-api


### How to Build NFT Exchange in Your DApp
//todo
https://0x.org/docs/0x-swap-api/guides/how-to-build-a-token-swap-dapp-with-0x-api

### 限价单
有两种类型的单子: limit order & RFQ order
Expand All @@ -60,4 +60,5 @@ https://docs.0x.org/0x-api-orderbook/introduction
- github: <https://github.com/0xProject/0x-protocol-specification/blob/master/v2/v2-specification.md#exchange>
- 0x文档: <https://0x.org/docs/guides/use-0x-api-liquidity-in-your-smart-contracts>
- video: https://www.web3.university/tracks/road-to-web3/build-a-blockchain-betting-game
- How to Get 0x and Matcha Data: https://0x.org/docs/developer-resources/how-to-get-0x-and-matcha-data

3 changes: 2 additions & 1 deletion defi/0x-protocal/demo/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ npx hardhat run scripts/deploy.js
```
## direct-swap
https://github.com/0xProject/0x-api-starter-guide-code/blob/master/src/direct-swap.js#L105-L113
//todo
https://0x.org/docs/0x-swap-api/guides/swap-tokens-with-0x-swap-api
## contract-swap

//todo
## limit order swap
https://github.com/0xProject/0x-starter-project/tree/master/src


//todo

## nft marketplace
55 changes: 53 additions & 2 deletions defi/0x-protocal/demo/hardhat.config.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,57 @@
require("@nomicfoundation/hardhat-toolbox");
require('dotenv').config();

/** @type import('hardhat/config').HardhatUserConfig */
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task('accounts', 'Prints the list of accounts', async () => {
const accounts = await ethers.getSigners();

for (const account of accounts) {
console.log(account.address);
}
});

function mnemonic() {
return process.env.PRIVATE_KEY;
}

/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.17",
solidity: '0.8.17',
networks: {
localhost: {
url: 'http://localhost:8545',
//gasPrice: 125000000000, // you can adjust gasPrice locally to see how much it will cost on production
/*
notice no mnemonic here? it will just use account 0 of the hardhat node to deploy
(you can put in a mnemonic here to set the deployer locally)
*/
},
goerli: {
url: 'https://goerli.infura.io/v3/' + process.env.INFURA_ID, //<---- CONFIG YOUR INFURA ID IN .ENV! (or it won't work)
accounts: [mnemonic()],
},
mainnet: {
url: 'https://eth-mainnet.g.alchemy.com/v2/' + process.env.ALCHEMY, //<---- CONFIG YOUR INFURA ID IN .ENV! (or it won't work)
accounts: [mnemonic()],
},
ropsten: {
url: 'https://ropsten.infura.io/v3/' + process.env.INFURA_ID, //<---- CONFIG YOUR INFURA ID IN .ENV! (or it won't work)
accounts: [mnemonic()],
},
arbitest: {
url: 'https://arbitrum-rinkeby.infura.io/v3/' + process.env.INFURA_ID, //<---- CONFIG YOUR INFURA ID IN .ENV! (or it won't work)
accounts: [mnemonic()],
},
matic: {
url: 'https://polygon-mainnet.infura.io/v3/' + process.env.PROJECT_ID, //<---- CONFIG YOUR INFURA ID IN .ENV! (or it won't work)
accounts: [mnemonic()]
},
op: {
url: 'https://opt-mainnet.g.alchemy.com/v2/' + process.env.ALCHEMY,
accounts: [mnemonic()],
},
},
};
13 changes: 12 additions & 1 deletion defi/0x-protocal/demo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,18 @@
"name": "hardhat-project",
"devDependencies": {
"@nomicfoundation/hardhat-toolbox": "^2.0.0",
"@types/node": "^20.11.16",
"dotenv": "^16.0.3",
"hardhat": "^2.12.4",
"node-fetch": "^2.6.1"
"node-fetch": "^2.6.1",
"qs": "6.11.2",
"typescript": "^5.3.3",
"yesno": "0.4.0"
},
"dependencies": {
"@1inch/limit-order-protocol-utils": "^4.0.13-alpha",
"@0x/protocol-utils":"11.24.2",
"@0x/contract-addresses":"8.13.0",
"web3": "4.2.2"
}
}
65 changes: 65 additions & 0 deletions defi/0x-protocal/demo/scripts/0xdirect-swap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
const hre = require("hardhat");
const fetch = require('node-fetch');
const qs = require('qs');
require('dotenv').config();

//https://github.com/0xProject/0x-api-starter-guide-code/blob/master/src/direct-swap.js#L105-L113
async function main() {

//const API_QUOTE_URL = 'https://api.0x.org/swap/v1/quote';
const API_QUOTE_URL = 'https://optimism.api.0x.org/swap/v1/quote';
console.info(`Fetching swap quote from 0x-API to sell WETH for DAI...`);

const exchangeOP="0xdef1abe32c034e558cdd535791643c58a13acc10";
const apiKey = process.env.ZEROXAPIKEY;

const usdcTokenAddress = '0x7F5c764cBc14f9669B88837ca1490cCa17c31607'; // Replace with actual USDC token address
const opTokenAddress = '0x4200000000000000000000000000000000000042'; // Replace with actual OP token address
const wethTokenAddress = '0x4200000000000000000000000000000000000006'; // Replace with actual OP token address

const params = {
// Not all token symbols are supported. The address of the token can be used instead.
sellToken:usdcTokenAddress ,
buyToken: opTokenAddress,
// Note that the DAI token uses 18 decimal places, so `sellAmount` is `100 * 10^18`.
sellAmount: '5000000',
}
const quoteUrl = `${API_QUOTE_URL}?${qs}`;

// const headers = { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` } }

// const response = await fetch(
// `https://api.0x.org/swap/v1/price?${qs.stringify(params)}`, {headers: {'0x-api-key': apiKey}}
// );

const response = await fetch(
`https://optimism.api.0x.org/swap/v1/quote?${qs.stringify(params)}`, {headers: {'0x-api-key': apiKey}}
);

const quote = await response.json();
console.log(quote)

console.info(`Received a quote ${quote}`);
console.info(`Received a quote with price ${quote.price}`);


const [signer] = await ethers.getSigners();

console.log("send transaction ----")
//
// await signer.sendTransaction({
// gasLimit: quote.gas,
// gasPrice: quote.gasPrice,
// to: quote.to,
// data: quote.data,
// value: quote.value,
// chainId: quote.chainId,
// });
}

// We recommend this pattern to be able to use async/await everywhere
// and properly handle errors.
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Loading

0 comments on commit cf77de8

Please sign in to comment.