Uniswap V2 DApp — Core Implementation
Entity models, Nethereum integration, and concrete Uniswap V2 calls for pools, liquidity, pricing, and swaps.
The previous two articles covered Uniswap, the dev environment, and baseline data. This post walks through entity classes, Nethereum helpers, and concrete Uniswap calls — connecting to a chain node, creating pools for arbitrary ERC20 pairs, adding/removing liquidity, reading LP reserves, pricing tokens, and executing swaps.
Project structure
The solution is organized into `Model`, `Resources`, `Utils`, and related folders. `Model` holds entities for RPC nodes, contracts, accounts, swap metadata, and Web3 helpers. Router, factory, and LP ABIs live under `Resources`. `Utils/ABIFunction.cs` defines ABI helper types and file extensions.

Project directory layout
Entity classes
RPCModel Stores chain and node settings: RPC URL, network ID, gas price, and gas limit.
ContractModel Contract entity with address, ABI, and liquidity amounts used for add/remove/swap (`AmountLiquidity`).
AccountModel Wallet entity with address and private key.
SwapModel Swap settings including slippage and the token path array.
Web3Ext Nethereum wrapper for pool creation, add/remove liquidity, LP address lookup, reserve reads, router approvals, and swap execution.
Feature implementation
On startup the app instantiates RPC, router, factory, LP contracts, and accounts, loading ABIs, addresses, and wallet keys.

Feature flow diagram
Create pool
Pick any ERC20 pair and call the factory `createPair` method to deploy a new liquidity pool.
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;
}Add liquidity
Adding liquidity calls `addLiquidity` on the Uniswap router. Key params: `amountADesired` / `amountBDesired` are desired deposit sizes; `amountAMin` / `amountBMin` guard against price movement.
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;
}Remove liquidity
Removing liquidity calls `removeLiquidity` on the router. `liquidity` is the LP amount; `amountAMin` / `amountBMin` set minimum tokens received to limit slippage.
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;
}Pool depth (reserves)
Reserve data from the LP contract powers token pricing. `getReserves` is a parameterless LP method.
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;
}Buy tokens
Buys use `swapExactTokensForTokens`. Before sending, call `getAmountsOut` to estimate output, subtract slippage, and pass the result as `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;
}Sell tokens
Sells call `swapExactTokensForTokensSupportingFeeOnTransferTokens`, which supports fee-on-transfer, burn, deflation, and inflation token mechanics.
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;
}
}