← 블로그로

Uniswap V2 DApp — 핵심 구현

엔티티 모델, Nethereum 통합, 풀·유동성·가격·스왑을 위한 구체적인 Uniswap V2 호출.

이전 두 글에서는 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;
            }
        }