예제 #1
0
        public async Task <decimal> GetTokenBalance(string accountAddress)
        {
            var service = new StandardTokenService(Web3Client, RskTestnetRifAddress);
            var wei     = await service.BalanceOfQueryAsync(accountAddress).ConfigureAwait(false);

            return(Web3.Convert.FromWei(wei, 18));
        }
예제 #2
0
        void Initialize()
        {
            var client = new RpcClient(new Uri("https://rinkeby.infura.io/v3/78e8427cc8b54e50b5100fc28e30e059"));

            web3 = new Web3(DefaultAccount, client);
            standardTokenService = new StandardTokenService(web3, CONTRACT_ADDRESS);
        }
        /// <summary>
        /// Create a new instance of this class.
        /// </summary>
        public EthereumManager(string url = "http://localhost:8545/")
        {
            // Log this start
            Logger.ApplicationInstance.Info("Starting EthereumManager against " + url);

            // Create basic objects we'll need
            _web3    = new Web3(url);
            Accounts = new ObservableCollection <EthereumAccount>();

            // Store a handle to our contracts
            _icoContract  = _web3.Eth.GetContract(GetAbi("IcoPhaseManagement"), IcoContractAddress);
            _siftContract = _web3.Eth.GetContract(GetAbi("SmartInvestmentFundToken"), SiftContractAddress);
            _tokenService = new StandardTokenService(_web3, _siftContract.Address);

            // Start our thread
            _isAlive            = true;
            _networkCheckThread = new Thread(NetworkCheckThreadEntry)
            {
                IsBackground = true, Name = "Ethereum Manager"
            };
            _networkCheckThread.Start();
            _transactionConfirmationThread = new Thread(TransactionConfirmationThreadEntry)
            {
                IsBackground = true, Name = "Transaction Confirmation"
            };
            _transactionConfirmationThread.Start();
        }
        //Standard
        public static StandardTokenService GetMoralityStandardTokenBank(MoralityTokenSettings settings)
        {
            var web3 = new Web3(settings.InfuraAddress);
            var standardTokenService = new StandardTokenService(web3, settings.ContractAddress);

            return(standardTokenService);
        }
예제 #5
0
        public async void ShouldBeAbleTransferTokensUsingTheHdWallet()
        {
            var wallet  = new Wallet(Words, Password);
            var account = wallet.GetAccount(0);

            var web3 = new Web3.Web3(account, _ethereumClientIntegrationFixture.GetWeb3().Client);

            ulong totalSupply      = 1000000;
            var   contractByteCode =
                "0x6060604052341561000f57600080fd5b604051602080610711833981016040528080519150505b60018054600160a060020a03191633600160a060020a0390811691909117918290556000838155911681526002602052604090208190555b505b6106a28061006f6000396000f300606060405236156100a15763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100a6578063095ea7b31461013157806318160ddd1461016757806323b872dd1461018c578063313ce567146101c857806370a08231146101f15780638da5cb5b1461022257806395d89b4114610251578063a9059cbb146102dc578063dd62ed3e14610312575b600080fd5b34156100b157600080fd5b6100b9610349565b60405160208082528190810183818151815260200191508051906020019080838360005b838110156100f65780820151818401525b6020016100dd565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561013c57600080fd5b610153600160a060020a0360043516602435610380565b604051901515815260200160405180910390f35b341561017257600080fd5b61017a6103ed565b60405190815260200160405180910390f35b341561019757600080fd5b610153600160a060020a03600435811690602435166044356103f4565b604051901515815260200160405180910390f35b34156101d357600080fd5b6101db610510565b60405160ff909116815260200160405180910390f35b34156101fc57600080fd5b61017a600160a060020a0360043516610515565b60405190815260200160405180910390f35b341561022d57600080fd5b610235610534565b604051600160a060020a03909116815260200160405180910390f35b341561025c57600080fd5b6100b9610543565b60405160208082528190810183818151815260200191508051906020019080838360005b838110156100f65780820151818401525b6020016100dd565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156102e757600080fd5b610153600160a060020a036004351660243561057a565b604051901515815260200160405180910390f35b341561031d57600080fd5b61017a600160a060020a0360043581169060243516610649565b60405190815260200160405180910390f35b60408051908101604052601a81527f4578616d706c6520466978656420537570706c7920546f6b656e000000000000602082015281565b600160a060020a03338116600081815260036020908152604080832094871680845294909152808220859055909291907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259085905190815260200160405180910390a35060015b92915050565b6000545b90565b600160a060020a0383166000908152600260205260408120548290108015906104445750600160a060020a0380851660009081526003602090815260408083203390941683529290522054829010155b80156104505750600082115b80156104755750600160a060020a038316600090815260026020526040902054828101115b1561050457600160a060020a0380851660008181526002602081815260408084208054899003905560038252808420338716855282528084208054899003905594881680845291905290839020805486019055917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9085905190815260200160405180910390a3506001610508565b5060005b5b9392505050565b601281565b600160a060020a0381166000908152600260205260409020545b919050565b600154600160a060020a031681565b60408051908101604052600581527f4649584544000000000000000000000000000000000000000000000000000000602082015281565b600160a060020a0333166000908152600260205260408120548290108015906105a35750600082115b80156105c85750600160a060020a038316600090815260026020526040902054828101115b1561063a57600160a060020a033381166000818152600260205260408082208054879003905592861680825290839020805486019055917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9085905190815260200160405180910390a35060016103e7565b5060006103e7565b5b92915050565b600160a060020a038083166000908152600360209081526040808320938516835292905220545b929150505600a165627a7a72305820ec01add6c7f9d88976180c397e2a5b2e9f8fc1f95f5abb00e2a4c9dbf7bcfaf20029";
            var abi =
                "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"totalSupply\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"remaining\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"totalSupply\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"}]";

            var receipt = await web3.Eth.DeployContract.SendRequestAndWaitForReceiptAsync(abi, contractByteCode,
                                                                                          account.Address, new HexBigInteger(3000000), null, totalSupply);

            var standarErc20Service = new StandardTokenService(web3, receipt.ContractAddress);

            var pollingService = new TransactionReceiptPollingService(web3.TransactionManager);

            var transactionHash = await standarErc20Service.TransferRequestAsync(
                "0x98f5438cDE3F0Ff6E11aE47236e93481899d1C47", 10);

            var receiptSend = await pollingService.PollForReceiptAsync(transactionHash);

            var balance =
                await standarErc20Service.BalanceOfQueryAsync("0x98f5438cDE3F0Ff6E11aE47236e93481899d1C47");

            Assert.Equal(10, balance);
        }
예제 #6
0
        public async Task <decimal> GetERC20Balance(string address)
        {
            var standardToken = new StandardTokenService(_web3, NethereumConfig.CONTRACT_ADDRESS);
            // TODO: Test BalanceOfQueryAsync method
            var balance = await standardToken.BalanceOfQueryAsync(NethereumConfig.WALLET_B);

            return(Web3.Convert.FromWei(balance));
        }
예제 #7
0
        public static async Task PrepSendFundsToBuyerWalletForPo(Web3.Web3 fromWeb3, Buyer.Po po)
        {
            // Transfer required funds (tokens) from given Web3 acccount to buyer wallet given on po
            StandardTokenService sts = new StandardTokenService(fromWeb3, po.CurrencyAddress);
            var txTransfer           = await sts.TransferRequestAndWaitForReceiptAsync(po.BuyerWalletAddress, po.GetTotalCurrencyValue());

            txTransfer.Status.Value.Should().Be(1);
        }
        void Initialize()
        {
            //var client = new RpcClient(new Uri("http://192.168.12.154:8545"));//iOS
            //var client = new RpcClient(new Uri("http://10.0.2.2:8545"));//ANDROID
            var client = new RpcClient(new Uri("https://rinkeby.infura.io/O3CUsRfVYECJi12W8fk3"));

            web3 = new Web3(DefaultAccount, client);
            standardTokenService = new StandardTokenService(web3, CONTRACT_ADDRESS);
        }
예제 #9
0
        //RpcClient client;

        public AccountManager(NewWalletController controller)
        {
            this.controller      = controller;
            _web3ProviderService = new Web3ProviderService();
            var account = controller.GetPKey();

            web3            = _web3ProviderService.GetWeb3(account);
            DaiTokenService = new StandardTokenService(web3, CONTRACT_ADDRESS);
        }
예제 #10
0
        public async void ShouldRejectPoItemAndRefundBuyer()
        {
            // Prepare a new PO
            Buyer.Po poAsRequested = await CreateBuyerPoAsync(quoteId : GetRandomInt());

            var signature = poAsRequested.GetSignatureBytes(_contracts.Web3);

            // Test setup - transfer required funds from current Web3 acccount to wallet buyer
            StandardTokenService sts = new StandardTokenService(_contracts.Web3, poAsRequested.CurrencyAddress);
            var totalPoValue         = poAsRequested.GetTotalCurrencyValue();
            var txTransfer           = await sts.TransferRequestAndWaitForReceiptAsync(poAsRequested.BuyerWalletAddress, totalPoValue);

            txTransfer.Status.Value.Should().Be(1);

            // Create PO on-chain
            // NB: this approves token transfer from WALLET BUYER contract (NOT msg.sender == current web3 account) to FUNDING contract
            var txReceiptCreate = await _contracts.Deployment.BuyerWalletService.CreatePurchaseOrderRequestAndWaitForReceiptAsync(poAsRequested, signature);

            txReceiptCreate.Status.Value.Should().Be(1);
            _output.WriteLine($"... PO created ...");

            // Get the PO number that was assigned
            var logPoCreated = txReceiptCreate.DecodeAllEvents <PurchaseOrderCreatedLogEventDTO>().FirstOrDefault();

            logPoCreated.Should().NotBeNull();
            var poNumberAsBuilt = logPoCreated.Event.Po.PoNumber;

            // NB: Refunds go to the PO buyer wallet address (not the po buyer address from the PO header, which represents the user)
            // Balance of PO buyer address before refund
            var poBuyerWalletAddressBalanceBefore = await sts.BalanceOfQueryAsync(poAsRequested.BuyerWalletAddress);

            _output.WriteLine($"PO buyer wallet address balance before refund: {await poBuyerWalletAddressBalanceBefore.PrettifyAsync(sts)}");

            // Do the refund (achieved by marking the PO item as rejected)
            var txReceiptPoItemReject = await _contracts.Deployment.SellerAdminService.SetPoItemRejectedRequestAndWaitForReceiptAsync(
                poAsRequested.EShopId, poNumberAsBuilt, PO_ITEM_NUMBER);

            txReceiptPoItemReject.Status.Value.Should().Be(1);
            var poItemValue = poAsRequested.PoItems[PO_ITEM_INDEX].CurrencyValue;

            _output.WriteLine($"... PO item rejected with value {await poItemValue.PrettifyAsync(sts)} ...");

            // Check log exists for Escrow refund
            var logPoItemReject = txReceiptPoItemReject.DecodeAllEvents <PurchaseItemEscrowRefundedLogEventDTO>().FirstOrDefault();

            logPoItemReject.Should().NotBeNull();

            // Balance of PO buyer wallet address after PO item rejection
            var poBuyerWalletAddressBalanceAfter = await sts.BalanceOfQueryAsync(poAsRequested.BuyerWalletAddress);

            _output.WriteLine($"PO buyer wallet address balance after refund: {await poBuyerWalletAddressBalanceAfter.PrettifyAsync(sts)}");

            // Checks
            var diff = poBuyerWalletAddressBalanceAfter - poBuyerWalletAddressBalanceBefore;

            diff.Should().Be(poItemValue, "PO buyer wallet should have increased by value of the PO item");
        }
예제 #11
0
        /// <summary>
        /// Format a token value according to its decimals and symbol
        /// eg "5000000000000000" becomes "50,000 SYM"
        /// </summary>
        public static async Task <string> PrettifyAsync(this BigInteger value, StandardTokenService sts)
        {
            var symbol = await sts.SymbolQueryAsync();

            var decimals = await sts.DecimalsQueryAsync();

            var valueFactored = value / BigInteger.Pow(10, decimals);

            return($"{valueFactored.ToString("N0")} {symbol}");
        }
예제 #12
0
        public async Task <decimal> GetAccountTokenBalance(string accountAddress)
        {
            var web3 = new Web3(this.smartContractAddressConfiguration.NodeUrl);
            StandardTokenService token = new StandardTokenService(web3, smartContractAddressConfiguration.TokenAddress);
            var balanceWei             = await token.GetBalanceOfAsync <BigInteger>(accountAddress);

            var balanceEther = Web3.Convert.FromWei(balanceWei);

            return(balanceEther);
        }
예제 #13
0
        public static async Task RunWriteTest(Web3 web3)
        {
            var listTasks = 500;

            var taskItems = new List <int>();

            for (var i = 0; i < listTasks; i++)
            {
                taskItems.Add(i);
            }

            var numProcs             = Environment.ProcessorCount;
            var concurrencyLevel     = numProcs * 2;
            var concurrentDictionary = new ConcurrentDictionary <int, string>(concurrencyLevel, listTasks * 2);

            var sw = Stopwatch.StartNew();

            Console.WriteLine("Deployment contracts:" + listTasks);
            await taskItems.ParallelForEachAsync(async (item, state) =>

                                                 //foreach (var item in taskItems)
            {
                var txnx = await StandardTokenService.DeployContractAsync(web3,
                                                                          new EIP20Deployment()
                {
                    TokenName = "TST", InitialAmount = 1000, TokenSymbol = "TST"
                });

                concurrentDictionary.TryAdd(item, txnx);
            }
                                                 , maxDegreeOfParalellism : 10);

            sw.Stop();
            Console.WriteLine("Done sending transactions in " + sw.ElapsedMilliseconds + "ms");

            Console.WriteLine();
            Console.WriteLine("Polling receipts....");

            var pollService = new TransactionReceiptPollingService(web3.TransactionManager);

            for (var i = 0; i < listTasks; i++)
            {
                string txn = null;
                concurrentDictionary.TryGetValue(i, out txn);
                var receipt = await pollService.PollForReceiptAsync(txn);

                if (i == listTasks - 1)
                {
                    Console.WriteLine("Last contract address:");
                    Console.WriteLine(receipt.ContractAddress);
                }
            }

            Console.WriteLine();
        }
        public static async Task <decimal> GetTokenBalance(string address)
        {
            var web3         = new Web3(ConfigurationManager.GetString("NetworkProvider"));
            var tokenAddress = ConfigurationManager.GetString("TokenAddress");

            var service = new StandardTokenService(web3, tokenAddress);

            BigInteger wei = await service.BalanceOfQueryAsync(address);

            var balance = Web3.Convert.FromWei(wei);

            return(balance);
        }
예제 #15
0
        public WonkaEthEIP20TransferTrigger(Web3 poWeb3, EIP20Deployment moDeployData, string psContractAddress, string psReceiverAddress, long pnTransferAmount, CancellationTokenSource poCancelToken = null)
            : base(poWeb3, psContractAddress, poCancelToken)
        {
            mnTotalSupply = Convert.ToInt64(moDeployData.InitialAmount);
            mnTransferAmt = pnTransferAmount;

            msTokenName       = moDeployData.TokenName;
            msTokenSymbol     = moDeployData.TokenSymbol;
            msReceiverAddress = psReceiverAddress;

            moEIP20Service = new StandardTokenService(poWeb3, psContractAddress);
            moContract     = moEIP20Service.ContractHandler;
        }
예제 #16
0
 private static void Initialize()
 {
     // set up magic numbers
     tokenAddress = SecretsController.SecretKey("address");
     abi          = SecretsController.SecretKey("abi");
     url          = SecretsController.SecretKey("infura_url");
     // account 1
     privatekey = SecretsController.SecretKey("privatekey");
     // account 2
     // privatekey = "95d16070fca17cb283db778650817b58b42c3ce8c164cd038037ba77bbad80f7";
     account = new Account(privatekey);
     web3    = new Web3(account, url);
     goToken = new StandardTokenService(web3, tokenAddress);
     init    = true;
 }
        public async Task Run()
        {
            //The quorum account
            var coinbaseNode1           = "0x83e0ebe69d8758f9450425fa39ef08692e55340d";
            var uriWithAccessTokenNode1 = "https://juanquorum1.blockchain.azure.com:3200/nNkcS8DyDSCLIC9oAoCw1orS";

            //Initialising Web3Quorum with a custom QuorumAccount
            var web3Private = new Web3Quorum(new QuorumAccount(coinbaseNode1), uriWithAccessTokenNode1);

            //Set the nodes to work in private mode for this web3 instance
            web3Private.SetPrivateRequestParameters(new[] { "LHTjKEqQPy6gbo4r9ouj8ztfbB+F7kWd9vosSmeQcEw=", "sXVr5ENaJeqAA8eTKm74f6epYTMcbsl8Ovp+Y8Q3dzA=" });

            //Unlock account to enable access
            var unlocked = await web3Private.Personal.UnlockAccount.SendRequestAsync(coinbaseNode1, "P455word1?1234", 30);

            //Deploying new ERC20 smart contract using the Standard token library service
            var erc20service = await StandardTokenService.DeployContractAndGetServiceAsync(web3Private, new EIP20Deployment()
            {
                InitialAmount = BigInteger.Parse("1000000000000000000000000"),
                DecimalUnits  = 18,
                TokenName     = "TEST",
                TokenSymbol   = "TST",
            });

            //After deploying the smart contract the owner "coinbaseNode1" will have a balance of 1000000000000000000000000
            var balanceOwnerAccount = await erc20service.BalanceOfQueryAsync(coinbaseNode1);

            //Transfering 10000
            var transferReceipt = await erc20service.TransferRequestAndWaitForReceiptAsync("0xc45ed03295fdb5667206c4c18f88b41b4f035358", 10000);

            //Validate that we get the new balance
            var balanceOwnerAfterTransfer = await erc20service.BalanceOfQueryAsync(coinbaseNode1);

            var balanceReceiverAccount = await erc20service.BalanceOfQueryAsync("0xc45ed03295fdb5667206c4c18f88b41b4f035358");

            //Create a web3 instance in a different node not included in the Private list
            var web3NoAccess = new Web3("https://juanquorum3-juanquorum1.blockchain.azure.com:3200/ekgKWCEhxcq6d_HH3N10g9W0");

            //initialising a new StardandTokenService with the same contract address
            var erc20noAccess = new StandardTokenService(web3NoAccess, erc20service.ContractHandler.ContractAddress);
            //validate we don't receive any amount
            var balanceOwnerAccountNoAccess = await erc20noAccess.BalanceOfQueryAsync(coinbaseNode1);
        }
예제 #18
0
        static async Task deployERC20()
        {
            var _account = new Account("fbde582d0deb10b30d0c1be8752650a9f4fc12c705610cb754b7ae3b0a2d4aa7", 5777);
            // var account = new Account(privatekey, Nethereum.Signer.Chain.MainNet);
            var _web3 = new Web3(_account, "http://127.0.0.1:7545");

            _web3.TransactionManager.UseLegacyAsDefault = true;
            ulong totalSupply        = 2000000;
            var   deploymentContract = new EIP20Deployment()
            {
                InitialAmount = totalSupply,
                TokenName     = "TestToken",
                TokenSymbol   = "TT"
            };

            var tokenService = await StandardTokenService.DeployContractAndWaitForReceiptAsync(_web3, deploymentContract);

            Console.WriteLine("Contract Address: " + tokenService.ContractAddress);
        }
예제 #19
0
        public WonkaEthEIP20TransferTrigger(Web3 poWeb3, long pnTotalSupply, string psTokenName, string psTokenSymbol, string psReceiverAddress, long pnTransferAmount, CancellationTokenSource poCancelToken = null)
            : base(poWeb3, poCancelToken)
        {
            mnTotalSupply = pnTotalSupply;
            mnTransferAmt = pnTransferAmount;

            msTokenName       = psTokenName;
            msTokenSymbol     = psTokenSymbol;
            msReceiverAddress = psReceiverAddress;

            var deploymentContract = new EIP20Deployment()
            {
                InitialAmount = new System.Numerics.BigInteger(pnTotalSupply),
                TokenName     = psTokenName,
                TokenSymbol   = psTokenSymbol
            };

            moEIP20Service = StandardTokenService.DeployContractAndGetServiceAsync(poWeb3, deploymentContract).Result;
            moContract     = moEIP20Service.ContractHandler;
        }
예제 #20
0
        static async Task TrasferFromDemo()
        {
            var _TokenAddress    = "0x4e3c5117ed03c6e3a47f4414506f2f4723ce79e1";
            var _account1Address = "0x4438083Ef903ACD146D3f705d790f9188d5B11Ac";
            var _account1        = new Account("fbde582d0deb10b30d0c1be8752650a9f4fc12c705610cb754b7ae3b0a2d4aa7");
            var _web3            = new Web3(_account1, "http://127.0.0.1:7545", 5777);

            _web3.TransactionManager.UseLegacyAsDefault = true;

            var _tokenService = new StandardTokenService(_web3, _TokenAddress);

            var ownerBalance = await _tokenService.BalanceOfQueryAsync(_account1Address);

            Console.WriteLine("Account1's Balance : " + ownerBalance);

            var _account2Address = "0x43c020cA68FfaA09AFc1674A78047C1b40CBb60E";
            var _account3Address = "0x86Ac1893ff1Ef07Ec709C6b81516bc25eB3FF7aE";

            var approveTransactionReceipt = await _tokenService.ApproveRequestAndWaitForReceiptAsync(_account3Address, 5000);

            var allowanceAmount = await _tokenService.AllowanceQueryAsync(_account1Address, _account3Address);

            Console.WriteLine("allowanceAmount : " + allowanceAmount);


            var _account3 = new Account("f4787bddd02d87d671697809885a3b36f902f4545a77556840b6b52a7dac8c5a");

            _web3 = new Web3(_account3, "http://127.0.0.1:7545");

            var _tokenServiceFrom = new StandardTokenService(_web3, _TokenAddress);

            var TransferFromReceipt = await _tokenServiceFrom.TransferFromRequestAndWaitForReceiptAsync(_account1Address, _account2Address, 2000);

            Console.WriteLine("================ TransferFrom =====================");
            ownerBalance = await _tokenServiceFrom.BalanceOfQueryAsync(_account1Address);

            Console.WriteLine("Account1's Balance : " + ownerBalance);
            allowanceAmount = await _tokenServiceFrom.AllowanceQueryAsync(_account1Address, _account3Address);

            Console.WriteLine("allowanceAmount : " + allowanceAmount);
        }
예제 #21
0
        static async Task TransferToken()
        {
            var _TokenAddress = "0x4e3c5117ed03c6e3a47f4414506f2f4723ce79e1";
            var _owner        = "0x4438083Ef903ACD146D3f705d790f9188d5B11Ac";
            var _account      = new Account("fbde582d0deb10b30d0c1be8752650a9f4fc12c705610cb754b7ae3b0a2d4aa7", 5777);
            // var account = new Account(privatekey, Nethereum.Signer.Chain.MainNet);
            var _web3 = new Web3(_account, "http://127.0.0.1:7545");

            _web3.TransactionManager.UseLegacyAsDefault = true;

            var _tokenService = new StandardTokenService(_web3, _TokenAddress);

            var ownerBalance = await _tokenService.BalanceOfQueryAsync(_owner);

            Console.WriteLine("Balance : " + ownerBalance);

            var _account2 = "0x43c020cA68FfaA09AFc1674A78047C1b40CBb60E";

            var transferReceipt = await _tokenService.TransferRequestAndWaitForReceiptAsync(_account2, 1500);

            ownerBalance = await _tokenService.BalanceOfQueryAsync(_owner);

            Console.WriteLine("Balance : " + ownerBalance);

            var account2Balance = await _tokenService.BalanceOfQueryAsync(_account2);

            Console.WriteLine("Account2's Balance : " + account2Balance);

            var _transferEvent = _tokenService.GetTransferEvent();

            var _allTransferFilter = await _transferEvent.CreateFilterAsync(new BlockParameter(transferReceipt.BlockNumber));

            var eventLogsAll = await _transferEvent.GetAllChanges(_allTransferFilter);

            var transferLog = eventLogsAll.First();

            Console.WriteLine("TxID : " + transferLog.Log.TransactionHash);
            Console.WriteLine("BlockNumber : " + transferLog.Log.BlockNumber.Value);
            Console.WriteLine("To : " + transferLog.Event.To.ToLower());
            Console.WriteLine("Value : " + transferLog.Event.Value);
        }
        public async Task RunAsync()
        {
            // Ethereum network to connect to
            var ethereumNetworkUrl = "https://mainnet.infura.io/";

            // ERC20 token called Gemini Dollar GUSD deployed on MainNet here:
            // https://etherscan.io/address/0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd#contracts
            var erc20TokenContractAddress = "0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd";
            var accountWithSomeTokens     = "0xdc24703f9210d377951819f2cc1dcc4061b88a67";

            // Setup web3 and token service, to allow us to interact with ERC20 contract
            var web3         = new Web3(ethereumNetworkUrl);
            var tokenService = new StandardTokenService(web3, erc20TokenContractAddress);

            // Check an address balance
            var symbol = await tokenService.SymbolQueryAsync();

            var tokens = await tokenService.BalanceOfQueryAsync(accountWithSomeTokens);

            System.Console.WriteLine($"Address: {accountWithSomeTokens} holds: {tokens} {symbol}");
            System.Console.ReadLine();
        }
예제 #23
0
        static async Task DisplayTokenInfo()
        {
            var _TokenAddress = "0x4e3c5117ed03c6e3a47f4414506f2f4723ce79e1";
            var _account      = new Account("fbde582d0deb10b30d0c1be8752650a9f4fc12c705610cb754b7ae3b0a2d4aa7", 5777);
            // var account = new Account(privatekey, Nethereum.Signer.Chain.MainNet);
            var _web3 = new Web3(_account, "http://127.0.0.1:7545");

            _web3.TransactionManager.UseLegacyAsDefault = true;

            var _tokenService = new StandardTokenService(_web3, _TokenAddress);

            var _totalSupply = await _tokenService.TotalSupplyQueryAsync();

            Console.WriteLine("TotalSupply : " + _totalSupply);

            var _tokenName = await _tokenService.NameQueryAsync();

            Console.WriteLine("TokenName : " + _tokenName);

            var _tokenSymbol = await _tokenService.SymbolQueryAsync();

            Console.WriteLine("TokenSymbol : " + _tokenSymbol);
        }
예제 #24
0
        public TokenPayment(EthPaymentsConfig config)
        {
            logger.Info($"Mode: token");
            logger.Info($"Loaded wallets: {config.Wallets.Count()}");
            logger.Info($"Geth address: {config.GethAddress}");
            logger.Info($"Callback url: {config.CallbackUrl}");
            logger.Info($"{nameof(config.TokenContractAddress)}: {config.TokenContractAddress}");
            logger.Info($"{nameof(config.TokenCurrency)}: {config.TokenCurrency}");

            wallets     = new HashSet <string>(config.Wallets);
            web3        = new Web3Geth(config.GethAddress);
            callbackUrl = config.CallbackUrl;

            this.config = config;

            notificationSender = new NotificationSender(callbackUrl, config.ApiKey, config.ApiSecret);


            if (!string.IsNullOrEmpty(config.TokenContractAddress))
            {
                var tokenService = new StandardTokenService(web3, config.TokenContractAddress);
                transfersEvent = tokenService.GetTransferEvent();
            }
        }
예제 #25
0
        public async void Test()
        {
            var contractByteCode =
                "0x6060604052341561000f57600080fd5b604051602080610711833981016040528080519150505b60018054600160a060020a03191633600160a060020a0390811691909117918290556000838155911681526002602052604090208190555b505b6106a28061006f6000396000f300606060405236156100a15763ffffffff7c010000000000000000000000000000000000000000000000000000000060003504166306fdde0381146100a6578063095ea7b31461013157806318160ddd1461016757806323b872dd1461018c578063313ce567146101c857806370a08231146101f15780638da5cb5b1461022257806395d89b4114610251578063a9059cbb146102dc578063dd62ed3e14610312575b600080fd5b34156100b157600080fd5b6100b9610349565b60405160208082528190810183818151815260200191508051906020019080838360005b838110156100f65780820151818401525b6020016100dd565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b341561013c57600080fd5b610153600160a060020a0360043516602435610380565b604051901515815260200160405180910390f35b341561017257600080fd5b61017a6103ed565b60405190815260200160405180910390f35b341561019757600080fd5b610153600160a060020a03600435811690602435166044356103f4565b604051901515815260200160405180910390f35b34156101d357600080fd5b6101db610510565b60405160ff909116815260200160405180910390f35b34156101fc57600080fd5b61017a600160a060020a0360043516610515565b60405190815260200160405180910390f35b341561022d57600080fd5b610235610534565b604051600160a060020a03909116815260200160405180910390f35b341561025c57600080fd5b6100b9610543565b60405160208082528190810183818151815260200191508051906020019080838360005b838110156100f65780820151818401525b6020016100dd565b50505050905090810190601f1680156101235780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34156102e757600080fd5b610153600160a060020a036004351660243561057a565b604051901515815260200160405180910390f35b341561031d57600080fd5b61017a600160a060020a0360043581169060243516610649565b60405190815260200160405180910390f35b60408051908101604052601a81527f4578616d706c6520466978656420537570706c7920546f6b656e000000000000602082015281565b600160a060020a03338116600081815260036020908152604080832094871680845294909152808220859055909291907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259085905190815260200160405180910390a35060015b92915050565b6000545b90565b600160a060020a0383166000908152600260205260408120548290108015906104445750600160a060020a0380851660009081526003602090815260408083203390941683529290522054829010155b80156104505750600082115b80156104755750600160a060020a038316600090815260026020526040902054828101115b1561050457600160a060020a0380851660008181526002602081815260408084208054899003905560038252808420338716855282528084208054899003905594881680845291905290839020805486019055917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9085905190815260200160405180910390a3506001610508565b5060005b5b9392505050565b601281565b600160a060020a0381166000908152600260205260409020545b919050565b600154600160a060020a031681565b60408051908101604052600581527f4649584544000000000000000000000000000000000000000000000000000000602082015281565b600160a060020a0333166000908152600260205260408120548290108015906105a35750600082115b80156105c85750600160a060020a038316600090815260026020526040902054828101115b1561063a57600160a060020a033381166000818152600260205260408082208054879003905592861680825290839020805486019055917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9085905190815260200160405180910390a35060016103e7565b5060006103e7565b5b92915050565b600160a060020a038083166000908152600360209081526040808320938516835292905220545b929150505600a165627a7a72305820ec01add6c7f9d88976180c397e2a5b2e9f8fc1f95f5abb00e2a4c9dbf7bcfaf20029";
            var abi =
                "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"totalSupply\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"owner\",\"outputs\":[{\"name\":\"\",\"type\":\"address\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_amount\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"remaining\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"totalSupply\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"constructor\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"}]";
            var addressOwner = "0x12890d2cce102216644c59dae5baed380d84830c";
            var pass         = "******";
            var web3         = new Web3Geth(new ManagedAccount(addressOwner, pass), ClientFactory.GetClient());

            try
            {
                var   eth          = web3.Eth;
                var   transactions = eth.Transactions;
                ulong totalSupply  = 1000000;


                var newAddress = await web3.Personal.NewAccount.SendRequestAsync(pass);

                Assert.NotNull(newAddress);
                Console.WriteLine(newAddress);
                var gas = await eth.DeployContract.EstimateGasAsync(abi, contractByteCode, addressOwner, totalSupply);

                var receipt =
                    await
                    eth.DeployContract.SendRequestAndWaitForReceiptAsync(abi, contractByteCode, addressOwner,
                                                                         new HexBigInteger(3000000), null, totalSupply);

                var tokenService = new StandardTokenService(web3, receipt.ContractAddress);

                var transfersEvent = tokenService.GetTransferEvent();


                var totalSupplyDeployed = await tokenService.GetTotalSupplyAsync <ulong>();

                Assert.Equal(totalSupply, totalSupplyDeployed);

                var ownerBalance = await tokenService.GetBalanceOfAsync <ulong>(addressOwner);

                Assert.Equal(totalSupply, ownerBalance);

                var transactionHash = await tokenService.TransferAsync(addressOwner, newAddress, 1000, new HexBigInteger(900000));

                var transferReceipt = await GetTransactionReceiptAsync(transactions, transactionHash);

                ownerBalance = await tokenService.GetBalanceOfAsync <ulong>(addressOwner);

                Assert.Equal(totalSupply - 1000, ownerBalance);

                var newAddressBalance = await tokenService.GetBalanceOfAsync <ulong>(newAddress);

                Assert.Equal((ulong)1000, newAddressBalance);

                var allTransfersFilter = await transfersEvent.CreateFilterAsync(new BlockParameter(transferReceipt.BlockNumber));

                var eventLogsAll = await transfersEvent.GetAllChanges <Transfer>(allTransfersFilter);

                Assert.Equal(1, eventLogsAll.Count);
                var transferLog = eventLogsAll.First();
                Assert.Equal(transferLog.Log.TransactionIndex.HexValue, transferReceipt.TransactionIndex.HexValue);
                Assert.Equal(transferLog.Log.BlockNumber.HexValue, transferReceipt.BlockNumber.HexValue);
                Assert.Equal(transferLog.Event.AddressTo, newAddress);
                Assert.Equal(transferLog.Event.Value, (ulong)1000);
            }
            finally
            {
                // var result = await web3.Personal.LockAccount.SendRequestAsync(addressOwner);
                // Assert.True(result, "Account should be locked");
            }
        }
예제 #26
0
        public async void Test()
        {
            var addressOwner = EthereumClientIntegrationFixture.AccountAddress;
            var web3         = _ethereumClientIntegrationFixture.GetWeb3();

            ulong totalSupply = 1000000;
            var   newAddress  = "0x12890d2cce102216644c59daE5baed380d84830e";

            var deploymentContract = new EIP20Deployment()
            {
                InitialAmount = totalSupply,
                TokenName     = "TestToken",
                TokenSymbol   = "TST"
            };

            var tokenService = await StandardTokenService.DeployContractAndGetServiceAsync(web3, deploymentContract);

            var transfersEvent = tokenService.GetTransferEvent();

            var totalSupplyDeployed = await tokenService.TotalSupplyQueryAsync();

            Assert.Equal(totalSupply, totalSupplyDeployed);

            var tokenName = await tokenService.NameQueryAsync();

            Assert.Equal("TestToken", tokenName);

            var tokenSymbol = await tokenService.SymbolQueryAsync();

            Assert.Equal("TST", tokenSymbol);

            var ownerBalance = await tokenService.BalanceOfQueryAsync(addressOwner);

            Assert.Equal(totalSupply, ownerBalance);

            var transferReceipt =
                await tokenService.TransferRequestAndWaitForReceiptAsync(newAddress, 1000);

            ownerBalance = await tokenService.BalanceOfQueryAsync(addressOwner);

            Assert.Equal(totalSupply - 1000, ownerBalance);

            var newAddressBalance = await tokenService.BalanceOfQueryAsync(newAddress);

            Assert.Equal(1000, newAddressBalance);

            var allTransfersFilter =
                await transfersEvent.CreateFilterAsync(new BlockParameter(transferReceipt.BlockNumber));

            var eventLogsAll = await transfersEvent.GetAllChangesAsync(allTransfersFilter);

            Assert.Single(eventLogsAll);
            var transferLog = eventLogsAll.First();

            Assert.Equal(transferLog.Log.TransactionIndex.HexValue, transferReceipt.TransactionIndex.HexValue);
            Assert.Equal(transferLog.Log.BlockNumber.HexValue, transferReceipt.BlockNumber.HexValue);
            Assert.Equal(transferLog.Event.To.ToLower(), newAddress.ToLower());
            Assert.Equal(transferLog.Event.Value, (ulong)1000);

            var approveTransactionReceipt = await tokenService.ApproveRequestAndWaitForReceiptAsync(newAddress, 1000);

            var allowanceAmount = await tokenService.AllowanceQueryAsync(addressOwner, newAddress);

            Assert.Equal(1000, allowanceAmount);
        }
예제 #27
0
        public async void Test()
        {
           
                var contractByteCode =
                    "0x60606040526040516020806106f5833981016040528080519060200190919050505b80600160005060003373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005081905550806000600050819055505b506106868061006f6000396000f360606040523615610074576000357c010000000000000000000000000000000000000000000000000000000090048063095ea7b31461008157806318160ddd146100b657806323b872dd146100d957806370a0823114610117578063a9059cbb14610143578063dd62ed3e1461017857610074565b61007f5b610002565b565b005b6100a060048080359060200190919080359060200190919050506101ad565b6040518082815260200191505060405180910390f35b6100c36004805050610674565b6040518082815260200191505060405180910390f35b6101016004808035906020019091908035906020019091908035906020019091905050610281565b6040518082815260200191505060405180910390f35b61012d600480803590602001909190505061048d565b6040518082815260200191505060405180910390f35b61016260048080359060200190919080359060200190919050506104cb565b6040518082815260200191505060405180910390f35b610197600480803590602001909190803590602001909190505061060b565b6040518082815260200191505060405180910390f35b600081600260005060003373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060008573ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905061027b565b92915050565b600081600160005060008673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050541015801561031b575081600260005060008673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060003373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000505410155b80156103275750600082115b1561047c5781600160005060008573ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828282505401925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a381600160005060008673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282825054039250508190555081600260005060008673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060003373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828282505403925050819055506001905061048656610485565b60009050610486565b5b9392505050565b6000600160005060008373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000505490506104c6565b919050565b600081600160005060003373ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050541015801561050c5750600082115b156105fb5781600160005060003373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282825054039250508190555081600160005060008573ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828282505401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905061060556610604565b60009050610605565b5b92915050565b6000600260005060008473ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060008373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005054905061066e565b92915050565b60006000600050549050610683565b9056";
                var abi =
                    @"[{""constant"":false,""inputs"":[{""name"":""_spender"",""type"":""address""},{""name"":""_value"",""type"":""uint256""}],""name"":""approve"",""outputs"":[{""name"":""success"",""type"":""bool""}],""type"":""function""},{""constant"":true,""inputs"":[],""name"":""totalSupply"",""outputs"":[{""name"":""supply"",""type"":""uint256""}],""type"":""function""},{""constant"":false,""inputs"":[{""name"":""_from"",""type"":""address""},{""name"":""_to"",""type"":""address""},{""name"":""_value"",""type"":""uint256""}],""name"":""transferFrom"",""outputs"":[{""name"":""success"",""type"":""bool""}],""type"":""function""},{""constant"":true,""inputs"":[{""name"":""_owner"",""type"":""address""}],""name"":""balanceOf"",""outputs"":[{""name"":""balance"",""type"":""uint256""}],""type"":""function""},{""constant"":false,""inputs"":[{""name"":""_to"",""type"":""address""},{""name"":""_value"",""type"":""uint256""}],""name"":""transfer"",""outputs"":[{""name"":""success"",""type"":""bool""}],""type"":""function""},{""constant"":true,""inputs"":[{""name"":""_owner"",""type"":""address""},{""name"":""_spender"",""type"":""address""}],""name"":""allowance"",""outputs"":[{""name"":""remaining"",""type"":""uint256""}],""type"":""function""},{""inputs"":[{""name"":""_initialAmount"",""type"":""uint256""}],""type"":""constructor""},{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""_from"",""type"":""address""},{""indexed"":true,""name"":""_to"",""type"":""address""},{""indexed"":false,""name"":""_value"",""type"":""uint256""}],""name"":""Transfer"",""type"":""event""},{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""_owner"",""type"":""address""},{""indexed"":true,""name"":""_spender"",""type"":""address""},{""indexed"":false,""name"":""_value"",""type"":""uint256""}],""name"":""Approval"",""type"":""event""}]";
                var addressOwner = "0x12890d2cce102216644c59dae5baed380d84830c";

                var web3 = new Nethereum.Web3.Web3(ClientFactory.GetClient());
            try
            {
                var eth = web3.Eth;
                var transactions = eth.Transactions;
                ulong totalSupply = 1000000;

                var pass = "******";
                var result =
                    await web3.Personal.UnlockAccount.SendRequestAsync(addressOwner, pass, new HexBigInteger(600));
                Assert.True(result, "Account should be unlocked");
                var newAddress = await web3.Personal.NewAccount.SendRequestAsync(pass);

                Assert.NotNull(newAddress);
                Console.WriteLine(newAddress);

                var transactionHash =
                    await
                        eth.DeployContract.SendRequestAsync(abi, contractByteCode, addressOwner,
                            new HexBigInteger(900000), totalSupply);

                result = await web3.Miner.Start.SendRequestAsync();
                Assert.True(result, "Mining should have started");

                //get the contract address 
                var receipt = await GetTransactionReceiptAsync(transactions, transactionHash);

                var code = await web3.Eth.GetCode.SendRequestAsync(receipt.ContractAddress);

                if (String.IsNullOrEmpty(code))
                {
                    throw new Exception(
                        "Code was not deployed correctly, verify bytecode or enough gas was uto deploy the contract");
                }

                var tokenService = new StandardTokenService(web3, receipt.ContractAddress);

                var transfersEvent = tokenService.GetTransferEvent();
              

                var totalSupplyDeployed = await tokenService.GetTotalSupplyAsync<ulong>();
                Assert.Equal(totalSupply, totalSupplyDeployed);

                var ownerBalance = await tokenService.GetBalanceOfAsync<ulong>(addressOwner);
                Assert.Equal(totalSupply, ownerBalance);

               transactionHash = await tokenService.TransferAsync(addressOwner, newAddress, 1000);
              
               var transferReceipt = await GetTransactionReceiptAsync(transactions, transactionHash);

                ownerBalance = await tokenService.GetBalanceOfAsync<ulong>(addressOwner);
                Assert.Equal(totalSupply - 1000, ownerBalance);

                var newAddressBalance = await tokenService.GetBalanceOfAsync<ulong>(newAddress);
                Assert.Equal((ulong) 1000, newAddressBalance);

                var allTransfersFilter = await transfersEvent.CreateFilterAsync(new BlockParameter(transferReceipt.BlockNumber));
                var eventLogsAll = await transfersEvent.GetAllChanges<Transfer>(allTransfersFilter);
                Assert.Equal(1, eventLogsAll.Count);
                var transferLog = eventLogsAll.First();
                Assert.Equal(transferLog.Log.TransactionIndex.HexValue, transferReceipt.TransactionIndex.HexValue);
                Assert.Equal(transferLog.Log.BlockNumber.HexValue, transferReceipt.BlockNumber.HexValue);
                Assert.Equal(transferLog.Event.AddressTo, newAddress);
                Assert.Equal(transferLog.Event.Value, (ulong)1000);

            }
            finally
            {
                var result = await web3.Miner.Stop.SendRequestAsync();
                Assert.True(result, "Mining should have stop");
                result = await web3.Personal.LockAccount.SendRequestAsync(addressOwner);
                Assert.True(result, "Account should be locked");
            }
           
        }
예제 #28
0
        private async Task <string> WriteOHLC(TradeEvent ev, DateTimeOffset?timestamp)
        {
            try
            {
                string     tokenSymbol;
                decimal    tokenAmount, ethAmount, price = 0;
                TokenModel token;
                if (ev.TokenGet == NullAddress)
                {
                    token = await _context.Token.FirstOrDefaultAsync(x => x.Token == ev.TokenGive);

                    tokenSymbol = token.Symbol;
                    var d = await _cache.GetOrCreateAsync(ev.TokenGive, entry =>
                    {
                        entry.SlidingExpiration = TimeSpan.FromSeconds(5);
                        var tokenContract       = new StandardTokenService(_nethereumClient, ev.TokenGive);
                        var decimals            = tokenContract.DecimalsQueryAsync(new DecimalsFunction()).Result;
                        return(Task.FromResult((decimal)Math.Pow(10, decimals)));
                    });

                    tokenAmount = (decimal)BigInteger.DivRem(ev.AmountGive, new BigInteger(d), out var remainder);
                    if (remainder > 0)
                    {
                        tokenAmount += (decimal)remainder / d;
                    }

                    ethAmount = UnitConversion.Convert.FromWei(ev.AmountGet, UnitConversion.EthUnit.Ether);
                    if (tokenAmount > 0)
                    {
                        price = ethAmount / tokenAmount;
                    }
                }
                else
                {
                    token = await _context.Token.FirstOrDefaultAsync(x => x.Token == ev.TokenGet);

                    tokenSymbol = token.Symbol;
                    var d = await _cache.GetOrCreateAsync(ev.TokenGet, entry =>
                    {
                        entry.SlidingExpiration = TimeSpan.FromSeconds(5);
                        var tokenContract       = new StandardTokenService(_nethereumClient, ev.TokenGive);
                        var decimals            = tokenContract.DecimalsQueryAsync(new DecimalsFunction()).Result;
                        return(Task.FromResult((decimal)Math.Pow(10, decimals)));
                    });

                    tokenAmount = (decimal)BigInteger.DivRem(ev.AmountGet, new BigInteger(d), out var remainder);
                    if (remainder > 0)
                    {
                        tokenAmount += (decimal)remainder / d;
                    }

                    ethAmount = UnitConversion.Convert.FromWei(ev.AmountGive, UnitConversion.EthUnit.Ether);
                    if (tokenAmount > 0)
                    {
                        price = ethAmount / tokenAmount;
                    }
                }
                _ohclService.WriteOHLC(price, tokenAmount, token.Symbol, timestamp.Value.UtcDateTime);
                return(tokenSymbol);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
예제 #29
0
        public async void Test()
        {
            var contractByteCode =
                "0x60606040526040516020806106f5833981016040528080519060200190919050505b80600160005060003373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005081905550806000600050819055505b506106868061006f6000396000f360606040523615610074576000357c010000000000000000000000000000000000000000000000000000000090048063095ea7b31461008157806318160ddd146100b657806323b872dd146100d957806370a0823114610117578063a9059cbb14610143578063dd62ed3e1461017857610074565b61007f5b610002565b565b005b6100a060048080359060200190919080359060200190919050506101ad565b6040518082815260200191505060405180910390f35b6100c36004805050610674565b6040518082815260200191505060405180910390f35b6101016004808035906020019091908035906020019091908035906020019091905050610281565b6040518082815260200191505060405180910390f35b61012d600480803590602001909190505061048d565b6040518082815260200191505060405180910390f35b61016260048080359060200190919080359060200190919050506104cb565b6040518082815260200191505060405180910390f35b610197600480803590602001909190803590602001909190505061060b565b6040518082815260200191505060405180910390f35b600081600260005060003373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060008573ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040518082815260200191505060405180910390a36001905061027b565b92915050565b600081600160005060008673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050541015801561031b575081600260005060008673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060003373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000505410155b80156103275750600082115b1561047c5781600160005060008573ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828282505401925050819055508273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a381600160005060008673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282825054039250508190555081600260005060008673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060003373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828282505403925050819055506001905061048656610485565b60009050610486565b5b9392505050565b6000600160005060008373ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000505490506104c6565b919050565b600081600160005060003373ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020600050541015801561050c5750600082115b156105fb5781600160005060003373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008282825054039250508190555081600160005060008573ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000206000828282505401925050819055508273ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef846040518082815260200191505060405180910390a36001905061060556610604565b60009050610605565b5b92915050565b6000600260005060008473ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005060008373ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060005054905061066e565b92915050565b60006000600050549050610683565b9056";
            var abi =
                @"[{""constant"":false,""inputs"":[{""name"":""_spender"",""type"":""address""},{""name"":""_value"",""type"":""uint256""}],""name"":""approve"",""outputs"":[{""name"":""success"",""type"":""bool""}],""type"":""function""},{""constant"":true,""inputs"":[],""name"":""totalSupply"",""outputs"":[{""name"":""supply"",""type"":""uint256""}],""type"":""function""},{""constant"":false,""inputs"":[{""name"":""_from"",""type"":""address""},{""name"":""_to"",""type"":""address""},{""name"":""_value"",""type"":""uint256""}],""name"":""transferFrom"",""outputs"":[{""name"":""success"",""type"":""bool""}],""type"":""function""},{""constant"":true,""inputs"":[{""name"":""_owner"",""type"":""address""}],""name"":""balanceOf"",""outputs"":[{""name"":""balance"",""type"":""uint256""}],""type"":""function""},{""constant"":false,""inputs"":[{""name"":""_to"",""type"":""address""},{""name"":""_value"",""type"":""uint256""}],""name"":""transfer"",""outputs"":[{""name"":""success"",""type"":""bool""}],""type"":""function""},{""constant"":true,""inputs"":[{""name"":""_owner"",""type"":""address""},{""name"":""_spender"",""type"":""address""}],""name"":""allowance"",""outputs"":[{""name"":""remaining"",""type"":""uint256""}],""type"":""function""},{""inputs"":[{""name"":""_initialAmount"",""type"":""uint256""}],""type"":""constructor""},{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""_from"",""type"":""address""},{""indexed"":true,""name"":""_to"",""type"":""address""},{""indexed"":false,""name"":""_value"",""type"":""uint256""}],""name"":""Transfer"",""type"":""event""},{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""_owner"",""type"":""address""},{""indexed"":true,""name"":""_spender"",""type"":""address""},{""indexed"":false,""name"":""_value"",""type"":""uint256""}],""name"":""Approval"",""type"":""event""}]";
            var addressOwner = "0x12890d2cce102216644c59dae5baed380d84830c";

            var web3 = new Nethereum.Web3.Web3(ClientFactory.GetClient());

            try
            {
                var   eth          = web3.Eth;
                var   transactions = eth.Transactions;
                ulong totalSupply  = 1000000;

                var pass   = "******";
                var result =
                    await web3.Personal.UnlockAccount.SendRequestAsync(addressOwner, pass, new HexBigInteger(600));

                Assert.True(result, "Account should be unlocked");
                var newAddress = await web3.Personal.NewAccount.SendRequestAsync(pass);

                Assert.NotNull(newAddress);
                Console.WriteLine(newAddress);

                var transactionHash =
                    await
                    eth.DeployContract.SendRequestAsync(abi, contractByteCode, addressOwner,
                                                        new HexBigInteger(900000), totalSupply);

                result = await web3.Miner.Start.SendRequestAsync();

                Assert.True(result, "Mining should have started");

                //get the contract address
                var receipt = await GetTransactionReceiptAsync(transactions, transactionHash);

                var code = await web3.Eth.GetCode.SendRequestAsync(receipt.ContractAddress);

                if (String.IsNullOrEmpty(code))
                {
                    throw new Exception(
                              "Code was not deployed correctly, verify bytecode or enough gas was uto deploy the contract");
                }

                var tokenService = new StandardTokenService(web3, receipt.ContractAddress);

                var transfersEvent = tokenService.GetTransferEvent();


                var totalSupplyDeployed = await tokenService.GetTotalSupplyAsync <ulong>();

                Assert.Equal(totalSupply, totalSupplyDeployed);

                var ownerBalance = await tokenService.GetBalanceOfAsync <ulong>(addressOwner);

                Assert.Equal(totalSupply, ownerBalance);

                transactionHash = await tokenService.TransferAsync(addressOwner, newAddress, 1000);

                var transferReceipt = await GetTransactionReceiptAsync(transactions, transactionHash);

                ownerBalance = await tokenService.GetBalanceOfAsync <ulong>(addressOwner);

                Assert.Equal(totalSupply - 1000, ownerBalance);

                var newAddressBalance = await tokenService.GetBalanceOfAsync <ulong>(newAddress);

                Assert.Equal((ulong)1000, newAddressBalance);

                var allTransfersFilter = await transfersEvent.CreateFilterAsync(new BlockParameter(transferReceipt.BlockNumber));

                var eventLogsAll = await transfersEvent.GetAllChanges <Transfer>(allTransfersFilter);

                Assert.Equal(1, eventLogsAll.Count);
                var transferLog = eventLogsAll.First();
                Assert.Equal(transferLog.Log.TransactionIndex.HexValue, transferReceipt.TransactionIndex.HexValue);
                Assert.Equal(transferLog.Log.BlockNumber.HexValue, transferReceipt.BlockNumber.HexValue);
                Assert.Equal(transferLog.Event.AddressTo, newAddress);
                Assert.Equal(transferLog.Event.Value, (ulong)1000);
            }
            finally
            {
                var result = await web3.Miner.Stop.SendRequestAsync();

                Assert.True(result, "Mining should have stop");
                result = await web3.Personal.LockAccount.SendRequestAsync(addressOwner);

                Assert.True(result, "Account should be locked");
            }
        }
예제 #30
0
        public async void ShouldCreatePoAndTransferFunds()
        {
            // Prepare a new PO
            Buyer.Po poAsRequested = await CreateBuyerPoAsync(quoteId : GetRandomInt());

            var signature = poAsRequested.GetSignatureBytes(_contracts.Web3);

            //----------------------------------------------------------
            // BEFORE PO RAISED
            //----------------------------------------------------------
            // Balance of Web3, before test starts (check account running these tests has enough funds to pay for the PO)
            StandardTokenService sts = new StandardTokenService(_contracts.Web3, poAsRequested.CurrencyAddress);
            var totalPoValue         = poAsRequested.GetTotalCurrencyValue();
            var web3AddressBalance   = await sts.BalanceOfQueryAsync(_contracts.Web3.TransactionManager.Account.Address);

            web3AddressBalance.Should().BeGreaterOrEqualTo(totalPoValue, "the Web3 account must be able to pay for whole PO");
            _output.WriteLine($"PO: {poAsRequested.PoNumber}  total value {await totalPoValue.PrettifyAsync(sts)}");

            // Balance of BuyerWallet, before test starts
            var buyerWalletBalance = await sts.BalanceOfQueryAsync(poAsRequested.BuyerWalletAddress);

            _output.WriteLine($"Wallet Buyer balance before test: {await buyerWalletBalance.PrettifyAsync(sts)}");

            // Test setup - transfer required funds from current Web3 acccount to wallet buyer
            var txTransfer = await sts.TransferRequestAndWaitForReceiptAsync(poAsRequested.BuyerWalletAddress, totalPoValue);

            txTransfer.Status.Value.Should().Be(1);

            // Balance of BuyerWallet, before PO raised
            buyerWalletBalance = await sts.BalanceOfQueryAsync(poAsRequested.BuyerWalletAddress);

            _output.WriteLine($"Wallet Buyer balance after receiving funding from Web3 account: {await buyerWalletBalance.PrettifyAsync(sts)}");

            // Balance of Funding, before PO raised
            var fundingBalanceBefore = await sts.BalanceOfQueryAsync(_contracts.Deployment.FundingService.ContractHandler.ContractAddress);

            _output.WriteLine($"Funding balance before PO: {await fundingBalanceBefore.PrettifyAsync(sts)}");

            //----------------------------------------------------------
            // RAISE PO
            //----------------------------------------------------------
            // Create PO on-chain
            // NB this approves token transfer from WALLET BUYER contract (NOT msg.sender == current web3 account) to FUNDING contract
            var txReceiptCreate = await _contracts.Deployment.BuyerWalletService.CreatePurchaseOrderRequestAndWaitForReceiptAsync(poAsRequested, signature);

            txReceiptCreate.Status.Value.Should().Be(1);
            _output.WriteLine($"... PO created ...");

            //----------------------------------------------------------
            // AFTER PO RAISED
            //----------------------------------------------------------
            // Balance of BuyerWallet, after PO raised
            buyerWalletBalance = await sts.BalanceOfQueryAsync(poAsRequested.BuyerWalletAddress);

            _output.WriteLine($"Wallet Buyer balance after PO: {await buyerWalletBalance.PrettifyAsync(sts)}");

            // Balance of Funding, after PO raised
            var fundingBalanceAfter = await sts.BalanceOfQueryAsync(_contracts.Deployment.FundingService.ContractHandler.ContractAddress);

            _output.WriteLine($"Funding balance after PO: {await fundingBalanceAfter.PrettifyAsync(sts)}");

            // Check
            var diff = fundingBalanceAfter - fundingBalanceBefore;

            diff.Should().Be(totalPoValue, "funding contract should have increased in value by the PO value");
        }
예제 #31
0
        public async Task RunAsync()
        {
            var account = new Account(PrivateKey);
            var web3    = new Web3(account, "http://*****:*****@"[{""anonymous"":false,""inputs"":[{""indexed"":true,""name"":""_from"",""type"":""address""},{""indexed"":true,""name"":""_to"",""type"":""address""},{""indexed"":false,""name"":""_value"",""type"":""uint256""}],""name"":""Transfer"",""type"":""event""}]";

            var event2 = web3.Eth.GetContract(abi, transferReceipt.ContractAddress).GetEvent <TransferEventDTO>("Transfer");

            var logs2 = await event2.GetAllChanges(
                event2.CreateFilterInput(new BlockParameter(tokenDeploymemtReceipt.BlockNumber),
                                         default(BlockParameter)));


            //mixing definitions, creates the same filter input using the same Abi Event type
            var logs3 = await event2.GetAllChanges(
                event1.CreateFilterInput(new BlockParameter(tokenDeploymemtReceipt.BlockNumber),
                                         default(BlockParameter)));

            var logs4 = await event1.GetAllChanges(
                event2.CreateFilterInput(new BlockParameter(tokenDeploymemtReceipt.BlockNumber),
                                         default(BlockParameter)));

            //because we are using the event typed we can do something like this, because the definition is extracted from the type, the name as a parameter will be removed later on, as it is not needed.
            var abiEmpty = @"[]";
            var event3   = web3.Eth.GetContract(abiEmpty, transferReceipt.ContractAddress).GetEvent <TransferEventDTO>("Transfer");
            var logs5    = await event3.GetAllChanges(
                event3.CreateFilterInput(new BlockParameter(tokenDeploymemtReceipt.BlockNumber),
                                         default(BlockParameter)));

            //if not using a type definition on the first place
            var event4 = web3.Eth.GetContract(abi, transferReceipt.ContractAddress).GetEvent("Transfer");
            var logs6  = await event4.GetAllChanges <TransferEventDTO>(
                event4.CreateFilterInput(new BlockParameter(tokenDeploymemtReceipt.BlockNumber),
                                         default(BlockParameter)));

            //mixing different event object types again
            var logs7 = await event4.GetAllChanges <TransferEventDTO>(event1.CreateFilterInput(
                                                                          new BlockParameter(tokenDeploymemtReceipt.BlockNumber),
                                                                          default(BlockParameter)));

            var logs9 = await event1.GetAllChanges(event4.CreateFilterInput(
                                                       new BlockParameter(tokenDeploymemtReceipt.BlockNumber),
                                                       default(BlockParameter)));


            //using the generated service to create an instance of the Event
            var event5 = new StandardTokenService(web3, tokenDeploymemtReceipt.ContractAddress)
                         .GetTransferEvent();

            var logs8 = await event5.GetAllChanges(
                event5.CreateFilterInput(new BlockParameter(tokenDeploymemtReceipt.BlockNumber),
                                         default(BlockParameter)));
        }