← 返回部落格

UniswapV2交易DAPP開發-基本實現

上兩篇文章對Uniswap、開發環境及需要的基礎資料進行了詳細的說明,本篇將對用到的實體類、Nethereum相關的類、及對Uniswap具體的呼叫進行詳細的講解。具體包括通過Nethereum和區塊鏈節點建立連線、根據任意幣對建立流動池子、給池子新增流動性、撤出流動性、獲得LP地址、獲得池子深度計算Token代幣價格以及進行Token兌換交易等。

程式結構

專案結構由Model、Resources、Utils等目錄組成,Model主要儲存節點、合約、賬戶、Swap交易資訊及Web3操作等實體類、擴充套件類。路由、工廠、LP等合約的ABI資訊已檔案的形式儲存在Resources目錄下。Utils目錄下,ABIFunction.cs為ABI操作函式定義的型別及File的擴充套件操作。

vs_ProjectFile

工程目錄結構

實體類

RPCModel

鏈、節點等相關資訊儲存在RPCModel類中,主要包括節點URL、網路ID以及鏈的GasPrice和操作的GasLimit。

ContractModel

ContractModel合約實體類主要包括合約地址、合約的ABI以及新增池子、撤池子、交易兌換的數量欄位(AmountLiquidity)。

AccountModel

AccountModel賬戶類,主要用到了地址、私鑰等屬性。

SwapModel

SwapModel為代幣交易兌換時用到的類,主要包括滑點設定和Token兌換路由陣列。

Web3Ext為對Nethereum的擴充套件和封裝,主要包括流動池的建立、新增流動池、撤出流動性、獲取LP地址、獲取流動池子的深度資訊、對路由合約授權操作以及Swap交易兌換等。

功能實現

程式啟動就建立了節點、路由合約、Factory合約、LP合約、賬戶等例項,並載入了合約對應的ABI和地址,賬戶對應的地址和私鑰。

Uniswap_All

功能流程圖

建立池子

選擇任意的Erc20幣對,通過Factory工廠合約提供的“createPair"介面進行流動池子的建立。

public static ResultModel createPair(RPCModel rPCModel, AccountModel accountModel, ContractModel factoryContract, ContractModel contractA, ContractModel contractB)
        {
            ResultModel resultModel=new ResultModel();
            try
            {
                Account account = new Account(accountModel.PrivateKey, rPCModel.NetworkId);
                Web3 web3 = new Web3(account, rPCModel.URL);
                Contract myContract = web3.Eth.GetContract(factoryContract.ABI, factoryContract.Address);
                BigInteger gPrice = Web3.Convert.ToWeiFromUnit(rPCModel.GasPrice, 1000000000);
                BigInteger gasLimit = new BigInteger(rPCModel.GasLimit);
                TransactionInput transactionInput = new TransactionInput
                {
                    Data = "",
                    Gas = new HexBigInteger(gasLimit),
                    From = account.Address,
                    Value = new HexBigInteger(0),
                    GasPrice = new HexBigInteger(gPrice)
                };
                var swapResult = myContract.GetFunction("createPair").SendTransactionAsync(transactionInput, contractA.Address, contractB.Address);
                swapResult.Wait();
                int count = 0;
                resultModel.TransHash = swapResult.Result;
                while (true)
                {
                    var receipt = web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(swapResult.Result);
                    receipt.Wait();
                    if (receipt.Result != null)
                    {
                        resultModel.State = (int)receipt.Result.Status.ToUlong();
                        break;
                    }
                    if (count >= 20)
                    {
                        resultModel.State = 2;
                        break;
                    }
                    Thread.Sleep(2000);
                    count++;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.InnerException != null)
                {
                    Console.WriteLine(ex.InnerException.ToString());
                }
                resultModel.Message = ex.Message;
            }
            return resultModel;
        }

新增流動性

新增流動是呼叫Uniswap的路由合約中的addLiquidity進行操作。其中需要注意的引數:amountADesired、amountBDesired使用者期望新增的數量,amountAMin、amountBMin為了避免價格波動帶來損失,最小允許新增的數量。

public static ResultModel addLiquidity(RPCModel rPCModel, AccountModel accountModel, ContractModel routerContract, ContractModel contractA, ContractModel contractB)
        {
            ResultModel resultModel = new ResultModel();
            try
            {
                Account account = new Account(accountModel.PrivateKey, rPCModel.NetworkId);
                Web3 web3 = new Web3(account, rPCModel.URL);
                Contract myContract = web3.Eth.GetContract(routerContract.ABI, routerContract.Address);
                BigInteger gPrice = Web3.Convert.ToWeiFromUnit(rPCModel.GasPrice, 1000000000);
                BigInteger gasLimit = new BigInteger(rPCModel.GasLimit);
                BigInteger amountADesired = Web3.Convert.ToWei(contractA.AmountLiquidity, contractA.UnitDecimal);
                BigInteger amountBDesired = Web3.Convert.ToWei(contractB.AmountLiquidity, contractB.UnitDecimal);
                TransactionInput transactionInput = new TransactionInput
                {
                    Data = "",
                    Gas = new HexBigInteger(gasLimit),
                    From = account.Address,
                    Value = new HexBigInteger(0),
                    GasPrice = new HexBigInteger(gPrice)
                };
                var swapResult = myContract.GetFunction("addLiquidity").SendTransactionAsync(transactionInput, contractA.Address, contractB.Address, amountADesired, amountBDesired, 0, 0, account.Address,GetSeconds(DateTime.Now));
                swapResult.Wait();
                int count = 0;
                resultModel.TransHash = swapResult.Result;
                while (true)
                {
                    var receipt = web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(swapResult.Result);
                    receipt.Wait();
                    if (receipt.Result != null)
                    {
                        resultModel.State = (int)receipt.Result.Status.ToUlong();
                        break;
                    }
                    if (count >= 20)
                    {
                        resultModel.State = 2;
                        break;
                    }
                    Thread.Sleep(2000);
                    count++;
                }
            }
            catch (Exception ex)
            {
                resultModel.State = -1;
                resultModel.Message = ex.Message;
                if (ex.InnerException != null)
                {
                    resultModel.Message=ex.InnerException.Message;
                }
            }
            return resultModel;
        }

移除流動性

移除流動是呼叫Uniswap的路由合約中的removeLiquidity進行操作。其中liquidity為LP的數量,amountAMin、amountBMin為了避免價格波動帶來損失,最小允許獲得的代幣數量。

public static ResultModel removeLiquidity(RPCModel rPCModel, AccountModel accountEntity, ContractModel routerContract, ContractModel contractLP, ContractModel contractA, ContractModel contractB)
        {
            ResultModel resultModel = new ResultModel();
            try
            {
                Account account = new Account(accountEntity.PrivateKey, rPCModel.NetworkId);
                Web3 web3 = new Web3(account, rPCModel.URL);
                Contract myContract = web3.Eth.GetContract(routerContract.ABI, routerContract.Address);
                BigInteger gPrice = Web3.Convert.ToWeiFromUnit(rPCModel.GasPrice, 1000000000);
                BigInteger gasLimit = new BigInteger(rPCModel.GasLimit);
                BigInteger liquidity = Web3.Convert.ToWei(contractLP.AmountLiquidity, contractLP.UnitDecimal);
                TransactionInput transactionInput = new TransactionInput
                {
                    Data = "",
                    Gas = new HexBigInteger(gasLimit),
                    From = account.Address,
                    Value = new HexBigInteger(0),
                    GasPrice = new HexBigInteger(gPrice)
                };
                var swapResult = myContract.GetFunction("removeLiquidity").SendTransactionAsync(transactionInput, contractA.Address, contractB.Address, liquidity, 0, 0, account.Address,GetSeconds(DateTime.Now));
                swapResult.Wait();
                int count = 0;
                resultModel.TransHash = swapResult.Result;
                resultModel.Message = "LP撤出成功!";
                while (true)
                {
                    var receipt = web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(swapResult.Result);
                    receipt.Wait();
                    if (receipt.Result != null)
                    {
                        resultModel.State = (int)receipt.Result.Status.ToUlong();
                        break;
                    }
                    if (count >= 20)
                    {
                        resultModel.State = 2;
                        break;
                    }
                    Thread.Sleep(2000);
                    count++;
                }
            }
            catch (Exception ex)
            {
                resultModel.State = -1;
                resultModel.Message=ex.Message;
                if (ex.InnerException != null)
                {
                    resultModel.Message=ex.Message+ex.InnerException.ToString();
                }
            }
            return resultModel;
        }

獲取池子深度資訊

通過獲得的深度資訊可以計算代幣的價格,getReserves是LP合約提供的方法,該方法無引數。

public static ResultModel getLPReserves(RPCModel rPCModel, ContractModel lPContract, ContractModel contractA, ContractModel contractB)
        {
            ResultModel resultModel = new ResultModel();
            try
            {
                Web3 web3 = new Web3(rPCModel.URL);
                Contract myContract = web3.Eth.GetContract(lPContract.ABI, lPContract.Address);
                var reservesResult = myContract.GetFunction("getReserves").CallDecodingToDefaultAsync();// .CallAsync<BigInteger>();
                reservesResult.Wait();
                if ((BigInteger)reservesResult.Result[0].Result > 0)
                {
                    decimal reserves0;// = Web3.Convert.FromWei((BigInteger)reservesResult.Result[0].Result);
                    decimal reserves1;// = Web3.Convert.FromWei((BigInteger)reservesResult.Result[1].Result);
                    reserves0 = Web3.Convert.FromWei((BigInteger)reservesResult.Result[0].Result, contractA.UnitDecimal);
                    reserves1 = Web3.Convert.FromWei((BigInteger)reservesResult.Result[1].Result, contractB.UnitDecimal);
                    resultModel.TokenAReserves = reserves0;
                    resultModel.TokenBReserves = reserves1;
                    resultModel.State = 1;
                }
            }
            catch (Exception ex)
            {
                resultModel.State = -1;
                resultModel.Message = ex.Message;
            }
            return resultModel;
        }

Token代幣買入

這裡呼叫了swapExactTokensForTokens方法進行代幣的買入兌換,在傳送代幣買入指令之前可以先通過getAmountsOut函式計算能得到的代幣數量,然後減去允許的滑點得到amountOutMin引數。

public static ResultModel swapExactTokensForTokens(RPCModel rPCModel, AccountModel accountEntity, ContractModel routerContract, ContractModel contractA, ContractModel contractB, SwapModel swapModel)
        {
            ResultModel resultModel = new ResultModel();
            try
            {
                Account account = new Account(accountEntity.PrivateKey, rPCModel.NetworkId);
                Web3 web3 = new Web3(account, rPCModel.URL);
                Contract myContract = web3.Eth.GetContract(routerContract.ABI, routerContract.Address);
                BigInteger amountIn = 0;
                amountIn = Web3.Convert.ToWei(contractB.AmountLiquidity, contractB.UnitDecimal);
                BigInteger gPrice = Web3.Convert.ToWeiFromUnit(rPCModel.GasPrice, 1000000000);
                var amountResult = myContract.GetFunction("getAmountsOut").CallDecodingToDefaultAsync(amountIn, swapModel.Path);
                amountResult.Wait();
                System.Collections.Generic.List<BigInteger> list = (System.Collections.Generic.List<BigInteger>)amountResult.Result[0].Result;
                decimal decOut = 0;
                BigInteger amountOutMin = 0;//
                decOut = (decimal)Web3.Convert.FromWei((BigInteger)list[1], contractA.UnitDecimal) * (decimal)(1 - swapModel.Slippage / 100);
                amountOutMin = Web3.Convert.ToWei(decOut, contractA.UnitDecimal);
                BigInteger gasLimit=new BigInteger(rPCModel.GasLimit);
                TransactionInput transactionInput = new TransactionInput
                {
                    Data = "",
                    Gas = new HexBigInteger(gasLimit),
                    From = account.Address,
                    Value = new HexBigInteger(0),
                    GasPrice = new HexBigInteger(gPrice)
                };
                var swapResult = myContract.GetFunction("swapExactTokensForTokens").SendTransactionAsync(transactionInput, amountIn, amountOutMin, swapModel.Path, account.Address, GetSeconds(DateTime.Now));
                swapResult.Wait();
                int count = 0;
                resultModel.TransHash = swapResult.Result;
                while (true)
                {
                    var receipt = web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(swapResult.Result);
                    receipt.Wait();
                    if (receipt.Result != null)
                    {
                        resultModel.State = (int)receipt.Result.Status.ToUlong();
                        if (resultModel.State == 1)
                        {
                            resultModel.Message = "Swap交易成功!";
                        }
                        else
                        {
                            resultModel.Message = "Swap交易失敗!";
                        }
                        break;
                    }
                    if (count >= 20)
                    {
                        resultModel.State = 2;
                        resultModel.Message = "獲取交易hash超時!";
                        break;
                    }
                    Thread.Sleep(2000);
                    count++;
                }
            }
            catch (Exception ex)
            {
                resultModel.State =-1;
                resultModel.Message= ex.Message;
                if (ex.InnerException != null)
                {
                    resultModel.Message += ex.InnerException.Message;
                }
            }
            return resultModel;
        }

Token代幣賣出

代幣賣出呼叫了swapExactTokensForTokensSupportingFeeOnTransferTokens函式,該函式支援有滑點、銷燬、通縮、通脹等模式的代幣Token。

public static ResultModel swapExactTokensForTokensSupportingFeeOnTransferTokens(RPCModel rPCModel, AccountModel accountModel, ContractModel routerContract, ContractModel contractA, ContractModel contractB, SwapModel swapModel)
        {
            ResultModel resultModel = new ResultModel();
            try
            {
                Account account = new Account(accountModel.PrivateKey, rPCModel.NetworkId);
                Web3 web3 = new Web3(account, rPCModel.URL);
                Contract myContract = web3.Eth.GetContract(routerContract.ABI, routerContract.Address);
                BigInteger amountIn =  Web3.Convert.ToWei(contractA.AmountLiquidity, contractA.UnitDecimal);
                BigInteger gPrice = Web3.Convert.ToWeiFromUnit(rPCModel.GasPrice, 1000000000);
                var amountResult = myContract.GetFunction("getAmountsOut").CallDecodingToDefaultAsync(amountIn, swapModel.Path);
                amountResult.Wait();
                System.Collections.Generic.List<BigInteger> list = (System.Collections.Generic.List<BigInteger>)amountResult.Result[0].Result;
                decimal decOut = 0;
                BigInteger amountOutMin = 0;
                decOut = (decimal)Web3.Convert.FromWei((BigInteger)list[1], contractB.UnitDecimal) * (decimal)(1 - swapModel.Slippage / 100);
                amountOutMin = Web3.Convert.ToWei(decOut, contractB.UnitDecimal);
                BigInteger gasLimit = new BigInteger(rPCModel.GasLimit);
                TransactionInput transactionInput = new TransactionInput
                {
                    Data = "",
                    Gas = new HexBigInteger(gasLimit),
                    From = account.Address,
                    Value = new HexBigInteger(0),
                    GasPrice = new HexBigInteger(gPrice)
                };
                var swapResult = myContract.GetFunction("swapExactTokensForTokensSupportingFeeOnTransferTokens").SendTransactionAsync(transactionInput, amountIn, amountOutMin, swapModel.Path, account.Address, GetSeconds(DateTime.Now));
                swapResult.Wait();
                int count = 0;
                resultModel.TransHash = swapResult.Result;
                while (true)
                {
                    try
                    {
                        var receipt = web3.Eth.Transactions.GetTransactionReceipt.SendRequestAsync(swapResult.Result);
                        receipt.Wait();
                        if (receipt.Result != null)
                        {
                            resultModel.State = (int)receipt.Result.Status.ToUlong();
                            if (resultModel.State == 1)
                            {
                                resultModel.Message = "Swap交易成功!";
                            }
                            else
                            {
                                resultModel.Message = "Swap交易失敗!";
                            }
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    if (count >= 20)
                    {
                        resultModel.State = 2;
                        resultModel.Message = "獲取交易hash超時!";
                        break;
                    }
                    Thread.Sleep(2000);
                    count++;
                }
                return resultModel;
            }
            catch (Exception ex)
            {
                resultModel.State = -1;
                resultModel.Message= "交易失敗:" + ex.Message;
                if (ex.InnerException != null)
                {
                    resultModel.Message += ex.InnerException.Message;
                }
                return resultModel;
            }
        }