Exemplo n.º 1
0
        public async Task <string> CashOut(Guid id, string coinAddress, string clientAddr, string toAddr, BigInteger amount, string sign)
        {
            await ThrowOnExistingId(id);

            var coinAFromDb = await GetCoinWithCheck(coinAddress);

            if (string.IsNullOrEmpty(sign))
            {
                sign = await GetSign(id, coinAddress, clientAddr, toAddr, amount);
            }

            ThrowOnWrongSignature(id, coinAddress, clientAddr, toAddr, amount, sign);

            var contract = _web3.Eth.GetContract(_settings.MainExchangeContract.Abi, _settings.MainExchangeContract.Address);
            var cashout  = contract.GetFunction("cashout");

            var convertedId = EthUtils.GuidToBigInteger(id);
            // function cashout(uint id, address coinAddress, address client, address to, uint amount, bytes client_sign, bytes params) onlyowner {
            var transactionHash = await cashout.SendTransactionAsync(Constants.AddressForRoundRobinTransactionSending,
                                                                     new HexBigInteger(Constants.GasForCoinTransaction), new HexBigInteger(0),
                                                                     convertedId, coinAFromDb.AdapterAddress, clientAddr, toAddr, amount, sign.HexToByteArray().FixByteOrder(), new byte[0]);

            await SaveUserHistory(coinAddress, amount.ToString(), clientAddr, toAddr, transactionHash, "CashOut");
            await CreatePendingTransaction(coinAddress, clientAddr, transactionHash);

            return(transactionHash);
        }
Exemplo n.º 2
0
        public async Task GetEthBalance()
        {
            string  address = "0x0000000000000000000000000000000000000000";
            decimal balance = await EthUtils.GetEtherBalance(address);

            Assert.IsTrue(balance > 0);
        }
Exemplo n.º 3
0
        public async Task <string> Transfer(Guid id, string coinAddress, string from, string to, BigInteger amount, string sign)
        {
            await ThrowOnExistingId(id);

            var coinAFromDb = await GetCoinWithCheck(coinAddress);

            if (string.IsNullOrEmpty(sign))
            {
                sign = await GetSign(id, coinAddress, from, to, amount);
            }

            ThrowOnWrongSignature(id, coinAddress, from, to, amount, sign);

            var contract         = _web3.Eth.GetContract(_settings.MainExchangeContract.Abi, _settings.MainExchangeContract.Address);
            var transferFunction = contract.GetFunction("transfer");

            var convertedId     = EthUtils.GuidToBigInteger(id);
            var transactionHash = await transferFunction.SendTransactionAsync(Constants.AddressForRoundRobinTransactionSending,
                                                                              new HexBigInteger(Constants.HalfGasLimit), new HexBigInteger(0),
                                                                              convertedId, coinAFromDb.AdapterAddress, from, to, amount, sign.HexToByteArray().FixByteOrder(), new byte[0]);

            await SaveUserHistory(coinAddress, amount.ToString(), from, to, transactionHash, "Transfer");
            await CreatePendingTransaction(coinAddress, from, transactionHash);

            return(transactionHash);
        }
Exemplo n.º 4
0
        public async Task <IdCheckResult> CheckId(Guid guidToCheck)
        {
            var contract = _web3.Eth.GetContract(_settings.MainExchangeContract.Abi, _settings.MainExchangeContract.Address);

            var  transactionsCheck = contract.GetFunction("transactions");
            bool isInList          = true;
            Guid useNext           = guidToCheck;

            while (isInList)
            {
                var bigIntRepresentation = EthUtils.GuidToBigInteger(useNext);
                isInList = await transactionsCheck.CallAsync <bool>(bigIntRepresentation);

                if (isInList)
                {
                    useNext = Guid.NewGuid();
                }
            }

            return(new IdCheckResult()
            {
                IsFree = useNext == guidToCheck,
                ProposedId = useNext
            });
        }
        public async Task TestTransferTokens()
        {
            var colorCoin = await _coinRepository.GetCoinByAddress(_tokenAdapterAddress);

            var toAddress = _settings.EthereumMainAccount;

            await CashinTokens(_externalTokenAddress, _clientTokenTransferAddress, new BigInteger(100), _tokenAdapterAddress, _clientA);

            var transferUser = await _transferContractService.GetTransferAddressUser(colorCoin.AdapterAddress, _clientTokenTransferAddress);

            var currentBalance = await _transferContractService.GetBalanceOnAdapter(colorCoin.AdapterAddress, _clientA);

            Assert.AreEqual(transferUser, _clientA.ToLower());

            var guid = Guid.NewGuid();

            EthUtils.GuidToBigInteger(guid);
            var externalSign = await _exchangeService.GetSign(guid, _tokenAdapterAddress, _clientA, toAddress, currentBalance);

            var transferHash = await _exchangeService.Transfer(guid, _tokenAdapterAddress, _clientA, toAddress,
                                                               currentBalance, externalSign);

            while (await _transactionService.GetTransactionReceipt(transferHash) == null)
            {
                await Task.Delay(100);
            }

            var currentBalanceOnAdapter = await _transferContractService.GetBalanceOnAdapter(colorCoin.AdapterAddress, _clientA);

            var newBalance = await _transferContractService.GetBalanceOnAdapter(colorCoin.AdapterAddress, toAddress);

            Assert.IsTrue(await _transactionService.IsTransactionExecuted(transferHash, Constants.GasForCoinTransaction));
            Assert.IsTrue(currentBalanceOnAdapter == 0);
            Assert.IsTrue(currentBalance <= newBalance);
        }
 private static string GetHash(Guid guid, string coinAdapterAddress, string fromAddress, string toAddress, BigInteger currentBalance)
 {
     return(EthUtils.GuidToByteArray(guid).ToHex() +
            coinAdapterAddress.HexToByteArray().ToHex() +
            fromAddress.HexToByteArray().ToHex() +
            toAddress.HexToByteArray().ToHex() +
            EthUtils.BigIntToArrayWithPadding(currentBalance).ToHex());
 }
Exemplo n.º 7
0
        public void Data()
        {
            var guid = Guid.Parse("176a82d8-3154-4c76-bab8-441ad43d0de6");

            var strForHash = EthUtils.GuidToByteArray(guid).ToHex();

            var hash = new Sha3Keccack().CalculateHash(strForHash.HexToByteArray());

            var sign = Sign(hash, private_key_a).ToHex();
        }
Exemplo n.º 8
0
        public async Task <OperationEstimationResult> EstimateCashoutGas(Guid id, string coinAdapterAddress, string fromAddress, string toAddress, BigInteger amount, string sign)
        {
            var blackListedAddress = await _blackListAddressesRepository.GetAsync(toAddress);

            var whiteListedAddress = await _whiteListAddressesRepository.GetAsync(toAddress);

            if (blackListedAddress != null && whiteListedAddress == null)
            {
                return(new OperationEstimationResult()
                {
                    GasAmount = Constants.GasForCoinTransaction,
                    IsAllowed = false
                });
            }

            //It is ok.
            if (ChaosKitty.MeowButLogically())
            {
                return(new OperationEstimationResult()
                {
                    GasAmount = 50000,
                    IsAllowed = true
                });
            }

            var coinAFromDb = await GetCoinWithCheck(coinAdapterAddress);

            if (string.IsNullOrEmpty(sign))
            {
                sign = await GetSign(id, coinAdapterAddress, fromAddress, toAddress, amount);
            }

            ThrowOnWrongSignature(id, coinAdapterAddress, fromAddress, toAddress, amount, sign);

            var contract    = _web3.Eth.GetContract(_settings.MainExchangeContract.Abi, _settings.MainExchangeContract.Address);
            var cashout     = contract.GetFunction("cashout");
            var convertedId = EthUtils.GuidToBigInteger(id);
            //ACTION
            var estimatedGasForOperation = await cashout.EstimateGasAsync(_settings.EthereumMainAccount,
                                                                          new HexBigInteger(Constants.GasForCoinTransaction), new HexBigInteger(0),
                                                                          convertedId,
                                                                          _addressUtil.ConvertToChecksumAddress(coinAFromDb.AdapterAddress),
                                                                          fromAddress,
                                                                          toAddress,
                                                                          amount,
                                                                          sign.HexToByteArray(),
                                                                          new byte[0]);

            return(new OperationEstimationResult()
            {
                GasAmount = estimatedGasForOperation.Value,
                IsAllowed = estimatedGasForOperation.Value < Constants.GasForCoinTransaction
            });
        }
        public byte[] GetHash(Guid id, string coinAddress, string clientAddr, string toAddr, BigInteger amount)
        {
            var strForHash = EthUtils.GuidToByteArray(id).ToHex() +
                             coinAddress.HexToByteArray().ToHex() +
                             clientAddr.HexToByteArray().ToHex() +
                             toAddr.HexToByteArray().ToHex() +
                             EthUtils.BigIntToArrayWithPadding(amount).ToHex();

            var hash = new Sha3Keccack().CalculateHash(strForHash.HexToByteArray());

            return(hash);
        }
Exemplo n.º 10
0
        private async Task ThrowOnExistingId(Guid id)
        {
            var contract             = _web3.Eth.GetContract(_settings.MainExchangeContract.Abi, _settings.MainExchangeContract.Address);
            var transactionsCheck    = contract.GetFunction("transactions");
            var bigIntRepresentation = EthUtils.GuidToBigInteger(id);

            bool isInList = await transactionsCheck.CallAsync <bool>(bigIntRepresentation);

            if (isInList)
            {
                throw new ClientSideException(ExceptionType.OperationWithIdAlreadyExists, $"operation with guid {id}");
            }
        }
Exemplo n.º 11
0
 /// <summary>
 /// Transfers a specified amount of ether from the input UserWallet to a specified address.
 /// </summary>
 /// <param name="userWalletManager"> The wallet to send the ether from. </param>
 /// <param name="gasLimit"> The gas limit to use for this ether send transaction. </param>
 /// <param name="gasPrice"> The gas price to use for this ether send transaction. </param>
 /// <param name="address"> The address to send the ether to. </param>
 /// <param name="amount"> The amount of ether to send. </param>
 public override void Transfer(UserWalletManager userWalletManager, HexBigInteger gasLimit, HexBigInteger gasPrice, string address, decimal amount)
 {
     userWalletManager.SignTransaction <ConfirmTransactionPopup>(
         request => EthUtils.SendEther(request, gasLimit, gasPrice, userWalletManager.GetWalletAddress(), address, amount),
         gasLimit,
         gasPrice,
         SolidityUtils.ConvertToUInt(amount, 18),
         address,
         "",
         address,
         AssetAddress,
         amount,
         "ETH");
 }
Exemplo n.º 12
0
        private static byte[] SignData(FiscoTransModel trans, ECKeyPair key)
        {
            byte[][] b = new byte[10][];
            b[0] = trans.data.AccountNonce;
            b[1] = LibraryHelper.FromBigInteger(trans.data.Price);
            b[2] = LibraryHelper.FromBigInteger(trans.data.GasLimit);
            b[3] = LibraryHelper.FromBigInteger(trans.data.BlockLimit);
            b[4] = trans.data.Recipient;
            b[5] = trans.data.Amount == null ? null : LibraryHelper.FromBigInteger(trans.data.Amount);
            b[6] = trans.data.Payload;
            b[7] = LibraryHelper.FromBigInteger(trans.data.ChainID);
            b[8] = LibraryHelper.FromBigInteger(trans.data.GroupID);
            b[9] = trans.data.ExtraData;

            var txb = Nethereum.RLP.RLP.EncodeElementsAndList(b);

            if (trans.smcrypto)
            {
                BigInteger r, s;
                SM2Utils.Sign(SM2Utils.SM3Hash(txb), key.prik, out r, out s);
                trans.data.R = LibraryHelper.FromBigInteger(r);
                trans.data.S = LibraryHelper.FromBigInteger(s);

                var    pub1 = key.pubk.Q.XCoord.GetEncoded();
                var    pub2 = key.pubk.Q.YCoord.GetEncoded();
                byte[] v    = new byte[pub1.Length + pub2.Length];
                Array.Copy(pub1, 0, v, 0, pub1.Length);
                Array.Copy(pub2, 0, v, pub1.Length, pub2.Length);
                Console.WriteLine(string.Format("sign.V:{0}", Hex.ToHexString(v)));
                trans.data.V = v;
            }
            else
            {
                var bytes = EthUtils.ConvertSHA256byte(txb);
                var sign  = EthUtils.Sign(bytes, key.prik);
                trans.data.R = sign.Item1;
                trans.data.S = sign.Item2;
                trans.data.V = sign.Item3;
            }
            byte[][] si = new byte[b.Length + 3][];
            Array.Copy(b, 0, si, 0, b.Length);
            si[b.Length]     = trans.data.V;
            si[b.Length + 1] = trans.data.R;
            si[b.Length + 2] = trans.data.S;

            var txs = Nethereum.RLP.RLP.EncodeElementsAndList(si);

            return(txs);
        }
Exemplo n.º 13
0
        public void TestHash()
        {
            var guid       = Guid.NewGuid();
            var amount     = 100;
            var strForHash = EthUtils.GuidToByteArray(guid).ToHex() +
                             _tokenAdapterAddress.HexToByteArray().ToHex() +
                             _clientA.HexToByteArray().ToHex() +
                             _clientB.HexToByteArray().ToHex() +
                             EthUtils.BigIntToArrayWithPadding(new BigInteger(amount)).ToHex();

            byte[] expectedHash = new Sha3Keccack().CalculateHash(strForHash.HexToByteArray());
            byte[] actualHash   = _hashCalculator.GetHash(guid, _tokenAdapterAddress, _clientA, _clientB, amount);
            bool   isEqual      = Enumerable.SequenceEqual(expectedHash, actualHash);

            Assert.IsTrue(isEqual);
        }
Exemplo n.º 14
0
        public void Test22()
        {
            var guid = new Guid("0b67caf2-0b02-4691-ac25-04858b0fa475");

            var strForHash = EthUtils.GuidToByteArray(guid).ToHex() +
                             "0x8c32ad594a6dc17b2e8b40af3df2c3ce1f79cdd4".HexToByteArray().ToHex() +
                             "0x5c711f0bfad342c4691b6e23cedcdf39e3fe03c1".HexToByteArray().ToHex() +
                             "0x33f53d968aee3cfe1ad460457a29827bfff33d8c".HexToByteArray().ToHex() +
                             EthUtils.BigIntToArrayWithPadding(9500).ToHex();

            var hash = new Sha3Keccack().CalculateHash(strForHash.HexToByteArray());

            var sign = Sign(hash, "0x443dac9b6e682a887009cfd00690d0cac1905e494f84d03070174149c2d0cc76").ToHex();

            Assert.AreEqual("6ddfe17c1ff216df529277ff7fc94bff41b6984d3de36d2132f452986743de4c44831c1bd41d58043705a60aa853d6beeb8b2e0dcdb09805c5dd28b7e3e705ce1b", sign);
        }
Exemplo n.º 15
0
        public async Task <string> CashIn(Guid id, string coinAddress, string receiver, BigInteger amount)
        {
            var web3 = new Web3(_settings.EthereumUrl);

            await web3.Personal.UnlockAccount.SendRequestAsync(_settings.EthereumMainAccount, _settings.EthereumMainAccountPassword, 120);

            var coinAFromDb = await _coinRepository.GetCoinByAddress(coinAddress);

            if (coinAFromDb == null)
            {
                throw new Exception($"Coin with address {coinAddress} deos not exist");
            }

            Contract contract;

            if (coinAFromDb.ContainsEth)
            {
                contract = web3.Eth.GetContract(_settings.EthAdapterContract.Abi, coinAFromDb.AdapterAddress);
            }
            else
            {
                contract = web3.Eth.GetContract(_settings.TokenAdapterContract.Abi, coinAFromDb.AdapterAddress);
            }

            var convertedAmountA = amount;

            var convertedId = EthUtils.GuidToBigInteger(id);

            var cashin = contract.GetFunction("cashin");
            var res    = await cashin.CallAsync <bool>(_settings.EthereumMainAccount, new HexBigInteger(Constants.GasForCoinTransaction),
                                                       new HexBigInteger(0), receiver, convertedAmountA);

            string tr;

            if (coinAFromDb.ContainsEth)
            {
                tr = await cashin.SendTransactionAsync(_settings.EthereumMainAccount, new HexBigInteger(Constants.GasForCoinTransaction),
                                                       new HexBigInteger(convertedAmountA), receiver, convertedAmountA);
            }
            else
            {
                tr = await cashin.SendTransactionAsync(_settings.EthereumMainAccount, new HexBigInteger(Constants.GasForCoinTransaction),
                                                       new HexBigInteger(0), receiver, convertedAmountA);
            }

            return(tr);
        }
        public async Task TestCheckSign_IsWrong()
        {
            var guid   = Guid.NewGuid();
            var amount = 50;

            EthUtils.GuidToBigInteger(guid);
            var strForHash = EthUtils.GuidToByteArray(guid).ToHex() +
                             _ethereumAdapterAddress.HexToByteArray().ToHex() +
                             _clientA.HexToByteArray().ToHex() +
                             _clientA.HexToByteArray().ToHex() +
                             EthUtils.BigIntToArrayWithPadding(new BigInteger(amount)).ToHex();

            var hash   = new Sha3Keccack().CalculateHash(strForHash.HexToByteArray());
            var sign   = Sign(hash, _privateKeyA).ToHex();
            var result = _exchangeService.CheckSign(guid, _ethereumAdapterAddress, _clientA, _clientA, new BigInteger(amount - 1), sign);

            Assert.IsFalse(result);
        }
Exemplo n.º 17
0
        //Main Exchange contract should be migrated to use the function below in an appropriate way.
        public async Task <string> TransferWithoutSignCheck(Guid id, string coinAddress, string from, string to, BigInteger amount, string sign = "01")
        {
            await ThrowOnExistingId(id);

            var coinAFromDb = await GetCoinWithCheck(coinAddress);

            var contract         = _web3.Eth.GetContract(_settings.MainExchangeContract.Abi, _settings.MainExchangeContract.Address);
            var transferFunction = contract.GetFunction("transfer");

            var convertedId     = EthUtils.GuidToBigInteger(id);
            var transactionHash = await transferFunction.SendTransactionAsync(_settings.EthereumMainAccount,
                                                                              new HexBigInteger(Constants.GasForCoinTransaction), new HexBigInteger(0),
                                                                              convertedId, coinAFromDb.AdapterAddress, from, to, amount, sign.HexToByteArray(), new byte[0]);

            await SaveUserHistory(coinAddress, amount.ToString(), from, to, transactionHash, "TransferWithoutSignCheck");

            return(transactionHash);
        }
Exemplo n.º 18
0
        public async Task <string> CashinOverTransferContract(Guid id, string coin, string receiver, decimal amount)
        {
            var coinDb = await _coinRepository.GetCoin(coin);

            if (!coinDb.BlockchainDepositEnabled)
            {
                throw new ClientSideException(ExceptionType.WrongParams, "Coin must be payable");
            }
            var contract = _web3.Eth.GetContract(_settings.TokenTransferContract.Abi, _settings.TokenTransferContract.Address);
            var cashin   = contract.GetFunction("cashin");

            var blockchainAmount = amount.ToBlockchainAmount(coinDb.Multiplier);
            var convertedId      = EthUtils.GuidToBigInteger(id);
            var tr = await cashin.SendTransactionAsync(_settings.EthereumMainAccount, new HexBigInteger(Constants.GasForCoinTransaction),
                                                       new HexBigInteger(0), convertedId, coinDb.AdapterAddress, receiver, blockchainAmount, Constants.GasForCoinTransaction, new byte[0]);

            return(tr);
        }
        public async Task TestCheckSign_IsCorrect()
        {
            var guid   = Guid.NewGuid();
            var amount = 50;

            EthUtils.GuidToBigInteger(guid);
            var strForHash = EthUtils.GuidToByteArray(guid).ToHex() +
                             _tokenAdapterAddress.HexToByteArray().ToHex() +
                             _clientA.HexToByteArray().ToHex() +
                             _clientA.HexToByteArray().ToHex() +
                             EthUtils.BigIntToArrayWithPadding(new BigInteger(amount)).ToHex();

            var hash = new Sha3Keccack().CalculateHash(strForHash.HexToByteArray());
            var sign = Sign(hash, _privateKeyA).ToHex();
            //var externalSign = await _exchangeService.GetSign(guid, _tokenAdapterAddress, ClientA, ClientA, new BigInteger(amount));
            var result = _exchangeService.CheckSign(guid, _tokenAdapterAddress, _clientA, _clientA, new BigInteger(amount), sign);

            Assert.IsTrue(result);
        }
Exemplo n.º 20
0
        public async Task <string> TransferWithChange(Guid id, string coinAddress, string from, string to, BigInteger amount,
                                                      string signFrom, BigInteger change, string signTo)
        {
            if (amount <= change)
            {
                throw new ClientSideException(ExceptionType.WrongParams, "Amount can't be less or equal than change");
            }

            await ThrowOnExistingId(id);

            var coinAFromDb = await GetCoinWithCheck(coinAddress);

            if (string.IsNullOrEmpty(signFrom))
            {
                signFrom = await GetSign(id, coinAddress, from, to, amount);
            }

            if (string.IsNullOrEmpty(signTo))
            {
                signTo = await GetSign(id, coinAddress, to, from, change);
            }

            ThrowOnWrongSignature(id, coinAddress, from, to, amount, signFrom);
            ThrowOnWrongSignature(id, coinAddress, to, from, change, signTo);

            var contract         = _web3.Eth.GetContract(_settings.MainExchangeContract.Abi, _settings.MainExchangeContract.Address);
            var transferFunction = contract.GetFunction("transferWithChange");
            var convertedId      = EthUtils.GuidToBigInteger(id);
            var transactionHash  = await transferFunction.SendTransactionAsync(Constants.AddressForRoundRobinTransactionSending,
                                                                               new HexBigInteger(Constants.HalfGasLimit), new HexBigInteger(0),
                                                                               convertedId, coinAFromDb.AdapterAddress, from, to, amount, change,
                                                                               signFrom.HexToByteArray().FixByteOrder(), signTo.HexToByteArray().FixByteOrder(), new byte[0]);

            var difference = (amount - change);

            await SaveUserHistory(coinAddress, difference.ToString(), from, to, transactionHash, "TransferWithChange");
            await CreatePendingTransaction(coinAddress, from, transactionHash);

            return(transactionHash);
        }
Exemplo n.º 21
0
        private async Task ThrowOnExistingId(Guid id)
        {
            //Check Old contract(Prevent old transactions from executing)
            var addresses = new string[]
            {
                _settings.MainExchangeContract.Address,
                _settings.PreviousMainExchangeContractAddress
            };

            foreach (var address in addresses)
            {
                var contract             = _web3.Eth.GetContract(_settings.MainExchangeContract.Abi, address);
                var transactionsCheck    = contract.GetFunction("transactions");
                var bigIntRepresentation = EthUtils.GuidToBigInteger(id);

                bool isInList = await transactionsCheck.CallAsync <bool>(bigIntRepresentation);

                if (isInList)
                {
                    throw new ClientSideException(ExceptionType.OperationWithIdAlreadyExists, $"operation with guid {id}");
                }
            }
        }
Exemplo n.º 22
0
        //public async Task<string> Swap(Guid id, string clientA, string clientB, string coinA, string coinB, decimal amountA, decimal amountB, string signAHex,
        //    string signBHex)
        //{
        //    var web3 = new Web3(_settings.EthereumUrl);

        //    await web3.Personal.UnlockAccount.SendRequestAsync(_settings.EthereumMainAccount, _settings.EthereumMainAccountPassword, new HexBigInteger(120));

        //    var contract = web3.Eth.GetContract(_settings.MainExchangeContract.Abi, _settings.MainExchangeContract.Address);

        //    var coinAFromDb = await _coinRepository.GetCoin(coinA);
        //    var coinBFromDb = await _coinRepository.GetCoin(coinB);

        //    var convertedAmountA = amountA.ToBlockchainAmount(coinAFromDb.Multiplier);
        //    var convertedAmountB = amountB.ToBlockchainAmount(coinBFromDb.Multiplier);

        //    var convertedId = EthUtils.GuidToBigInteger(id);

        //    var swap = contract.GetFunction("swap");
        //    var tr = await swap.SendTransactionAsync(_settings.EthereumMainAccount, new HexBigInteger(Constants.GasForCoinTransaction), new HexBigInteger(0),
        //            convertedId, clientA, clientB, coinAFromDb.AdapterAddress, coinBFromDb.AdapterAddress, convertedAmountA, convertedAmountB, signAHex.HexToByteArray().FixByteOrder(), signBHex.HexToByteArray().FixByteOrder(), new byte[0]);
        //    await _cointTransactionService.PutTransactionToQueue(tr);
        //    return tr;
        //}
        public async Task <OperationEstimationResult> EstimateCashoutGas(Guid id, string coinAdapterAddress, string fromAddress, string toAddress, BigInteger amount, string sign)
        {
            var coinAFromDb = await GetCoinWithCheck(coinAdapterAddress);

            if (string.IsNullOrEmpty(sign))
            {
                sign = await GetSign(id, coinAdapterAddress, fromAddress, toAddress, amount);
            }

            ThrowOnWrongSignature(id, coinAdapterAddress, fromAddress, toAddress, amount, sign);

            var contract    = _web3.Eth.GetContract(_settings.MainExchangeContract.Abi, _settings.MainExchangeContract.Address);
            var cashout     = contract.GetFunction("cashout");
            var convertedId = EthUtils.GuidToBigInteger(id);
            //ACTION
            var estimatedGasForOperation = await cashout.EstimateGasAsync(_settings.EthereumMainAccount,
                                                                          new HexBigInteger(Constants.GasForCoinTransaction), new HexBigInteger(0), convertedId, coinAFromDb.AdapterAddress, fromAddress, toAddress, amount, sign.HexToByteArray().FixByteOrder(), new byte[0]);

            return(new OperationEstimationResult()
            {
                GasAmount = estimatedGasForOperation.Value,
                IsAllowed = estimatedGasForOperation.Value < Constants.GasForCoinTransaction
            });
        }
Exemplo n.º 23
0
        private static Dictionary <string, List <InteropTransfer> > GetInteropTransfers(Nexus nexus, Logger logger,
                                                                                        TransactionReceipt txr, EthAPI api, string[] swapAddresses)
        {
            logger.Debug($"get interop transfers for tx {txr.TransactionHash}");
            var interopTransfers = new Dictionary <string, List <InteropTransfer> >();

            Nethereum.RPC.Eth.DTOs.Transaction tx = null;
            try
            {
                // tx to get the eth transfer if any
                tx = api.GetTransaction(txr.TransactionHash);
            }
            catch (Exception e)
            {
                logger.Error("Getting eth tx failed: " + e.Message);
            }

            logger.Debug("Transaction status: " + txr.Status.Value);
            // check if tx has failed
            if (txr.Status.Value == 0)
            {
                logger.Error($"tx {txr.TransactionHash} failed");
                return(interopTransfers);
            }

            var     nodeSwapAddresses = swapAddresses.Select(x => EthereumWallet.EncodeAddress(x));
            Address interopAddress;

            try
            {
                interopAddress = ExtractInteropAddress(tx, logger);
            }
            catch (Exception e)
            {
                if (e.ToString().Contains("Header byte out of range"))
                {
                    // Ignoring this exception and skipping this tx.
                    // RecoverFromSignature() crashed and we cannot avoid it atm.
                    // Related to EIP-1559, example of probematic tx: https://etherscan.io/tx/0xb022c146d8d1e684de0c1faae43e7ce36afb6969719adfdcafcc5bb7d5913185
                    // TODO Fix by updating to new Nethereum and dealing with EIP-1559 better.
                    logger.Debug("Warning: Skipping 'Header byte out of range' tx: " + tx.TransactionHash);
                    return(interopTransfers);
                }
                else
                {
                    throw;
                }
            }

            // ERC721 (NFT)
            // TODO currently this code block is mostly copypaste from ERC20 block, later make a single method for both...
            //var erc721_events = txr.DecodeAllEvents<Nethereum.StandardNonFungibleTokenERC721.ContractDefinition.TransferEventDTOBase>();
            //foreach (var evt in erc721_events)
            //{
            //    var asset = EthUtils.FindSymbolFromAsset(nexus, evt.Log.Address);
            //    if (asset == null)
            //    {
            //        logger.Warning($"Asset [{evt.Log.Address}] not supported");
            //        continue;
            //    }

            //    var targetAddress = EthereumWallet.EncodeAddress(evt.Event.To);
            //    var sourceAddress = EthereumWallet.EncodeAddress(evt.Event.From);
            //    var tokenID = PBigInteger.Parse(evt.Event.TokenId.ToString());

            //    if (nodeSwapAddresses.Contains(targetAddress))
            //    {
            //        if (!interopTransfers.ContainsKey(evt.Log.TransactionHash))
            //        {
            //            interopTransfers.Add(evt.Log.TransactionHash, new List<InteropTransfer>());
            //        }

            //        string tokenURI = FetchTokenURI(evt.Log.Address, evt.Event.TokenId);

            //        interopTransfers[evt.Log.TransactionHash].Add
            //        (
            //            new InteropTransfer
            //            (
            //                EthereumWallet.EthereumPlatform,
            //                sourceAddress,
            //                DomainSettings.PlatformName,
            //                targetAddress,
            //                interopAddress,
            //                asset,
            //                tokenID,
            //                System.Text.Encoding.UTF8.GetBytes(tokenURI)
            //            )
            //        );
            //    }
            //}

            // ERC20
            var erc20_events = txr.DecodeAllEvents <TransferEventDTO>();

            foreach (var evt in erc20_events)
            {
                var asset = EthUtils.FindSymbolFromAsset(EthereumWallet.EthereumPlatform, nexus, evt.Log.Address);
                if (asset == null)
                {
                    logger.Warning($"Asset [{evt.Log.Address}] not supported");
                    continue;
                }

                var targetAddress = EthereumWallet.EncodeAddress(evt.Event.To);
                var sourceAddress = EthereumWallet.EncodeAddress(evt.Event.From);
                var amount        = PBigInteger.Parse(evt.Event.Value.ToString());

                if (nodeSwapAddresses.Contains(targetAddress))
                {
                    if (!interopTransfers.ContainsKey(evt.Log.TransactionHash))
                    {
                        interopTransfers.Add(evt.Log.TransactionHash, new List <InteropTransfer>());
                    }

                    interopTransfers[evt.Log.TransactionHash].Add
                    (
                        new InteropTransfer
                        (
                            EthereumWallet.EthereumPlatform,
                            sourceAddress,
                            DomainSettings.PlatformName,
                            targetAddress,
                            interopAddress,
                            asset,
                            amount
                        )
                    );
                }
            }

            if (tx.Value != null && tx.Value.Value > 0)
            {
                var targetAddress = EthereumWallet.EncodeAddress(tx.To);
                var sourceAddress = EthereumWallet.EncodeAddress(tx.From);

                if (nodeSwapAddresses.Contains(targetAddress))
                {
                    var amount = PBigInteger.Parse(tx.Value.ToString());

                    if (!interopTransfers.ContainsKey(tx.TransactionHash))
                    {
                        interopTransfers.Add(tx.TransactionHash, new List <InteropTransfer>());
                    }

                    interopTransfers[tx.TransactionHash].Add
                    (
                        new InteropTransfer
                        (
                            EthereumWallet.EthereumPlatform,
                            sourceAddress,
                            DomainSettings.PlatformName,
                            targetAddress,
                            interopAddress,
                            "ETH", // TODO use const
                            amount
                        )
                    );
                }
            }


            return(interopTransfers);
        }
Exemplo n.º 24
0
 /// <summary>
 /// Gets the ether balance of a given address.
 /// </summary>
 /// <param name="address"> The address to get the Ether balance for. </param>
 /// <param name="onBalanceReceived"> Callback to execute once the balance has been received, with the amount as a parameter. </param>
 public override void GetBalance(string address, Action <dynamic> onBalanceReceived)
 {
     EthUtils.GetEtherBalance(address).OnSuccess(onBalanceReceived);
 }
Exemplo n.º 25
0
        private static Dictionary <string, List <InteropTransfer> > GetInteropTransfers(Nexus nexus, Logger logger,
                                                                                        TransactionReceipt txr, EthAPI api, string swapAddress)
        {
            logger.Debug($"get interop transfers for tx {txr.TransactionHash}");
            var interopTransfers = new Dictionary <string, List <InteropTransfer> >();

            Nethereum.RPC.Eth.DTOs.Transaction tx = null;
            try
            {
                // tx to get the eth transfer if any
                tx = api.GetTransaction(txr.TransactionHash);
            }
            catch (Exception e)
            {
                logger.Error("Getting eth tx failed: " + e.Message);
            }

            logger.Debug("Transaction status: " + txr.Status.Value);
            // check if tx has failed
            if (txr.Status.Value == 0)
            {
                logger.Error($"tx {txr.TransactionHash} failed");
                return(interopTransfers);
            }

            var nodeSwapAddress = EthereumWallet.EncodeAddress(swapAddress);
            var events          = txr.DecodeAllEvents <TransferEventDTO>();
            var interopAddress  = ExtractInteropAddress(tx);

            // ERC20
            foreach (var evt in events)
            {
                var asset = EthUtils.FindSymbolFromAsset(nexus, evt.Log.Address);
                if (asset == null)
                {
                    logger.Warning($"Asset [{evt.Log.Address}] not supported");
                    continue;
                }

                var targetAddress = EthereumWallet.EncodeAddress(evt.Event.To);
                var sourceAddress = EthereumWallet.EncodeAddress(evt.Event.From);
                var amount        = PBigInteger.Parse(evt.Event.Value.ToString());

                if (targetAddress.Equals(nodeSwapAddress))
                {
                    if (!interopTransfers.ContainsKey(evt.Log.TransactionHash))
                    {
                        interopTransfers.Add(evt.Log.TransactionHash, new List <InteropTransfer>());
                    }

                    interopTransfers[evt.Log.TransactionHash].Add
                    (
                        new InteropTransfer
                        (
                            EthereumWallet.EthereumPlatform,
                            sourceAddress,
                            DomainSettings.PlatformName,
                            targetAddress,
                            interopAddress,
                            asset,
                            amount
                        )
                    );
                }
            }

            if (tx.Value != null && tx.Value.Value > 0)
            {
                var targetAddress = EthereumWallet.EncodeAddress(tx.To);
                var sourceAddress = EthereumWallet.EncodeAddress(tx.From);

                if (targetAddress.Equals(nodeSwapAddress))
                {
                    var amount = PBigInteger.Parse(tx.Value.ToString());

                    if (!interopTransfers.ContainsKey(tx.TransactionHash))
                    {
                        interopTransfers.Add(tx.TransactionHash, new List <InteropTransfer>());
                    }

                    interopTransfers[tx.TransactionHash].Add
                    (
                        new InteropTransfer
                        (
                            EthereumWallet.EthereumPlatform,
                            sourceAddress,
                            DomainSettings.PlatformName,
                            targetAddress,
                            interopAddress,
                            "ETH", // TODO use const
                            amount
                        )
                    );
                }
            }


            return(interopTransfers);
        }
Exemplo n.º 26
0
        private static Dictionary <string, List <InteropTransfer> > GetInteropTransfers(Nexus nexus, Logger logger,
                                                                                        TransactionReceipt txr, EthAPI api, string[] swapAddresses)
        {
            logger.Debug($"get interop transfers for tx {txr.TransactionHash}");
            var interopTransfers = new Dictionary <string, List <InteropTransfer> >();

            Nethereum.RPC.Eth.DTOs.Transaction tx = null;
            try
            {
                // tx to get the eth transfer if any
                tx = api.GetTransaction(txr.TransactionHash);
            }
            catch (Exception e)
            {
                logger.Error("Getting eth tx failed: " + e.Message);
            }

            Console.WriteLine("txr: " + txr.Status);
            logger.Debug("Transaction status: " + txr.Status.Value);
            // check if tx has failed
            if (txr.Status.Value == 0)
            {
                logger.Error($"tx {txr.TransactionHash} failed");
                return(interopTransfers);
            }

            foreach (var a in swapAddresses)
            {
                Console.WriteLine("swap address: " + a);
            }
            var nodeSwapAddresses = swapAddresses.Select(x => BSCWallet.EncodeAddress(x));
            var interopAddress    = ExtractInteropAddress(tx);

            Console.WriteLine("interop address: " + interopAddress);

            // ERC721 (NFT)
            // TODO currently this code block is mostly copypaste from BEP20 block, later make a single method for both...
            //var erc721_events = txr.DecodeAllEvents<Nethereum.StandardNonFungibleTokenERC721.ContractDefinition.TransferEventDTOBase>();
            //foreach (var evt in erc721_events)
            //{
            //    var asset = EthUtils.FindSymbolFromAsset(nexus, evt.Log.Address);
            //    if (asset == null)
            //    {
            //        logger.Warning($"Asset [{evt.Log.Address}] not supported");
            //        continue;
            //    }

            //    var targetAddress = BSCWallet.EncodeAddress(evt.Event.To);
            //    var sourceAddress = BSCWallet.EncodeAddress(evt.Event.From);
            //    var tokenID = PBigInteger.Parse(evt.Event.TokenId.ToString());

            //    if (nodeSwapAddresses.Contains(targetAddress))
            //    {
            //        if (!interopTransfers.ContainsKey(evt.Log.TransactionHash))
            //        {
            //            interopTransfers.Add(evt.Log.TransactionHash, new List<InteropTransfer>());
            //        }

            //        string tokenURI = FetchTokenURI(evt.Log.Address, evt.Event.TokenId);

            //        interopTransfers[evt.Log.TransactionHash].Add
            //        (
            //            new InteropTransfer
            //            (
            //                BSCWallet.BSCPlatform,
            //                sourceAddress,
            //                DomainSettings.PlatformName,
            //                targetAddress,
            //                interopAddress,
            //                asset,
            //                tokenID,
            //                System.Text.Encoding.UTF8.GetBytes(tokenURI)
            //            )
            //        );
            //    }
            //}

            // BEP20
            var bep20_events = txr.DecodeAllEvents <TransferEventDTO>();

            foreach (var evt in bep20_events)
            {
                var asset = EthUtils.FindSymbolFromAsset(BSCWallet.BSCPlatform, nexus, evt.Log.Address);
                if (asset == null)
                {
                    logger.Warning($"Asset [{evt.Log.Address}] not supported");
                    continue;
                }

                var targetAddress = BSCWallet.EncodeAddress(evt.Event.To);
                var sourceAddress = BSCWallet.EncodeAddress(evt.Event.From);
                var amount        = PBigInteger.Parse(evt.Event.Value.ToString());

                if (nodeSwapAddresses.Contains(targetAddress))
                {
                    if (!interopTransfers.ContainsKey(evt.Log.TransactionHash))
                    {
                        interopTransfers.Add(evt.Log.TransactionHash, new List <InteropTransfer>());
                    }

                    interopTransfers[evt.Log.TransactionHash].Add
                    (
                        new InteropTransfer
                        (
                            BSCWallet.BSCPlatform,
                            sourceAddress,
                            DomainSettings.PlatformName,
                            targetAddress,
                            interopAddress,
                            asset,
                            amount
                        )
                    );
                }
            }

            Console.WriteLine("value: " + tx.Value);
            Console.WriteLine("value: " + tx.Value.Value);
            if (tx.Value != null && tx.Value.Value > 0)
            {
                var targetAddress = BSCWallet.EncodeAddress(tx.To);
                var sourceAddress = BSCWallet.EncodeAddress(tx.From);

                foreach (var a in nodeSwapAddresses)
                {
                    Console.WriteLine("node swap address: " + a);
                }
                Console.WriteLine("target address: " + targetAddress);

                if (nodeSwapAddresses.Contains(targetAddress))
                {
                    var amount = PBigInteger.Parse(tx.Value.ToString());

                    if (!interopTransfers.ContainsKey(tx.TransactionHash))
                    {
                        interopTransfers.Add(tx.TransactionHash, new List <InteropTransfer>());
                    }

                    interopTransfers[tx.TransactionHash].Add
                    (
                        new InteropTransfer
                        (
                            BSCWallet.BSCPlatform,
                            sourceAddress,
                            DomainSettings.PlatformName,
                            targetAddress,
                            interopAddress,
                            "BSC", // TODO use const
                            amount
                        )
                    );
                }
            }


            return(interopTransfers);
        }