← ブログに戻る

Uniswap V2 DApp — コア実装

エンティティモデル、Nethereum 統合、プール・流動性・価格・スワップの具体的な Uniswap V2 呼び出し。

前の 2 記事では Uniswap、開発環境、基礎データを取り上げました。本記事ではエンティティクラス、Nethereum ヘルパー、具体的な Uniswap 呼び出し(チェーンノードへの接続、任意の ERC20 ペアのプール作成、流動性の追加 / 除去、LP 準備金の取得、トークン価格算出、スワップ実行)を解説します。

プロジェクト構成

ソリューションは `Model`、`Resources`、`Utils` などのフォルダで構成されます。`Model` は RPC ノード、コントラクト、アカウント、スワップメタデータ、Web3 ヘルパーのエンティティを保持します。Router、Factory、LP の ABI は `Resources` にあります。`Utils/ABIFunction.cs` は ABI ヘルパー型とファイル拡張子を定義します。

vs_ProjectFile

プロジェクトディレクトリ構成

エンティティクラス

RPCModel はチェーンとノード設定(RPC URL、ネットワーク ID、ガス価格、ガス上限)を保持。

ContractModel はアドレス、ABI、追加 / 除去 / スワップに使う流動性数量(`AmountLiquidity`)を持つコントラクトエンティティ。

AccountModel はアドレスと秘密鍵を持つウォレットエンティティ。

SwapModel はスリッページとトークンパス配列を含むスワップ設定。

Web3Ext プール作成、流動性の追加 / 除去、LP アドレス検索、準備金取得、ルーター承認、スワップ実行のための Nethereum ラッパー。

機能実装

起動時にアプリは RPC、ルーター、ファクトリ、LP コントラクト、アカウントをインスタンス化し、ABI、アドレス、ウォレットキーを読み込みます。

Uniswap_All

機能フロー図

プール作成

任意の ERC20 ペアを選び、ファクトリの `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;
        }

流動性除去

流動性の除去はルーターの `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;
        }

プール深度(準備金)

LP コントラクトの準備金データがトークン価格算出の基になります。`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;
        }

トークン購入

買いは `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;
        }

トークン売却

売りは `swapExactTokensForTokensSupportingFeeOnTransferTokens` を呼び出します。これは転送手数料、バーン、デフレ、インフレのトークンメカニズムに対応します。

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;
            }
        }