创建自己的以太坊生态(2)

上文搭建了以太坊网络,并发行了ERC20代币和uniswap交易所

本文介绍一种使用truffle发布uni的方法

把上文中的几个合约源码拷贝到项目中,直接上代码

2_deploy_tokens.js

const cht = artifacts.require("CHTToken");
const bnb = artifacts.require("BNB");
const weth9 = artifacts.require("WETH9");
const UniswapV2Factory = artifacts.require("UniswapV2Factory");
const router = artifacts.require("UniswapV2Router02");

const ethers = require('ethers');
let contract = require("truffle-contract");

const providerURL = 'http://172.16.30.174:8545';//服务地址
const PRIVATE_KEY1 = '私钥';//0x477257735cCEF9C7d42856649c7149865D04eDeb
const PRIVATE_KEY2 = '私钥'; //0x18A1cf95EDBAf22f55E4789782eB76A1E4C192Af


module.exports = async function (deployer) {
    deployer.deploy(cht);
    deployer.deploy(bnb, "200000000000000000000000000", "BNB", "18", "BNB");
    await deployer.deploy(weth9);


    //发布UniswapV2Factory
    await deployer.deploy(UniswapV2Factory, "0x477257735cCEF9C7d42856649c7149865D04eDeb")
    let data = require("../build/contracts/UniswapV2Factory.json");
    let uniswapV2FactoryAbi = contract(data).abi;
    // Define Provider
    let provider = new ethers.providers.JsonRpcProvider(providerURL);
    let wallet1 = new ethers.Wallet(PRIVATE_KEY1, provider);
    let uniswapV2FactoryContract = new ethers.Contract(UniswapV2Factory.address, uniswapV2FactoryAbi, provider);
    const contractWithSigner = uniswapV2FactoryContract.connect(wallet1);
    const res = await contractWithSigner.INIT_CODE_PAIR_HASH.call();
    console.log("INIT_CODE_PAIR_HASH----------", res);//0x907598391dc1af8f3b14e938fe6ccd99e5d732db43ab917de7973d1a2e423beb
    // const feeToSetter = await contractWithSigner.feeToSetter.call();
    // console.log("---------------",feeToSetter);

    // 发布router
    await deployer.deploy(router, UniswapV2Factory.address, weth9.address);


    console.log("let chtAddress=\"", cht.address,"\"");
    console.log("let bnbAddress=\"", bnb.address,"\"");
    console.log("let weth9Address=\"", weth9.address,"\"");
    console.log("let uniswapV2FactoryAddress=\"", UniswapV2Factory.address,"\"");
    console.log("let routerAddress=\"", router.address,"\"");
};

/*
cht.address 0x2c2Ac80d599B03C5Eeb3888D637b5647f3aDc31F
bnb.address 0x1A98B16A0469BCC164925b213624145187ca1EB7
weth9.address 0xA31269A211d487622A2DbCa8362B410a29735354
UniswapV2Factory.address 0x0B5EC37A0265702f166524cf323551c095f38649
routerAddress 0x1d07cBfD8a5127b4aF4fD1073B47900f3DD85F07
 */

invoke.js

const ethers = require('ethers');
let contract = require("truffle-contract");
let BN = require("bn.js")
const data = require("../build/contracts/CHTToken.json");
// let web = require("web3")

let chtAddress="0x92a51f7fA617EB68ad05e34f4d05D386Bdb81610"
let bnbAddress="0x856d986F88a0893741AEEC88E1f30D16dB3326e1"
let weth9Address="0xBF0F208399B0Ebc0AF979fA5401618459a17c106"
let uniswapV2FactoryAddress="0xB70781044867C3fF534b7B28DA0F1522aC566Cc1"
let routerAddress="0xD5B3A887C6270944397f296CA5C2CFF161777C43"



const providerURL = 'http://172.16.30.174:8545';
const address1 = "0x477257735cCEF9C7d42856649c7149865D04eDeb";
const PRIVATE_KEY1 = '私钥';//0x477257735cCEF9C7d42856649c7149865D04eDeb
const PRIVATE_KEY2 = '私钥'; //0x18A1cf95EDBAf22f55E4789782eB76A1E4C192Af

const p18 = new BN(10).pow(new BN(18));
let provider = new ethers.providers.JsonRpcProvider(providerURL);
let wallet1 = new ethers.Wallet(PRIVATE_KEY1, provider);

//调用cht的approve方法
let chtApprove = async (amount) => {
    let data = require("../build/contracts/CHTToken.json");
    let chtAbi = contract(data).abi;
    // Define Provider

    let chtContract = new ethers.Contract(chtAddress, chtAbi, provider);
    const contractWithSigner = chtContract.connect(wallet1);
    const tx = await contractWithSigner.approve(
        routerAddress,
        new BN(amount).mul(p18).toString(), {
            gasLimit: 210000,
            gasPrice: 20
        }
    )
    console.log(`Transaction hash: ${tx.hash}`);
    const receipt = await tx.wait();
    console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}

//调用bnb的approve方法
let bnbApprove = async (amount) => {
    let data = require("../build/contracts/BNB.json");
    let bnbAbi = contract(data).abi;
    // Define Provider
    // let provider = new ethers.providers.JsonRpcProvider(providerURL);
    // let wallet1 = new ethers.Wallet(PRIVATE_KEY1, provider);
    let chtContract = new ethers.Contract(bnbAddress, bnbAbi, provider);
    const contractWithSigner = chtContract.connect(wallet1);
    const tx = await contractWithSigner.approve(
        routerAddress,
        new BN(amount).mul(p18).toString(), {
            gasLimit: 210000,
            gasPrice: 20
        }
    )
    console.log(`Transaction hash: ${tx.hash}`);
    const receipt = await tx.wait();
    console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}

//添加流动性
let addLiquidity = async () => {
    let tokenA = chtAddress;
    let tokenB = bnbAddress;
    let amountADesired = new BN(1000).mul(p18).toString();
    let amountBDesired = new BN(1000).mul(p18).toString();
    let amountAMin = new BN(100).mul(p18).toString();
    let amountBMin = new BN(100).mul(p18).toString();
    let to = address1;
    let deadline = 2629448614;

    let data = require("../build/contracts/UniswapV2Router02.json");
    let routerAbi = contract(data).abi;
    // Define Provider
    // let provider = new ethers.providers.JsonRpcProvider(providerURL);
    // let wallet1 = new ethers.Wallet(PRIVATE_KEY1, provider);
    let routerContract = new ethers.Contract(routerAddress, routerAbi, provider);
    const contractWithSigner = routerContract.connect(wallet1);
    const tx = await contractWithSigner.addLiquidity(
        tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin, to, deadline, {
            gasLimit: 8000000,
            gasPrice: 20
        }
    )
    console.log(`Transaction hash: ${tx.hash}`);
    const receipt = await tx.wait();
    console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}

//调用swap方法
let swapExactTokensForTokens = async () => {
    let uniswapV2Router02Address = routerAddress;

    let amountIn = new BN(10).mul(p18).toString();
    let amountOutMin = new BN(9).mul(p18).toString();
    let path = [chtAddress, bnbAddress]
    let to = address1;
    let deadline = 2629448614;

    let data = require("../build/contracts/UniswapV2Router02.json");
    let routerAbi = contract(data).abi;
    let routerContract = new ethers.Contract(uniswapV2Router02Address, routerAbi, provider);
    const contractWithSigner = routerContract.connect(wallet1);
    const tx = await contractWithSigner.swapExactTokensForTokens(
        amountIn, amountOutMin, path, to, deadline, {
            gasLimit: 8000000,
            gasPrice: 20
        }
    )
    console.log(`Transaction hash: ${tx.hash}`);
    const receipt = await tx.wait();
    console.log(`Transaction was mined in block ${receipt.blockNumber}`);
}

// chtApprove(1000000).then(function (){ //approve
//     bnbApprove(1000000).then(function (){ //approve
//         addLiquidity().then(function (){//添加流动性
//             // swapExactTokensForTokens()
//         })
//     });
// });

swapExactTokensForTokens()

几个注意事项:

1,把几个合约拷贝进contract目录下后,由于solidity版本不同,不能使用truffle compile一起编译,要一个一个编译,具体做法就是编译哪个合约的时候,就把其他的合约后缀名改掉

2,编译不同版本的合约时,在配置文件中solc version要填写对应的版本号

3,编译uni的factory和router时,编译器配置如下(version填写对应的)

compilers: {
    solc: {
        version: "0.6.6",    // Fetch exact version from solc-bin (default: truffle's version)
        docker: false,        // Use "0.5.1" you've installed locally with docker (default: false)
        settings: {          // See the solidity docs for advice about optimization and evmVersion
            optimizer: {
                enabled: true,
                runs: 9999
            },
            evmVersion: "istanbul",
            outputSelection: {
                "*": {
                    "": [
                        "ast"
                    ],
                    "*": [
                        "evm.bytecode.object",
                        "evm.deployedBytecode.object",
                        "abi",
                        "evm.bytecode.sourceMap",
                        "evm.deployedBytecode.sourceMap",
                        "metadata"
                    ]
                },
            }
        }
    }
}

4,发布合约时,先发布factory合约,然后调用INIT_CODE_PAIR_HASH方法得到pair合约hash,填入到router合约后再发布router合约

5,invoke时gaslimit调大一点

也可以部署一份uniswap交易所的前端,仓库名为uniswap-interface,切换至v2.2.10,修改源码中router合约的地址(/src/constants/index.ts中第六行),使用yarn命令编译,yarn start命令发布,即可在本地前端页面上调用uniswap,但是只支持在以太坊的几个测试网上,如需切换到自己部署的网络,还需要去修改源码


转载请注明来源

×

喜欢就点赞,疼爱就打赏