Beispiel #1
0
        public TransactionInput CreateTransactionInput(string from, HexBigInteger gas,
                                                       HexBigInteger value)
        {
            var encodedInput = FunctionCallEncoder.EncodeRequest(FunctionABI.Sha3Signature);

            return(new TransactionInput(encodedInput, from, gas, value));
        }
        /// <summary>
        /// 异步 Call 调用 适用于链上调用但不需要共识(通常用constant,view等修饰的合约方法)
        /// </summary>
        /// <param name="contractAddress">合约地址</param>
        /// <param name="abi">合约abi</param>
        /// <param name="callFunctionName">调用方法名称</param>
        /// <returns>返回交易回执</returns>
        public async Task <ReceiptResultDto> CallRequestAsync(string contractAddress, string abi, string callFunctionName, Parameter[] inputsParameters = null, params object[] value)
        {
            CallInput callDto = new CallInput();

            callDto.From = new Account(this._privateKey).Address.ToLower();//address ;
            var contractAbi = new ABIDeserialiser().DeserialiseContract(abi);

            callDto.To    = contractAddress;
            callDto.Value = new HexBigInteger(0);
            var function = contractAbi.Functions.FirstOrDefault(x => x.Name == callFunctionName);

            var sha3Signature = function.Sha3Signature;// "0x53ba0944";

            if (inputsParameters == null)
            {
                callDto.Data = "0x" + sha3Signature;
            }
            else
            {
                var functionCallEncoder = new FunctionCallEncoder();
                var funcData            = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters,
                                                                            value);
                callDto.Data = funcData;
            }
            var getRequest = new RpcRequest(this._requestId, JsonRPCAPIConfig.Call, new object[] { this._requestObjectId, callDto });
            var result     = await this._rpcClient.SendRequestAsync <ReceiptResultDto>(getRequest);

            //var getRequest = new RpcRequestMessage(this.RequestId, JsonRPCAPIConfig.Call, new object[] { this.RequestObjectId, callDto });
            //var result = HttpUtils.RpcPost<ReceiptResultDto>(BaseConfig.DefaultUrl, getRequest); //同步方法
            return(result);
        }
        /// <summary>
        ///异步 发送交易,返回交易回执
        /// </summary>
        /// <param name="abi">合约abi</param>
        /// <param name="contractAddress">合约地址</param>
        /// <param name="functionName">合约请求调用方法名称</param>
        /// <param name="inputsParameters">方法对应的 参数</param>
        /// <param name="value">请求参数值</param>
        /// <returns>交易回执</returns>
        public async Task <ReceiptResultDto> SendTranscationWithReceiptAsync(string abi, string contractAddress, string functionName, Parameter[] inputsParameters, params object[] value)
        {
            ReceiptResultDto receiptResult = new ReceiptResultDto();

            var des                 = new ABIDeserialiser();
            var contract            = des.DeserialiseContract(abi);
            var function            = contract.Functions.FirstOrDefault(x => x.Name == functionName);
            var sha3Signature       = function.Sha3Signature;// "0x53ba0944";
            var functionCallEncoder = new FunctionCallEncoder();
            var result              = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters,
                                                                        value);
            var blockNumber = await GetBlockNumberAsync();

            var transDto = BuildTransactionParams(result, blockNumber, contractAddress);
            var tx       = BuildRLPTranscation(transDto);

            tx.Sign(new EthECKey(this._privateKey.HexToByteArray(), true));
            var txHash = await SendRequestAysnc <string>(tx.Data, tx.Signature);

            if (txHash != null)
            {
                receiptResult = await GetTranscationReceiptAsync(txHash);

                if (receiptResult == null)
                {
                    throw new Exception("txHash != null 的时候报错了:" + receiptResult.ToJson());
                }
            }
            return(receiptResult);
        }
Beispiel #4
0
        public Task <string> SendTransactionAsync(string from, HexBigInteger gas,
                                                  HexBigInteger value)
        {
            var encodedInput = FunctionCallEncoder.EncodeRequest(FunctionABI.Sha3Signature);

            return(SendTransactionAsync(encodedInput, from, gas, value));
        }
Beispiel #5
0
        public async Task <dynamic> ExecuteTestAsync(RpcClient client)
        {
            //The compiled solidity contract to be deployed
            //contract test { function multiply(uint a) returns(uint d) { return a * 7; } }
            var contractByteCode =
                "0x606060405260728060106000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa1146037576035565b005b604b60048080359060200190919050506061565b6040518082815260200191505060405180910390f35b6000600782029050606d565b91905056";

            //Create a new Eth Send Transanction RPC Handler
            var ethSendTransation = new EthSendTransaction(client);
            //As the input the compiled contract is the Data, together with our address
            var transactionInput = new TransactionInput();

            transactionInput.Data = contractByteCode;
            transactionInput.From = "0x12890d2cce102216644c59dae5baed380d84830c";
            // retrieve the hash
            var transactionHash = await ethSendTransation.SendRequestAsync(transactionInput);

            //the contract should be mining now

            //get contract address
            var ethGetTransactionReceipt = new EthGetTransactionReceipt(client);
            TransactionReceipt receipt   = null;

            //wait for the contract to be mined to the address
            while (receipt == null)
            {
                receipt = await ethGetTransactionReceipt.SendRequestAsync(transactionHash);
            }

            //Encode and build function parameters
            var function = new FunctionCallEncoder();

            //Input the function method Sha3Encoded (4 bytes)
            var sha3Signature = "c6888fa1";
            //Define input parameters
            var inputParameters = new[] { new Parameter("uint", "a") };
            //encode the function call (function + parameter input)

            //using 69 as the input
            var functionCall = function.EncodeRequest(sha3Signature, inputParameters, 69);

            //reuse the transaction input, (just the address)
            //the destination address is the contract address
            transactionInput.To = receipt.ContractAddress;
            //use as data the function call
            transactionInput.Data = functionCall;
            // rpc method to do the call
            var ethCall = new EthCall(client);
            // call and get the result
            var resultFunction = await ethCall.SendRequestAsync(transactionInput);

            // decode the output
            var functionDecoder = new FunctionCallDecoder();

            var output = functionDecoder.DecodeOutput <int>(resultFunction, new Parameter("uint", "d"));

            //visual test
            return("The result of deploying a contract and calling a function to multiply 7 by 69 is: " + output +
                   " and should be 483");
        }
Beispiel #6
0
        /// <summary>
        ///同步 发送交易,返回交易回执
        /// </summary>
        /// <param name="abi">合约abi</param>
        /// <param name="contractAddress">合约地址</param>
        /// <param name="functionName">合约请求调用方法名称</param>
        /// <param name="inputsParameters">方法对应的 参数</param>
        /// <param name="value">请求参数值</param>
        /// <returns>交易回执</returns>
        public ReceiptResultDto SendTranscationWithReceipt(string abi, string contractAddress, string functionName, Parameter[] inputsParameters, params object[] value)
        {
            ReceiptResultDto receiptResult = new ReceiptResultDto();

            var des      = new ABIDeserialiser();
            var contract = des.DeserialiseContract(abi);

            var function            = contract.Functions.FirstOrDefault(x => x.Name == functionName);
            var sha3Signature       = function.Sha3Signature;// "0x53ba0944";
            var functionCallEncoder = new FunctionCallEncoder();
            var result = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters,
                                                           value);
            var blockNumber = GetBlockNumber();
            var transDto    = BuildTransactionParams(result, blockNumber, contractAddress);
            var tx          = BuildRLPTranscation(transDto);

            tx.Sign(new EthECKey(this._privateKey.HexToByteArray(), true));
            var txHash = SendRequest <object>(tx.Data, tx.Signature);

            if (txHash != null)
            {
                receiptResult = GetTranscationReceipt(txHash.ToString());
            }
            return(receiptResult);
        }
Beispiel #7
0
 protected FunctionBuilderBase(ContractBuilder contract, FunctionABI functionAbi)
 {
     FunctionABI         = functionAbi;
     _contract           = contract;
     FunctionCallDecoder = new FunctionCallDecoder();
     FunctionCallEncoder = new FunctionCallEncoder();
 }
 public virtual void ShouldEncodeAddress()
 {
     var functionCallEncoder = new FunctionCallEncoder();
     var sha3Signature = "c6888fa1";
     var inputsParameters = new[] {CreateParam("address", "a")};
     var result = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, "1234567890abcdef1234567890abcdef12345678");
     Assert.Equal("0xc6888fa10000000000000000000000001234567890abcdef1234567890abcdef12345678", result);
 }
 public virtual void ShouldEncodeBool()
 {
     var functionCallEncoder = new FunctionCallEncoder();
     var sha3Signature = "c6888fa1";
     var inputsParameters = new[] { CreateParam("bool", "a") };
     var result = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, true);
     Assert.Equal("0xc6888fa10000000000000000000000000000000000000000000000000000000000000001", result);
 }
        public async Task<dynamic> ExecuteTestAsync(RpcClient client)
        {

            
            //The compiled solidity contract to be deployed
            //contract test { function multiply(uint a) returns(uint d) { return a * 7; } }
            var contractByteCode = "0x606060405260728060106000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa1146037576035565b005b604b60048080359060200190919050506061565b6040518082815260200191505060405180910390f35b6000600782029050606d565b91905056";

            //Create a new Eth Send Transanction RPC Handler
            var ethSendTransation = new EthSendTransaction(client);
            //As the input the compiled contract is the Data, together with our address
            var transactionInput = new TransactionInput();
            transactionInput.Data = contractByteCode;
            transactionInput.From = "0x12890d2cce102216644c59dae5baed380d84830c";
            // retrieve the hash
            var transactionHash =  await ethSendTransation.SendRequestAsync( transactionInput);
            
            //the contract should be mining now

            //get contract address 
            var ethGetTransactionReceipt = new EthGetTransactionReceipt(client);
            TransactionReceipt receipt = null;
            //wait for the contract to be mined to the address
            while (receipt == null)
            {
                receipt = await ethGetTransactionReceipt.SendRequestAsync( transactionHash);
            }

            //Encode and build function parameters 
            var function = new FunctionCallEncoder();

            //Input the function method Sha3Encoded (4 bytes) 
            var sha3Signature = "c6888fa1";
            //Define input parameters
            var inputParameters = new[] { new Parameter("uint", "a") };
            //encode the function call (function + parameter input)
           
            //using 69 as the input
            var functionCall = function.EncodeRequest(sha3Signature, inputParameters, 69);
            //reuse the transaction input, (just the address) 
            //the destination address is the contract address
            transactionInput.To = receipt.ContractAddress;
            //use as data the function call
            transactionInput.Data = functionCall;
            // rpc method to do the call
            var ethCall = new EthCall(client);
            // call and get the result
            var resultFunction = await ethCall.SendRequestAsync( transactionInput);
            // decode the output
            var functionDecoder = new FunctionCallDecoder();

            var output = functionDecoder.DecodeOutput<int>(resultFunction, new Parameter("uint", "d"));
            //visual test 
            return "The result of deploying a contract and calling a function to multiply 7 by 69 is: " + output  + " and should be 483";

           

        }
Beispiel #11
0
        public Task <string> SignAndSendTransactionAsync(string password, HexBigInteger gas, HexBigInteger value, string from
                                                         )
        {
            var encodedInput = FunctionCallEncoder.EncodeRequest(FunctionABI.Sha3Signature);

            return
                (personalSignAndSendTransaction.SendRequestAsync(new TransactionInput(encodedInput, ContractAddress, from, gas,
                                                                                      value), password));
        }
Beispiel #12
0
        public virtual void ShouldEncodeInt()
        {
            var input = new FunctionIntInput {
                A = 69
            };
            var result = new FunctionCallEncoder().EncodeRequest(input);

            Assert.Equal("0xc6888fa10000000000000000000000000000000000000000000000000000000000000045", result);
        }
        public virtual void ShouldEncodeAddress()
        {
            var functionCallEncoder = new FunctionCallEncoder();
            var sha3Signature       = "c6888fa1";
            var inputsParameters    = new[] { CreateParam("address", "a") };
            var result = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, "1234567890abcdef1234567890abcdef12345678");

            Assert.Equal("0xc6888fa10000000000000000000000001234567890abcdef1234567890abcdef12345678", result);
        }
        public virtual void ShouldEncodeBool()
        {
            var functionCallEncoder = new FunctionCallEncoder();
            var sha3Signature       = "c6888fa1";
            var inputsParameters    = new[] { CreateParam("bool", "a") };
            var result = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, true);

            Assert.Equal("0xc6888fa10000000000000000000000000000000000000000000000000000000000000001", result);
        }
Beispiel #15
0
        public async Task <decimal> BalanceOfAsync(string contractAddress, ITronAccount ownerAccount)
        {
            var contractAddressBytes = Base58Encoder.DecodeFromBase58Check(contractAddress);
            var ownerAddressBytes    = Base58Encoder.DecodeFromBase58Check(ownerAccount.Address);
            var wallet      = _walletClient.GetProtocol();
            var functionABI = ABITypedRegistry.GetFunctionABI <BalanceOfFunction>();

            try
            {
                var addressBytes = new byte[20];
                Array.Copy(ownerAddressBytes, 1, addressBytes, 0, addressBytes.Length);

                var addressBytesHex = "0x" + addressBytes.ToHex();

                var balanceOf = new BalanceOfFunction {
                    Owner = addressBytesHex
                };
                var decimals = GetDecimals(wallet, contractAddressBytes);

                var encodedHex = new FunctionCallEncoder().EncodeRequest(balanceOf, functionABI.Sha3Signature);

                var trigger = new TriggerSmartContract
                {
                    ContractAddress = ByteString.CopyFrom(contractAddressBytes),
                    OwnerAddress    = ByteString.CopyFrom(ownerAddressBytes),
                    Data            = ByteString.CopyFrom(encodedHex.HexToByteArray()),
                };

                var transactionExtention = await wallet.TriggerConstantContractAsync(trigger, headers : _walletClient.GetHeaders());

                if (!transactionExtention.Result.Result)
                {
                    throw new Exception(transactionExtention.Result.Message.ToStringUtf8());
                }
                if (transactionExtention.ConstantResult.Count == 0)
                {
                    throw new Exception($"result error, ConstantResult length=0.");
                }

                var result = new FunctionCallDecoder().DecodeFunctionOutput <BalanceOfFunctionOutput>(transactionExtention.ConstantResult[0].ToByteArray().ToHex());

                var balance = Convert.ToDecimal(result.Balance);
                if (decimals > 0)
                {
                    balance /= Convert.ToDecimal(Math.Pow(10, decimals));
                }

                return(balance);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                throw;
            }
        }
        public virtual void ShouldEncodeMultipleTypesIncludingDynamiString()
        {
            var paramsEncoded =
                "0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000004500000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000568656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005776f726c64000000000000000000000000000000000000000000000000000000";
            var functionCallEncoder = new FunctionCallEncoder();
            var sha3Signature       = "c6888fa1";
            var inputsParameters    = new[] { CreateParam("string", "a"), CreateParam("int", "b"), CreateParam("string", "c") };

            var result = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, "hello", 69, "world");

            Assert.Equal("0x" + sha3Signature + paramsEncoded, result);
        }
        protected FunctionBase(IClient rpcClient, Contract contract, FunctionABI functionABI)
        {
            FunctionABI        = functionABI;
            this.rpcClient     = rpcClient;
            this.contract      = contract;
            ethCall            = new EthCall(rpcClient);
            ethSendTransaction = new EthSendTransaction(rpcClient);
            ethEstimateGas     = new EthEstimateGas(rpcClient);

            FunctionCallDecoder = new FunctionCallDecoder();
            FunctionCallEncoder = new FunctionCallEncoder();
        }
 public virtual void ShouldEncodeMultipleTypesIncludingDynamiString()
 {
      var paramsEncoded =
     "0000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000004500000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000000000000568656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005776f726c64000000000000000000000000000000000000000000000000000000";
     var functionCallEncoder = new FunctionCallEncoder();
     var sha3Signature = "c6888fa1";
     var inputsParameters = new[] {CreateParam("string", "a"), CreateParam("int", "b"), CreateParam("string", "c")};
    
     var result = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, "hello", 69, "world");
     Assert.Equal("0x" + sha3Signature + paramsEncoded, result);
     
 }
Beispiel #19
0
        public virtual void WhenAnAddressParameterValueIsNull_ShouldProvideAHelpfulError()
        {
            var functionCallEncoder = new FunctionCallEncoder();
            var sha3Signature       = "c6888fa1";
            var inputsParameters    = new[] { CreateParam("address", "_address1") };
            var parameterValues     = new object[] { null };

            var ex = Assert.Throws <AbiEncodingException>(() => functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, parameterValues));

            const string ExpectedError =
                "An error occurred encoding abi value. Order: '1', Type: 'address', Value: 'null'.  Ensure the value is valid for the abi type.";

            Assert.Equal(ExpectedError, ex.Message);
        }
Beispiel #20
0
        private long GetDecimals(Wallet.WalletClient wallet, byte[] contractAddressBytes)
        {
            var trc20Decimals = new DecimalsFunction();

            var callEncoder = new FunctionCallEncoder();
            var functionABI = ABITypedRegistry.GetFunctionABI <DecimalsFunction>();

            var encodedHex = callEncoder.EncodeRequest(trc20Decimals, functionABI.Sha3Signature);

            var trigger = new TriggerSmartContract
            {
                ContractAddress = ByteString.CopyFrom(contractAddressBytes),
                Data            = ByteString.CopyFrom(encodedHex.HexToByteArray()),
            };

            var txnExt = wallet.TriggerConstantContract(trigger, headers: _walletClient.GetHeaders());

            var result = txnExt.ConstantResult[0].ToByteArray().ToHex();

            return(new FunctionCallDecoder().DecodeOutput <long>(result, new Parameter("uint8", "d")));
        }
        private static async Task SendTransaction(RpcClient client, string addressFrom,
            string contractAddress)
        {
            var transactionInput = new TransactionInput();
            var ethSendTransaction = new EthSendTransaction(client);
            var function = new FunctionCallEncoder();
            //Input the function method Sha3Encoded (4 bytes) 
            var sha3Signature = "c6888fa1";
            //Define input parameters
            var inputParameters = new[] {new Parameter("uint", "a")};
            //encode the function call (function + parameter input)
            //using 69 as the input
            var functionCall = function.EncodeRequest(sha3Signature, inputParameters, 69);
            transactionInput.From = addressFrom;
            //the destination address is the contract address
            transactionInput.To = contractAddress;
            //use as data the function call
            transactionInput.Data = functionCall;

            var transactionHashFunction = await ethSendTransaction.SendRequestAsync(transactionInput);
        }
        public virtual void ShouldEncodeMultipleTypesIncludingDynamicStringAndIntArray()
        {
            var paramsEncoded =
                "00000000000000000000000000000000000000000000000000000000000002c0000000000000000000000000000000000000000000000000000000000003944700000000000000000000000000000000000000000000000000000000000394480000000000000000000000000000000000000000000000000000000000039449000000000000000000000000000000000000000000000000000000000003944a000000000000000000000000000000000000000000000000000000000003944b000000000000000000000000000000000000000000000000000000000003944c000000000000000000000000000000000000000000000000000000000003944d000000000000000000000000000000000000000000000000000000000003944e000000000000000000000000000000000000000000000000000000000003944f0000000000000000000000000000000000000000000000000000000000039450000000000000000000000000000000000000000000000000000000000003945100000000000000000000000000000000000000000000000000000000000394520000000000000000000000000000000000000000000000000000000000039453000000000000000000000000000000000000000000000000000000000003945400000000000000000000000000000000000000000000000000000000000394550000000000000000000000000000000000000000000000000000000000039456000000000000000000000000000000000000000000000000000000000003945700000000000000000000000000000000000000000000000000000000000394580000000000000000000000000000000000000000000000000000000000039459000000000000000000000000000000000000000000000000000000000003945a0000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000000568656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005776f726c64000000000000000000000000000000000000000000000000000000";

            var function = new FunctionMultipleInputOutput();
            function.A = "hello";
            function.C = "world";

            var array = new BigInteger[20];
            for (uint i = 0; i < 20; i++)
            {
                array[i] = i + 234567;
            }

            function.B = array.ToList();

            var result = new FunctionCallEncoder().EncodeRequest(function, "c6888fa1");

            Assert.Equal("0x" + "c6888fa1" + paramsEncoded, result);
        }
        public virtual void ShouldEncodeMultipleTypesIncludingDynamicStringAndIntArray()
        {
            var paramsEncoded =
                "00000000000000000000000000000000000000000000000000000000000002c0000000000000000000000000000000000000000000000000000000000003944700000000000000000000000000000000000000000000000000000000000394480000000000000000000000000000000000000000000000000000000000039449000000000000000000000000000000000000000000000000000000000003944a000000000000000000000000000000000000000000000000000000000003944b000000000000000000000000000000000000000000000000000000000003944c000000000000000000000000000000000000000000000000000000000003944d000000000000000000000000000000000000000000000000000000000003944e000000000000000000000000000000000000000000000000000000000003944f0000000000000000000000000000000000000000000000000000000000039450000000000000000000000000000000000000000000000000000000000003945100000000000000000000000000000000000000000000000000000000000394520000000000000000000000000000000000000000000000000000000000039453000000000000000000000000000000000000000000000000000000000003945400000000000000000000000000000000000000000000000000000000000394550000000000000000000000000000000000000000000000000000000000039456000000000000000000000000000000000000000000000000000000000003945700000000000000000000000000000000000000000000000000000000000394580000000000000000000000000000000000000000000000000000000000039459000000000000000000000000000000000000000000000000000000000003945a0000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000000568656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005776f726c64000000000000000000000000000000000000000000000000000000";

        
            var functionCallEncoder = new FunctionCallEncoder();
            var sha3Signature = "c6888fa1";
            var inputsParameters = new[] {CreateParam("string", "a"), CreateParam("uint[20]", "b"), CreateParam("string", "c")};

            var array = new uint[20];
            for (uint i = 0; i < 20; i++)
            {
                array[i] = i + 234567;
            }

            var result = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, "hello", array, "world");

            Assert.Equal("0x" + sha3Signature + paramsEncoded, result);
          
        }
        public virtual void ShouldEncodeMultipleTypesIncludingDynamicStringAndIntArray()
        {
            var paramsEncoded =
                "00000000000000000000000000000000000000000000000000000000000002c0000000000000000000000000000000000000000000000000000000000003944700000000000000000000000000000000000000000000000000000000000394480000000000000000000000000000000000000000000000000000000000039449000000000000000000000000000000000000000000000000000000000003944a000000000000000000000000000000000000000000000000000000000003944b000000000000000000000000000000000000000000000000000000000003944c000000000000000000000000000000000000000000000000000000000003944d000000000000000000000000000000000000000000000000000000000003944e000000000000000000000000000000000000000000000000000000000003944f0000000000000000000000000000000000000000000000000000000000039450000000000000000000000000000000000000000000000000000000000003945100000000000000000000000000000000000000000000000000000000000394520000000000000000000000000000000000000000000000000000000000039453000000000000000000000000000000000000000000000000000000000003945400000000000000000000000000000000000000000000000000000000000394550000000000000000000000000000000000000000000000000000000000039456000000000000000000000000000000000000000000000000000000000003945700000000000000000000000000000000000000000000000000000000000394580000000000000000000000000000000000000000000000000000000000039459000000000000000000000000000000000000000000000000000000000003945a0000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000000568656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005776f726c64000000000000000000000000000000000000000000000000000000";


            var functionCallEncoder = new FunctionCallEncoder();
            var sha3Signature       = "c6888fa1";
            var inputsParameters    = new[] { CreateParam("string", "a"), CreateParam("uint[20]", "b"), CreateParam("string", "c") };

            var array = new uint[20];

            for (uint i = 0; i < 20; i++)
            {
                array[i] = i + 234567;
            }

            var result = functionCallEncoder.EncodeRequest(sha3Signature, inputsParameters, "hello", array, "world");

            Assert.Equal("0x" + sha3Signature + paramsEncoded, result);
        }
Beispiel #25
0
        public virtual void ShouldEncodeMultipleTypesIncludingDynamicStringAndIntArray()
        {
            var paramsEncoded =
                "00000000000000000000000000000000000000000000000000000000000002c0000000000000000000000000000000000000000000000000000000000003944700000000000000000000000000000000000000000000000000000000000394480000000000000000000000000000000000000000000000000000000000039449000000000000000000000000000000000000000000000000000000000003944a000000000000000000000000000000000000000000000000000000000003944b000000000000000000000000000000000000000000000000000000000003944c000000000000000000000000000000000000000000000000000000000003944d000000000000000000000000000000000000000000000000000000000003944e000000000000000000000000000000000000000000000000000000000003944f0000000000000000000000000000000000000000000000000000000000039450000000000000000000000000000000000000000000000000000000000003945100000000000000000000000000000000000000000000000000000000000394520000000000000000000000000000000000000000000000000000000000039453000000000000000000000000000000000000000000000000000000000003945400000000000000000000000000000000000000000000000000000000000394550000000000000000000000000000000000000000000000000000000000039456000000000000000000000000000000000000000000000000000000000003945700000000000000000000000000000000000000000000000000000000000394580000000000000000000000000000000000000000000000000000000000039459000000000000000000000000000000000000000000000000000000000003945a0000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000000000000000000000000000000000000568656c6c6f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005776f726c64000000000000000000000000000000000000000000000000000000";

            var function = new FunctionMultipleInputOutput();

            function.A = "hello";
            function.C = "world";

            var array = new BigInteger[20];

            for (uint i = 0; i < 20; i++)
            {
                array[i] = i + 234567;
            }

            function.B = array.ToList();

            var result = new FunctionCallEncoder().EncodeRequest(function);

            Assert.Equal("0x" + "c6888fa1" + paramsEncoded, result);
        }
Beispiel #26
0
 public PaymentsService(IPaymentTransfersRepository paymentTransfersRepository,
                        ITransactionScopeHandler transactionScopeHandler,
                        IPrivateBlockchainFacadeClient pbfClient,
                        IMAVNPropertyIntegrationClient realEstateIntegrationClient,
                        IEligibilityEngineClient eligibilityEngineClient,
                        ISettingsService settingsService,
                        IWalletManagementClient wmClient,
                        ICustomerProfileClient cpClient,
                        ICampaignClient campaignClient,
                        ILogFactory logFactory)
 {
     _functionCallEncoder         = new FunctionCallEncoder();
     _abiEncode                   = new ABIEncode();
     _paymentTransfersRepository  = paymentTransfersRepository;
     _transactionScopeHandler     = transactionScopeHandler;
     _pbfClient                   = pbfClient;
     _realEstateIntegrationClient = realEstateIntegrationClient;
     _eligibilityEngineClient     = eligibilityEngineClient;
     _settingsService             = settingsService;
     _wmClient       = wmClient;
     _cpClient       = cpClient;
     _campaignClient = campaignClient;
     _log            = logFactory.CreateLog(this);
 }
Beispiel #27
0
        internal void CompileExpression(ParserContext parser, ByteBuffer buffer, Expression expr, bool outputUsed)
        {
            if (expr is FunctionCall)
            {
                FunctionCallEncoder.Compile(this, parser, buffer, (FunctionCall)expr, outputUsed);
            }
            else if (expr is IntegerConstant)
            {
                ConstantEncoder.CompileInteger(parser, buffer, (IntegerConstant)expr, outputUsed);
            }
            else if (expr is Variable)
            {
                VariableEncoder.Compile(parser, buffer, (Variable)expr, outputUsed);
            }
            else if (expr is BooleanConstant)
            {
                ConstantEncoder.CompileBoolean(parser, buffer, (BooleanConstant)expr, outputUsed);
            }
            else if (expr is DotField)
            {
                DotFieldEncoder.Compile(this, parser, buffer, (DotField)expr, outputUsed);
            }
            else if (expr is BracketIndex)
            {
                BracketIndexEncoder.Compile(this, parser, buffer, (BracketIndex)expr, outputUsed);
            }
            else if (expr is OpChain)
            {
                OpChainEncoder.Compile(this, parser, buffer, (OpChain)expr, outputUsed);
            }
            else if (expr is StringConstant)
            {
                ConstantEncoder.CompileString(parser, buffer, (StringConstant)expr, outputUsed);
            }
            else if (expr is NegativeSign)
            {
                NegativeSignEncoder.Compile(this, parser, buffer, (NegativeSign)expr, outputUsed);
            }
            else if (expr is ListDefinition)
            {
                ListDefinitionEncoder.Compile(this, parser, buffer, (ListDefinition)expr, outputUsed);
            }
            else if (expr is Increment)
            {
                IncrementEncoder.Compile(this, parser, buffer, (Increment)expr, outputUsed);
            }
            else if (expr is FloatConstant)
            {
                ConstantEncoder.CompileFloat(parser, buffer, (FloatConstant)expr, outputUsed);
            }
            else if (expr is NullConstant)
            {
                ConstantEncoder.CompileNull(parser, buffer, (NullConstant)expr, outputUsed);
            }
            else if (expr is ThisKeyword)
            {
                ThisEncoder.Compile(parser, buffer, (ThisKeyword)expr, outputUsed);
            }
            else if (expr is Instantiate)
            {
                InstantiateEncoder.Compile(this, parser, buffer, (Instantiate)expr, outputUsed);
            }
            else if (expr is DictionaryDefinition)
            {
                DictionaryDefinitionEncoder.Compile(this, parser, buffer, (DictionaryDefinition)expr, outputUsed);
            }
            else if (expr is BooleanCombination)
            {
                BooleanCombinationEncoder.Compile(this, parser, buffer, (BooleanCombination)expr, outputUsed);
            }
            else if (expr is BooleanNot)
            {
                BooleanNotEncoder.Compile(this, parser, buffer, (BooleanNot)expr, outputUsed);
            }
            else if (expr is Cast)
            {
                CastEncoder.Compile(this, parser, buffer, (Cast)expr, outputUsed);
            }
            else if (expr is Ternary)
            {
                TernaryEncoder.Compile(this, parser, buffer, (Ternary)expr, outputUsed);
            }
            else if (expr is ListSlice)
            {
                ListSliceEncoder.Compile(this, parser, buffer, (ListSlice)expr, outputUsed);
            }
            else if (expr is NullCoalescer)
            {
                NullCoalescerEncoder.Compile(this, parser, buffer, (NullCoalescer)expr, outputUsed);
            }
            else if (expr is BaseMethodReference)
            {
                BaseMethodReferenceEncoder.Compile(parser, buffer, (BaseMethodReference)expr, outputUsed);
            }
            else if (expr is FunctionReference)
            {
                FunctionReferenceEncoder.Compile(parser, buffer, (FunctionReference)expr, outputUsed);
            }
            else if (expr is FieldReference)
            {
                FieldReferenceEncoder.Compile(parser, buffer, (FieldReference)expr, outputUsed);
            }
            else if (expr is CoreFunctionInvocation)
            {
                CoreFunctionInvocationEncoder.Compile(this, parser, buffer, (CoreFunctionInvocation)expr, null, null, outputUsed);
            }
            else if (expr is IsComparison)
            {
                IsComparisonEncoder.Compile(this, parser, buffer, (IsComparison)expr, outputUsed);
            }
            else if (expr is ClassReferenceLiteral)
            {
                ClassReferenceEncoder.Compile(parser, buffer, (ClassReferenceLiteral)expr, outputUsed);
            }
            else if (expr is Lambda)
            {
                LambdaEncoder.Compile(this, parser, buffer, (Lambda)expr, outputUsed);
            }
            else if (expr is PrimitiveMethodReference)
            {
                DotFieldEncoder.Compile(this, parser, buffer, (PrimitiveMethodReference)expr, outputUsed);
            }

            // The following parse tree items must be removed before reaching the byte code encoder.
            else if (expr is BaseKeyword)
            {
                this.CompileBaseKeyword(parser, buffer, (BaseKeyword)expr, outputUsed);
            }
            else if (expr is CompileTimeDictionary)
            {
                this.CompileCompileTimeDictionary((CompileTimeDictionary)expr);
            }


            else
            {
                throw new NotImplementedException();
            }
        }
        public override async Task <string> ExecuteAsync(IClient client)
        {
            //The compiled solidity contract to be deployed
            //contract test { function multiply(uint a) returns(uint d) { return a * 7; } }
            var contractByteCode =
                "0x606060405260728060106000396000f360606040526000357c010000000000000000000000000000000000000000000000000000000090048063c6888fa1146037576035565b005b604b60048080359060200190919050506061565b6040518082815260200191505060405180910390f35b6000600782029050606d565b91905056";

            //As the input the compiled contract is the Data, together with our address
            var transactionInput = new TransactionInput();

            transactionInput.Data = contractByteCode;
            transactionInput.From = Settings.GetDefaultAccount();
            // retrieve the hash

            var minerStart       = new MinerStart(client);
            var minerStartResult = await minerStart.SendRequestAsync();

            var transactionHash =
                await
                new PersonalSignAndSendTransaction(client).SendRequestAsync(transactionInput,
                                                                            Settings.GetDefaultAccountPassword());

            //get contract address
            var ethGetTransactionReceipt = new EthGetTransactionReceipt(client);
            TransactionReceipt receipt   = null;

            //wait for the contract to be mined to the address
            while (receipt == null)
            {
                await Task.Delay(1000);

                receipt = await ethGetTransactionReceipt.SendRequestAsync(transactionHash);
            }


            var minerStop       = new MinerStop(client);
            var minerStopResult = await minerStop.SendRequestAsync();

            //Encode and build function parameters
            var function = new FunctionCallEncoder();

            //Input the function method Sha3Encoded (4 bytes)
            var sha3Signature = "c6888fa1";
            //Define input parameters
            var inputParameters = new[] { new Parameter("uint", "a") };
            //encode the function call (function + parameter input)

            //using 69 as the input
            var functionCall = function.EncodeRequest(sha3Signature, inputParameters, 69);

            //reuse the transaction input, (just the address)
            //the destination address is the contract address
            transactionInput.To = receipt.ContractAddress;
            //use as data the function call
            transactionInput.Data = functionCall;
            // rpc method to do the call
            var ethCall = new EthCall(client);
            // call and get the result
            var resultFunction = await ethCall.SendRequestAsync(transactionInput);

            // decode the output
            var functionDecoder = new FunctionCallDecoder();

            var output  = functionDecoder.DecodeOutput <int>(resultFunction, new Parameter("uint", "d"));
            var message = "The result of deploying a contract and calling a function to multiply 7 by 69 is: " +
                          output +
                          " and should be 483";

            Assert.Equal(483, output);

            return(message);
        }
Beispiel #29
0
        public async Task <string> TransferAsync(string contractAddress, ITronAccount ownerAccount, string toAddress, decimal amount, string memo, long feeLimit)
        {
            var contractAddressBytes = Base58Encoder.DecodeFromBase58Check(contractAddress);
            var callerAddressBytes   = Base58Encoder.DecodeFromBase58Check(toAddress);
            var ownerAddressBytes    = Base58Encoder.DecodeFromBase58Check(ownerAccount.Address);
            var wallet      = _walletClient.GetProtocol();
            var functionABI = ABITypedRegistry.GetFunctionABI <TransferFunction>();

            try
            {
                var contract = await wallet.GetContractAsync(new BytesMessage
                {
                    Value = ByteString.CopyFrom(contractAddressBytes),
                }, headers : _walletClient.GetHeaders());

                var toAddressBytes = new byte[20];
                Array.Copy(callerAddressBytes, 1, toAddressBytes, 0, toAddressBytes.Length);

                var toAddressHex = "0x" + toAddressBytes.ToHex();

                var decimals = GetDecimals(wallet, contractAddressBytes);

                var tokenAmount = amount;
                if (decimals > 0)
                {
                    tokenAmount = amount * Convert.ToDecimal(Math.Pow(10, decimals));
                }

                var trc20Transfer = new TransferFunction
                {
                    To          = toAddressHex,
                    TokenAmount = Convert.ToInt64(tokenAmount),
                };

                var encodedHex = new FunctionCallEncoder().EncodeRequest(trc20Transfer, functionABI.Sha3Signature);


                var trigger = new TriggerSmartContract
                {
                    ContractAddress = ByteString.CopyFrom(contractAddressBytes),
                    OwnerAddress    = ByteString.CopyFrom(ownerAddressBytes),
                    Data            = ByteString.CopyFrom(encodedHex.HexToByteArray()),
                };

                var transactionExtention = await wallet.TriggerConstantContractAsync(trigger, headers : _walletClient.GetHeaders());

                if (!transactionExtention.Result.Result)
                {
                    _logger.LogWarning($"[transfer]transfer failed, message={transactionExtention.Result.Message.ToStringUtf8()}.");
                    return(null);
                }

                var transaction = transactionExtention.Transaction;

                if (transaction.Ret.Count > 0 && transaction.Ret[0].Ret == Transaction.Types.Result.Types.code.Failed)
                {
                    return(null);
                }

                transaction.RawData.Data     = ByteString.CopyFromUtf8(memo);
                transaction.RawData.FeeLimit = feeLimit;

                var transSign = _transactionClient.GetTransactionSign(transaction, ownerAccount.PrivateKey);

                var result = await _transactionClient.BroadcastTransactionAsync(transSign);

                return(transSign.GetTxid());
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);
                return(null);
            }
        }
Beispiel #30
0
 protected FunctionBuilderBase(string contractAddress)
 {
     ContractAddress     = contractAddress;
     FunctionCallDecoder = new FunctionCallDecoder();
     FunctionCallEncoder = new FunctionCallEncoder();
 }
        private static async Task SendTransaction(IClient client, string addressFrom,
            string contractAddress)
        {
            var transactionInput = new TransactionInput();
            var ethSendTransaction = new EthSendTransaction(client);
            var function = new FunctionCallEncoder();
            //Input the function method Sha3Encoded (4 bytes) 
            var sha3Signature = "c6888fa1";
            //Define input parameters
            var inputParameters = new[] {new Parameter("uint", "a")};
            //encode the function call (function + parameter input)
            //using 69 as the input
            var functionCall = function.EncodeRequest(sha3Signature, inputParameters, 69);
            transactionInput.From = addressFrom;
            //the destination address is the contract address
            transactionInput.To = contractAddress;
            //use as data the function call
            transactionInput.Data = functionCall;

            var transactionHashFunction = await ethSendTransaction.SendRequestAsync(transactionInput);
        }
Beispiel #32
0
 public string GetData(params object[] functionInput)
 {
     return(FunctionCallEncoder.EncodeRequest(FunctionABI.Sha3Signature, FunctionABI.InputParameters,
                                              functionInput));
 }
Beispiel #33
0
 public BlockchainEncodingService()
 {
     _functionCallEncoder = new FunctionCallEncoder();
 }
Beispiel #34
0
        private async Task OnMetaMaskShare()
        {
            Error = null;

            var chain = await MetaMaskService.GetSelectedChain();

            if (chain.chain != MetaMask.Blazor.Enums.Chain.Kovan)
            {
                Error    = "Please select the Kovan network in MetaMask. Sharing currently only works on the Kovan testnet.";
                Progress = null;
                return;
            }

            if (SkyDocsService.CurrentSum == null)
            {
                Progress = null;
                return;
            }

            //Store data to share and get URL
            Progress = "Saving sharing secrets to Skynet...";
            StateHasChanged();

            try
            {
                var             existing = SkyDocsService.CurrentSum;
                DocumentSummary shareSum = new DocumentSummary()
                {
                    ContentSeed   = existing.ContentSeed,
                    CreatedDate   = existing.CreatedDate,
                    Id            = existing.Id,
                    ShareOrigin   = existing.ShareOrigin,
                    Title         = existing.Title,
                    PublicKey     = existing.PublicKey,
                    ModifiedDate  = existing.ModifiedDate,
                    PreviewImage  = existing.PreviewImage,
                    PrivateKey    = ShareReadOnly ? null : existing.PrivateKey,
                    StorageSource = SkyDocsService.IsDfinityLogin ? StorageSource.Dfinity : StorageSource.Skynet
                };

                string?url = await ShareService.StoreShareMessage(ShareFormModel.EthAddress, shareSum);

                if (string.IsNullOrEmpty(url))
                {
                    Error = "Error storing shared data. Please try again";
                }
                else
                {
                    Console.WriteLine(url);
                }

                //Smart contract has a function called "share"
                FunctionABI function = new FunctionABI("share", false);

                //With 4 inputs
                var inputsParameters = new[] {
                    new Parameter("address", "receiver"),
                    new Parameter("string", "appId"),
                    new Parameter("string", "shareType"),
                    new Parameter("string", "data")
                };
                function.InputParameters = inputsParameters;

                var functionCallEncoder = new FunctionCallEncoder();

                var data = functionCallEncoder.EncodeRequest(function.Sha3Signature, inputsParameters,
                                                             ShareFormModel.EthAddress,
                                                             "SkyDocs",
                                                             string.Empty,
                                                             url);

                //Using The Share It Network: https://github.com/michielpost/TheShareItNetwork
                string     address  = "0x6E8c5AFd3CFf5f6Ec85c032B68eF2997323a00FD";
                BigInteger weiValue = 0;

                data = data[2..]; //Remove the 0x from the generated string
 public virtual void ShouldEncodeInt()
 {
     var input = new FunctionIntInput {A = 69};
     var result = new FunctionCallEncoder().EncodeRequest(input, "c6888fa1");
     Assert.Equal("0xc6888fa10000000000000000000000000000000000000000000000000000000000000045", result);
 }
 public EncoderService()
 {
     _abiEncode           = new ABIEncode();
     _functionCallEncoder = new FunctionCallEncoder();
 }
Beispiel #37
0
        public TransactionInput CreateTransactionInput(HexBigInteger type, string from, HexBigInteger gas, HexBigInteger value, HexBigInteger maxFeePerGas, HexBigInteger maxPriorityFeePerGas)
        {
            var encodedInput = FunctionCallEncoder.EncodeRequest(FunctionABI.Sha3Signature);

            return(new TransactionInput(type, encodedInput, ContractAddress, from, gas, value, maxFeePerGas, maxPriorityFeePerGas));
        }