예제 #1
0
        /// <summary>
        /// Internal helper function implementing the file delete functionality.
        /// </summary>
        public async Task <TResult> SystemRestoreFileImplementationAsync <TResult>(Address fileToRestore, Signatory?signatory, Action <IContext>?configure = null) where TResult : new()
        {
            fileToRestore           = RequireInputParameter.FileToRestore(fileToRestore);
            await using var context = CreateChildContext(configure);
            RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatories     = Transactions.GatherSignatories(context, signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = new TransactionBody(context, transactionId);

            transactionBody.SystemUndelete = new SystemUndeleteTransactionBody
            {
                FileID = new FileID(fileToRestore)
            };
            var receipt = await transactionBody.SignAndExecuteWithRetryAsync(signatories, context);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to delete file, status: {receipt.Status}", transactionId.ToTxId(), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                record.FillProperties(rec);
            }
            else if (result is TransactionReceipt rcpt)
            {
                receipt.FillProperties(transactionId, rcpt);
            }
            return(result);
        }
예제 #2
0
        /// <summary>
        /// Retrieves the account records associated with an account that are presently
        /// held within the network.
        /// </summary>
        /// <param name="address">
        /// The Hedera Network Address to retrieve associated records.
        /// </param>
        /// <param name="configure">
        /// Optional callback method providing an opportunity to modify
        /// the execution configuration for just this method call.
        /// It is executed prior to submitting the request to the network.
        /// </param>
        /// <returns>
        /// A detailed description of the account.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">If required arguments are missing.</exception>
        /// <exception cref="InvalidOperationException">If required context configuration is missing.</exception>
        /// <exception cref="PrecheckException">If the gateway node create rejected the request upon submission.</exception>
        public async Task <TransactionRecord[]> GetAccountRecordsAsync(Address address, Action <IContext>?configure = null)
        {
            address = RequireInputParameter.Address(address);
            var context         = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transfers       = Transactions.CreateCryptoTransferList((payer, -context.FeeLimit), (gateway, context.FeeLimit));
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateCryptoTransferTransactionBody(context, transfers, transactionId, "Get Account Records");
            var query           = new Query
            {
                CryptoGetAccountRecords = new CryptoGetAccountRecordsQuery
                {
                    Header    = Transactions.SignQueryHeader(transactionBody, payer),
                    AccountID = Protobuf.ToAccountID(address)
                }
            };
            var response = await Transactions.ExecuteRequestWithRetryAsync(context, query, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, getResponseCode(response));
            return(response.CryptoGetAccountRecords.Records.Select(record =>
            {
                var result = new TransactionRecord();
                Protobuf.FillRecordProperties(record, result);
                return result;
            }).ToArray());
        /// <summary>
        /// Retrieves the network address associated with the specified smart contract id.
        /// </summary>
        /// <param name="smartContractId">
        /// The smart contract ID to look up.
        /// </param>
        /// <param name="configure">
        /// Optional callback method providing an opportunity to modify
        /// the execution configuration for just this method call.
        /// It is executed prior to submitting the request to the network.
        /// </param>
        /// <returns>
        /// The network address associated with the smart contract ID.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">If required arguments are missing.</exception>
        /// <exception cref="InvalidOperationException">If required context configuration is missing.</exception>
        /// <exception cref="PrecheckException">If the gateway node create rejected the request upon submission.</exception>
        public async Task <Address> GetAddressFromSmartContractId(string smartContractId, Action <IContext>?configure = null)
        {
            smartContractId = RequireInputParameter.SmartContractId(smartContractId);
            var context         = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transfers       = Transactions.CreateCryptoTransferList((payer, -context.FeeLimit), (gateway, context.FeeLimit));
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateCryptoTransferTransactionBody(context, transfers, transactionId, "Get Contract By Solidity ID");
            var query           = new Query
            {
                GetBySolidityID = new GetBySolidityIDQuery
                {
                    Header     = Transactions.SignQueryHeader(transactionBody, payer),
                    SolidityID = smartContractId
                }
            };
            var response = await Transactions.ExecuteRequestWithRetryAsync(context, query, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, getResponseCode(response));
            var data = response.GetBySolidityID;

            if (data.ContractID != null)
            {
                return(Protobuf.FromContractID(data.ContractID));
            }
            if (data.AccountID != null)
            {
                return(Protobuf.FromAccountID(data.AccountID));
            }
            if (data.FileID != null)
            {
                return(Protobuf.FromFileID(data.FileID));
            }
            throw new TransactionException($"Address from Smart Contract ID {smartContractId} was not found.", Protobuf.FromTransactionId(transactionId), ResponseCode.Unknown);
예제 #4
0
        /// <summary>
        /// Set the period of time where the network will suspend will stop creating events
        /// and accepting transactions. This can be used to safely shut down
        /// the platform for maintenance and for upgrades if the file information is included.
        /// </summary>
        /// <param name="suspendParameters">
        /// The details of the suspend request, includes the time to wait before suspension,
        /// the duration of the suspension and optionally to include an update file.
        /// </param>
        /// <param name="configure">
        /// Optional callback method providing an opportunity to modify
        /// the execution configuration for just this method call.
        /// It is executed prior to submitting the request to the network.
        /// </param>
        /// <returns>
        /// A Submit Message Receipt indicating success.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">If required arguments are missing.</exception>
        /// <exception cref="InvalidOperationException">If required context configuration is missing.</exception>
        /// <exception cref="PrecheckException">If the gateway node create rejected the request upon submission.</exception>
        /// <exception cref="ConsensusException">If the network was unable to come to consensus before the duration of the transaction expired.</exception>
        /// <exception cref="TransactionException">If the network rejected the create request as invalid or had missing data.</exception>
        public async Task <TransactionReceipt> SuspendNetworkAsync(SuspendNetworkParams suspendParameters, Action <IContext>?configure = null)
        {
            suspendParameters       = RequireInputParameter.SuspendNetworkParams(suspendParameters);
            await using var context = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatories     = Transactions.GatherSignatories(context);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = new TransactionBody(context, transactionId);
            var startDate       = DateTime.UtcNow.Add(suspendParameters.Starting);
            var endDate         = startDate.Add(suspendParameters.Duration);

            transactionBody.Freeze = new FreezeTransactionBody
            {
                StartHour = startDate.Hour,
                StartMin  = startDate.Minute,
                EndHour   = endDate.Hour,
                EndMin    = endDate.Minute,
            };
            if (!suspendParameters.UpdateFile.IsNullOrNone())
            {
                transactionBody.Freeze.UpdateFile = new FileID(suspendParameters.UpdateFile);
                transactionBody.Freeze.FileHash   = ByteString.CopyFrom(suspendParameters.UpdateFileHash.Span);
            }
            var receipt = await transactionBody.SignAndExecuteWithRetryAsync(signatories, context);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Failed to submit suspend/freeze command, status: {receipt.Status}", transactionId.ToTxId(), (ResponseCode)receipt.Status);
            }
            return(receipt.FillProperties(transactionId, new TransactionReceipt()));
        }
예제 #5
0
        /// <summary>
        /// Internal implementation of the update Contract functionality.
        /// </summary>
        private async Task <TResult> UpdateContractImplementationAsync <TResult>(UpdateContractParams updateParameters, Action <IContext>?configure) where TResult : new()
        {
            updateParameters        = RequireInputParameter.UpdateParameters(updateParameters);
            await using var context = CreateChildContext(configure);
            RequireInContext.Gateway(context);
            var payer              = RequireInContext.Payer(context);
            var signatory          = Transactions.GatherSignatories(context, updateParameters.Signatory);
            var updateContractBody = new ContractUpdateTransactionBody
            {
                ContractID = Protobuf.ToContractID(updateParameters.Contract)
            };

            if (updateParameters.Expiration.HasValue)
            {
                updateContractBody.ExpirationTime = Protobuf.ToTimestamp(updateParameters.Expiration.Value);
            }
            if (!(updateParameters.Administrator is null))
            {
                updateContractBody.AdminKey = Protobuf.ToPublicKey(updateParameters.Administrator);
            }
            if (updateParameters.RenewPeriod.HasValue)
            {
                updateContractBody.AutoRenewPeriod = Protobuf.ToDuration(updateParameters.RenewPeriod.Value);
            }
            if (!(updateParameters.File is null))
            {
                updateContractBody.FileID = Protobuf.ToFileId(updateParameters.File);
            }
            if (!string.IsNullOrWhiteSpace(updateParameters.Memo))
            {
                updateContractBody.Memo = updateParameters.Memo;
            }
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateTransactionBody(context, transactionId);

            transactionBody.ContractUpdateInstance = updateContractBody;
            var request = await Transactions.SignTransactionAsync(transactionBody, signatory);

            var precheck = await Transactions.ExecuteSignedRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to update Contract, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord arec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, arec);
            }
            else if (result is TransactionReceipt arcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, arcpt);
            }
            return(result);
예제 #6
0
        /// <summary>
        /// Internal implementation for Multi Account Transfer Crypto.
        /// Returns either a receipt or record or throws an exception.
        /// </summary>
        private async Task <TResult> TransferImplementationAsync <TResult>(Dictionary <Account, long> sendAccounts, Dictionary <Address, long> receiveAddresses, Action <IContext>?configure) where TResult : new()
        {
            var transferList = RequireInputParameter.MultiTransfers(sendAccounts, receiveAddresses);
            var context      = CreateChildContext(configure);

            RequireInContext.Gateway(context);
            var payers          = sendAccounts.Keys.ToArray <ISigner>().Append(RequireInContext.Payer(context)).ToArray();
            var transfers       = Transactions.CreateCryptoTransferList(transferList);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateCryptoTransferTransactionBody(context, transfers, transactionId, "Transfer Crypto");
            var request         = Transactions.SignTransaction(transactionBody, payers);
            var precheck        = await Transactions.ExecuteRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck.NodeTransactionPrecheckCode);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to execute crypto transfer, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransferRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, rec);
                rec.Transfers = Protobuf.FromTransferList(record.TransferList);
            }
            else if (result is TransactionReceipt rcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, rcpt);
            }
            return(result);
예제 #7
0
        /// <summary>
        /// Internal implementation of dissociate method.
        /// </summary>
        private async Task <TResult> DissociateTokenImplementationAsync <TResult>(TokenID[] tokens, Address account, Signatory?signatory, Action <IContext>?configure) where TResult : new()
        {
            account = RequireInputParameter.Account(account);
            await using var context = CreateChildContext(configure);
            RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatories     = Transactions.GatherSignatories(context, signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = new TransactionBody(context, transactionId);

            transactionBody.TokenDissociate = new TokenDissociateTransactionBody
            {
                Account = new AccountID(account)
            };
            transactionBody.TokenDissociate.Tokens.AddRange(tokens);
            var receipt = await transactionBody.SignAndExecuteWithRetryAsync(signatories, context);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to Dissociate Token from Account, status: {receipt.Status}", transactionId.ToTxId(), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                record.FillProperties(rec);
            }
            else if (result is TransactionReceipt rcpt)
            {
                receipt.FillProperties(transactionId, rcpt);
            }
            return(result);
        }
예제 #8
0
        /// <summary>
        /// Internal Helper function to retrieve the transaction record provided
        /// by the network following network consensus regarding a query or transaction.
        /// </summary>
        private async Task <Proto.TransactionRecord> GetTransactionRecordAsync(ContextStack context, TransactionID transactionRecordId)
        {
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transfers       = Transactions.CreateCryptoTransferList((payer, -context.FeeLimit), (gateway, context.FeeLimit));
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateCryptoTransferTransactionBody(context, transfers, transactionId, "Get Transaction Record");
            var query           = new Query
            {
                TransactionGetRecord = new TransactionGetRecordQuery
                {
                    Header        = Transactions.SignQueryHeader(transactionBody, payer),
                    TransactionID = transactionRecordId
                }
            };
            var response = await Transactions.ExecuteRequestWithRetryAsync(context, query, getServerMethod, getResponseCode);

            var responseCode = getResponseCode(response);

            if (responseCode != ResponseCodeEnum.Ok)
            {
                throw new TransactionException("Unable to retrieve transaction record.", Protobuf.FromTransactionId(transactionRecordId), (ResponseCode)responseCode);
            }
            ValidateResult.PreCheck(transactionId, getResponseCode(response));
            return(response.TransactionGetRecord.TransactionRecord);
예제 #9
0
        /// <summary>
        /// Deletes a contract instance from the network returning the remaining
        /// crypto balance to the specified address.  Must be signed
        /// by the admin key.
        /// </summary>
        /// <param name="contractToDelete">
        /// The Contract instance that will be deleted.
        /// </param>
        /// <param name="transferToAddress">
        /// The address that will receive any remaining balance from the deleted Contract.
        /// </param>
        /// <param name="configure">
        /// Optional callback method providing an opportunity to modify
        /// the execution configuration for just this method call.
        /// It is executed prior to submitting the request to the network.
        /// </param>
        /// <returns>
        /// A transaction receipt indicating a successful operation.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">If required arguments are missing.</exception>
        /// <exception cref="InvalidOperationException">If required context configuration is missing.</exception>
        /// <exception cref="PrecheckException">If the gateway node create rejected the request upon submission.</exception>
        /// <exception cref="ConsensusException">If the network was unable to come to consensus before the duration of the transaction expired.</exception>
        /// <exception cref="TransactionException">If the network rejected the create request as invalid or had missing data.</exception>
        public async Task <TransactionReceipt> DeleteContractAsync(Address contractToDelete, Address transferToAddress, Action <IContext>?configure = null)
        {
            contractToDelete  = RequireInputParameter.ContractToDelete(contractToDelete);
            transferToAddress = RequireInputParameter.TransferToAddress(transferToAddress);
            var context = CreateChildContext(configure);

            RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateEmptyTransactionBody(context, transactionId, "Delete Contract");

            transactionBody.ContractDeleteInstance = new ContractDeleteTransactionBody
            {
                ContractID        = Protobuf.ToContractID(contractToDelete),
                TransferAccountID = Protobuf.ToAccountID(transferToAddress)
            };
            var request  = Transactions.SignTransaction(transactionBody, payer);
            var precheck = await Transactions.ExecuteRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck.NodeTransactionPrecheckCode);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to delete contract, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TransactionReceipt();

            Protobuf.FillReceiptProperties(transactionId, receipt, result);
            return(result);
예제 #10
0
        /// <summary>
        /// Internal implementation of delete topic method.
        /// </summary>
        private async Task <TransactionReceipt> DeleteTopicImplementationAsync(Address topicToDelete, Signatory?signatory, Action <IContext>?configure)
        {
            topicToDelete           = RequireInputParameter.AddressToDelete(topicToDelete);
            await using var context = CreateChildContext(configure);
            RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatories     = Transactions.GatherSignatories(context, signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateTransactionBody(context, transactionId);

            transactionBody.ConsensusDeleteTopic = new ConsensusDeleteTopicTransactionBody
            {
                TopicID = Protobuf.ToTopicID(topicToDelete)
            };
            var request = await Transactions.SignTransactionAsync(transactionBody, signatories);

            var precheck = await Transactions.ExecuteSignedRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to Delete Topic, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TransactionReceipt();

            Protobuf.FillReceiptProperties(transactionId, receipt, result);
            return(result);
예제 #11
0
 internal TransactionBody(GossipContextStack context, TransactionID transactionId)
 {
     OnConstruction();
     TransactionID = transactionId;
     NodeAccountID = new AccountID(RequireInContext.Gateway(context));
     TransactionFee = (ulong)context.FeeLimit;
     TransactionValidDuration = new Proto.Duration(context.TransactionDuration);
     Memo = context.Memo ?? "";
 }
예제 #12
0
        /// <summary>
        /// Internal implementation of the update account functionality.
        /// </summary>
        private async Task <TResult> UpdateAccountImplementationAsync <TResult>(UpdateAccountParams updateParameters, Action <IContext>?configure) where TResult : new()
        {
            updateParameters        = RequireInputParameter.UpdateParameters(updateParameters);
            await using var context = CreateChildContext(configure);
            RequireInContext.Gateway(context);
            var payer             = RequireInContext.Payer(context);
            var updateAccountBody = new CryptoUpdateTransactionBody
            {
                AccountIDToUpdate = new AccountID(updateParameters.Address)
            };

            if (!(updateParameters.Endorsement is null))
            {
                updateAccountBody.Key = new Key(updateParameters.Endorsement);
            }
            if (updateParameters.RequireReceiveSignature.HasValue)
            {
                updateAccountBody.ReceiverSigRequiredWrapper = updateParameters.RequireReceiveSignature.Value;
            }
            if (updateParameters.AutoRenewPeriod.HasValue)
            {
                updateAccountBody.AutoRenewPeriod = new Duration(updateParameters.AutoRenewPeriod.Value);
            }
            if (updateParameters.Expiration.HasValue)
            {
                updateAccountBody.ExpirationTime = new Timestamp(updateParameters.Expiration.Value);
            }
            if (!(updateParameters.Proxy is null))
            {
                updateAccountBody.ProxyAccountID = new AccountID(updateParameters.Proxy);
            }
            var signatory       = Transactions.GatherSignatories(context, updateParameters.Signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = new TransactionBody(context, transactionId);

            transactionBody.CryptoUpdateAccount = updateAccountBody;
            var receipt = await transactionBody.SignAndExecuteWithRetryAsync(signatory, context);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to update account, status: {receipt.Status}", transactionId.ToTxId(), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                record.FillProperties(rec);
            }
            else if (result is TransactionReceipt rcpt)
            {
                receipt.FillProperties(transactionId, rcpt);
            }
            return(result);
        }
예제 #13
0
        /// <summary>
        /// Internal implementation of the update Topic functionality.
        /// </summary>
        private async Task <TResult> UpdateTopicImplementationAsync <TResult>(UpdateTopicParams updateParameters, Action <IContext>?configure) where TResult : new()
        {
            updateParameters        = RequireInputParameter.UpdateParameters(updateParameters);
            await using var context = CreateChildContext(configure);
            RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatory       = Transactions.GatherSignatories(context, updateParameters.Signatory);
            var updateTopicBody = new ConsensusUpdateTopicTransactionBody
            {
                TopicID = new TopicID(updateParameters.Topic)
            };

            if (updateParameters.Memo != null)
            {
                updateTopicBody.Memo = updateParameters.Memo;
            }
            if (!(updateParameters.Administrator is null))
            {
                updateTopicBody.AdminKey = new Key(updateParameters.Administrator);
            }
            if (!(updateParameters.Participant is null))
            {
                updateTopicBody.SubmitKey = new Key(updateParameters.Participant);
            }
            if (updateParameters.RenewPeriod.HasValue)
            {
                updateTopicBody.AutoRenewPeriod = new Duration(updateParameters.RenewPeriod.Value);
            }
            if (!(updateParameters.RenewAccount is null))
            {
                updateTopicBody.AutoRenewAccount = new AccountID(updateParameters.RenewAccount);
            }
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = new TransactionBody(context, transactionId);

            transactionBody.ConsensusUpdateTopic = updateTopicBody;
            var receipt = await transactionBody.SignAndExecuteWithRetryAsync(signatory, context);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to update Topic, status: {receipt.Status}", transactionId.ToTxId(), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                record.FillProperties(rec);
            }
            else if (result is TransactionReceipt rcpt)
            {
                receipt.FillProperties(transactionId, rcpt);
            }
            return(result);
        }
예제 #14
0
        /// <summary>
        /// Internal implementation of the submit message call.
        /// </summary>
        private async Task <TResult> SubmitUnsafeTransactionImplementationAsync <TResult>(ReadOnlyMemory <byte> transaction, Action <IContext>?configure) where TResult : new()
        {
            var innerTransactionId = RequireInputParameter.IdFromTransactionBytes(transaction);

            await using var context = CreateChildContext(configure);
            var gateway            = RequireInContext.Gateway(context);
            var payer              = RequireInContext.Payer(context);
            var signatories        = Transactions.GatherSignatories(context);
            var outerTransactionId = Transactions.GetOrCreateTransactionID(context);
            // Note: custom transaction body, does not carry a max fee since
            // the inner transaction is the transaction to process, it still
            // must be signed however.
            var transactionBody = new TransactionBody
            {
                TransactionID            = outerTransactionId,
                NodeAccountID            = new AccountID(RequireInContext.Gateway(context)),
                TransactionValidDuration = new Proto.Duration(context.TransactionDuration),
                UncheckedSubmit          = new UncheckedSubmitBody {
                    TransactionBytes = ByteString.CopyFrom(transaction.Span)
                }
            };
            var precheck = await transactionBody.SignAndSubmitWithRetryAsync(signatories, context);

            ValidateResult.PreCheck(outerTransactionId, precheck);
            // NOTE: The outer transaction ID exists so that the administrative account has something to sign that
            // can be verified, however, the transaction never actually exists in the system so there will never be
            // a receipt for this submission, however, there will be an attempt to execute the submitted transaction
            // as this method bypasses PRECHECK validations.  So, there will be a receipt for the inner traction, with
            // success or a failure code.  Therefore we return the receipt or record for the custom transaction.
            var receipt = await Transactions.GetReceiptAsync(context, innerTransactionId);

            // Retain standard behavior of throwing an exception if the receipt has an error code.
            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Submit Unsafe Transaction failed, status: {receipt.Status}", innerTransactionId.ToTxId(), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, innerTransactionId);

                record.FillProperties(rec);
            }
            else if (result is TransactionReceipt rcpt)
            {
                receipt.FillProperties(innerTransactionId, rcpt);
            }
            return(result);
        }
예제 #15
0
        /// <summary>
        /// Internal implementation for Create Account
        /// Returns either a receipt or record or throws
        /// an exception.
        /// </summary>
        private async Task <TResult> CreateAccountImplementationAsync <TResult>(CreateAccountParams createParameters, Action <IContext>?configure) where TResult : new()
        {
            createParameters = RequireInputParameter.CreateParameters(createParameters);
            var context = CreateChildContext(configure);

            RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateEmptyTransactionBody(context, transactionId, "Create Account");
            // Create Account requires just the 32 bits of the public key, without the prefix.
            var publicKeyWithoutPrefix = Keys.ImportPublicEd25519KeyFromBytes(createParameters.PublicKey).Export(KeyBlobFormat.PkixPublicKey).TakeLast(32).ToArray();

            transactionBody.CryptoCreateAccount = new CryptoCreateTransactionBody
            {
                Key = new Proto.Key {
                    Ed25519 = ByteString.CopyFrom(publicKeyWithoutPrefix)
                },
                InitialBalance         = createParameters.InitialBalance,
                SendRecordThreshold    = createParameters.SendThresholdCreateRecord,
                ReceiveRecordThreshold = createParameters.ReceiveThresholdCreateRecord,
                ReceiverSigRequired    = createParameters.RequireReceiveSignature,
                AutoRenewPeriod        = Protobuf.ToDuration(createParameters.AutoRenewPeriod),
            };
            var request  = Transactions.SignTransaction(transactionBody, payer);
            var precheck = await Transactions.ExecuteRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck.NodeTransactionPrecheckCode);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to create account, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is AccountReceipt arcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, arcpt);
                arcpt.Address = Protobuf.FromAccountID(receipt.AccountID);
            }
            else if (result is AccountRecord arec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, arec);
                arec.Address = Protobuf.FromAccountID(receipt.AccountID);
            }
            return(result);
예제 #16
0
        /// <summary>
        /// Internal helper method implementing the file update service.
        /// </summary>
        public async Task <TResult> UpdateFileImplementationAsync <TResult>(UpdateFileParams updateParameters, Action <IContext>?configure) where TResult : new()
        {
            updateParameters        = RequireInputParameter.UpdateParameters(updateParameters);
            await using var context = CreateChildContext(configure);
            RequireInContext.Gateway(context);
            var payer          = RequireInContext.Payer(context);
            var signatory      = Transactions.GatherSignatories(context, updateParameters.Signatory);
            var updateFileBody = new FileUpdateTransactionBody
            {
                FileID = Protobuf.ToFileId(updateParameters.File)
            };

            if (!(updateParameters.Endorsements is null))
            {
                updateFileBody.Keys = Protobuf.ToPublicKeyList(updateParameters.Endorsements);
            }
            if (updateParameters.Contents.HasValue)
            {
                updateFileBody.Contents = ByteString.CopyFrom(updateParameters.Contents.Value.ToArray());
            }
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateTransactionBody(context, transactionId);

            transactionBody.FileUpdate = updateFileBody;
            var request = await Transactions.SignTransactionAsync(transactionBody, signatory);

            var precheck = await Transactions.ExecuteSignedRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to update file, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, rec);
            }
            else if (result is TransactionReceipt rcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, rcpt);
            }
            return(result);
예제 #17
0
        /// <summary>
        /// Internal implementation of the Create Token service.
        /// </summary>
        private async Task <TResult> CreateTokenImplementationAsync <TResult>(CreateTokenParams createParameters, Action <IContext>?configure) where TResult : new()
        {
            createParameters        = RequireInputParameter.CreateParameters(createParameters);
            await using var context = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatory       = Transactions.GatherSignatories(context, createParameters.Signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = new TransactionBody(context, transactionId);

            transactionBody.TokenCreation = new TokenCreateTransactionBody
            {
                Name             = createParameters.Name,
                Symbol           = createParameters.Symbol,
                InitialSupply    = createParameters.Circulation,
                Decimals         = createParameters.Decimals,
                Treasury         = new AccountID(createParameters.Treasury),
                AdminKey         = createParameters.Administrator.IsNullOrNone() ? null : new Key(createParameters.Administrator),
                KycKey           = createParameters.GrantKycEndorsement.IsNullOrNone() ? null : new Key(createParameters.GrantKycEndorsement),
                FreezeKey        = createParameters.SuspendEndorsement.IsNullOrNone() ? null : new Key(createParameters.SuspendEndorsement),
                WipeKey          = createParameters.ConfiscateEndorsement.IsNullOrNone() ? null : new Key(createParameters.ConfiscateEndorsement),
                SupplyKey        = createParameters.SupplyEndorsement.IsNullOrNone() ? null : new Key(createParameters.SupplyEndorsement),
                FreezeDefault    = createParameters.InitializeSuspended,
                Expiry           = new Timestamp(createParameters.Expiration),
                AutoRenewAccount = createParameters.RenewAccount.IsNullOrNone() ? null : new AccountID(createParameters.RenewAccount),
                AutoRenewPeriod  = createParameters.RenewPeriod.HasValue ? new Duration(createParameters.RenewPeriod.Value) : null
            };
            var receipt = await transactionBody.SignAndExecuteWithRetryAsync(signatory, context);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to create Token, status: {receipt.Status}", transactionId.ToTxId(), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is CreateTokenRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                record.FillProperties(rec);
            }
            else if (result is CreateTokenReceipt rcpt)
            {
                receipt.FillProperties(transactionId, rcpt);
            }
            return(result);
        }
예제 #18
0
        /// <summary>
        /// Internal implementation for Create Account
        /// Returns either a receipt or record or throws
        /// an exception.
        /// </summary>
        private async Task <TResult> CreateAccountImplementationAsync <TResult>(CreateAccountParams createParameters, Action <IContext>?configure) where TResult : new()
        {
            var publicKey = RequireInputParameter.KeysFromEndorsements(createParameters);

            await using var context = CreateChildContext(configure);
            RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatories     = Transactions.GatherSignatories(context, createParameters.Signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateTransactionBody(context, transactionId);

            transactionBody.CryptoCreateAccount = new CryptoCreateTransactionBody
            {
                Key                    = publicKey,
                InitialBalance         = createParameters.InitialBalance,
                SendRecordThreshold    = createParameters.SendThresholdCreateRecord,
                ReceiveRecordThreshold = createParameters.ReceiveThresholdCreateRecord,
                ReceiverSigRequired    = createParameters.RequireReceiveSignature,
                AutoRenewPeriod        = Protobuf.ToDuration(createParameters.AutoRenewPeriod),
                ProxyAccountID         = createParameters.Proxy is null ? null : Protobuf.ToAccountID(createParameters.Proxy),
            };
            var request = await Transactions.SignTransactionAsync(transactionBody, signatories);

            var precheck = await Transactions.ExecuteSignedRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to create account, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is CreateAccountRecord arec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, arec);
                arec.Address = Protobuf.FromAccountID(receipt.AccountID);
            }
            else if (result is CreateAccountReceipt arcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, arcpt);
                arcpt.Address = Protobuf.FromAccountID(receipt.AccountID);
            }
            return(result);
예제 #19
0
        /// <summary>
        /// Internal Create Contract Implementation
        /// </summary>
        public async Task <TResult> CreateContractImplementationAsync <TResult>(CreateContractParams createParameters, Action <IContext>?configure) where TResult : new()
        {
            createParameters        = RequireInputParameter.CreateParameters(createParameters);
            await using var context = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatory       = Transactions.GatherSignatories(context, createParameters.Signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateTransactionBody(context, transactionId);

            transactionBody.ContractCreateInstance = new ContractCreateTransactionBody
            {
                FileID                = Protobuf.ToFileId(createParameters.File),
                AdminKey              = createParameters.Administrator is null ? null : Protobuf.ToPublicKey(createParameters.Administrator),
                Gas                   = createParameters.Gas,
                InitialBalance        = createParameters.InitialBalance,
                AutoRenewPeriod       = Protobuf.ToDuration(createParameters.RenewPeriod),
                ConstructorParameters = ByteString.CopyFrom(Abi.EncodeArguments(createParameters.Arguments).ToArray()),
                Memo                  = context.Memo ?? ""
            };
            var request = await Transactions.SignTransactionAsync(transactionBody, signatory);

            var precheck = await Transactions.ExecuteSignedRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to create contract, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is CreateContractRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, rec);
                rec.Contract = Protobuf.FromContractID(receipt.ContractID);
            }
            else if (result is CreateContractReceipt rcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, rcpt);
                rcpt.Contract = Protobuf.FromContractID(receipt.ContractID);
            }
            return(result);
예제 #20
0
        /// <summary>
        /// Internal implementation of the contract call method.
        /// </summary>
        private async Task <TResult> SubmitMessageImplementationAsync <TResult>(Address topic, ReadOnlyMemory <byte> message, Signatory?signatory, Action <IContext>?configure) where TResult : new()
        {
            topic   = RequireInputParameter.Topic(topic);
            message = RequireInputParameter.Message(message);
            await using var context = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatories     = Transactions.GatherSignatories(context, signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateTransactionBody(context, transactionId);

            transactionBody.ConsensusSubmitMessage = new ConsensusSubmitMessageTransactionBody
            {
                TopicID = Protobuf.ToTopicID(topic),
                Message = ByteString.CopyFrom(message.Span)
            };
            var request = await Transactions.SignTransactionAsync(transactionBody, signatories);

            var precheck = await Transactions.ExecuteSignedRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Submit Message failed, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is SubmitMessageRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, rec);
                rec.RunningHash    = receipt.TopicRunningHash?.ToByteArray();
                rec.SequenceNumber = receipt.TopicSequenceNumber;
            }
            else if (result is SubmitMessageReceipt rcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, rcpt);
                rcpt.RunningHash    = receipt.TopicRunningHash?.ToByteArray();
                rcpt.SequenceNumber = receipt.TopicSequenceNumber;
            }
            return(result);
예제 #21
0
        /// <summary>
        /// Internal helper method implementing the file update service.
        /// </summary>
        public async Task <TResult> UpdateFileImplementationAsync <TResult>(UpdateFileParams updateParameters, Action <IContext>?configure) where TResult : new()
        {
            updateParameters        = RequireInputParameter.UpdateParameters(updateParameters);
            await using var context = CreateChildContext(configure);
            RequireInContext.Gateway(context);
            var payer          = RequireInContext.Payer(context);
            var signatory      = Transactions.GatherSignatories(context, updateParameters.Signatory);
            var updateFileBody = new FileUpdateTransactionBody
            {
                FileID = new FileID(updateParameters.File)
            };

            if (!(updateParameters.Endorsements is null))
            {
                updateFileBody.Keys = new KeyList(updateParameters.Endorsements);
            }
            if (updateParameters.Contents.HasValue)
            {
                updateFileBody.Contents = ByteString.CopyFrom(updateParameters.Contents.Value.ToArray());
            }
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = new TransactionBody(context, transactionId);

            transactionBody.FileUpdate = updateFileBody;
            var receipt = await transactionBody.SignAndExecuteWithRetryAsync(signatory, context);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to update file, status: {receipt.Status}", transactionId.ToTxId(), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                record.FillProperties(rec);
            }
            else if (result is TransactionReceipt rcpt)
            {
                receipt.FillProperties(transactionId, rcpt);
            }
            return(result);
        }
예제 #22
0
        /// <summary>
        /// Internal implementation of the Create ConsensusTopic service.
        /// </summary>
        private async Task <TResult> CreateTopicImplementationAsync <TResult>(CreateTopicParams createParameters, Action <IContext>?configure) where TResult : new()
        {
            createParameters        = RequireInputParameter.CreateParameters(createParameters);
            await using var context = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatory       = Transactions.GatherSignatories(context, createParameters.Signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateTransactionBody(context, transactionId);

            transactionBody.ConsensusCreateTopic = new ConsensusCreateTopicTransactionBody
            {
                Memo             = createParameters.Memo,
                AdminKey         = createParameters.Administrator is null ? null : Protobuf.ToPublicKey(createParameters.Administrator),
                SubmitKey        = createParameters.Participant is null ? null : Protobuf.ToPublicKey(createParameters.Participant),
                AutoRenewPeriod  = Protobuf.ToDuration(createParameters.RenewPeriod),
                AutoRenewAccount = createParameters.RenewAccount is null ? null : Protobuf.ToAccountID(createParameters.RenewAccount)
            };
            var request = await Transactions.SignTransactionAsync(transactionBody, signatory);

            var precheck = await Transactions.ExecuteSignedRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to create Consensus Topic, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is CreateTopicRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, rec);
                rec.Topic = Protobuf.FromTopicID(receipt.TopicID);
            }
            else if (result is CreateTopicReceipt rcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, rcpt);
                rcpt.Topic = Protobuf.FromTopicID(receipt.TopicID);
            }
            return(result);
예제 #23
0
        /// <summary>
        /// Internal implementation of the Create File service.
        /// </summary>
        public async Task <TResult> CreateFileImplementationAsync <TResult>(CreateFileParams createParameters, Action <IContext>?configure) where TResult : new()
        {
            createParameters        = RequireInputParameter.CreateParameters(createParameters);
            await using var context = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var signatory       = Transactions.GatherSignatories(context, createParameters.Signatory);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateTransactionBody(context, transactionId);

            transactionBody.FileCreate = new FileCreateTransactionBody
            {
                ExpirationTime = Protobuf.ToTimestamp(createParameters.Expiration),
                Keys           = Protobuf.ToPublicKeyList(createParameters.Endorsements),
                Contents       = ByteString.CopyFrom(createParameters.Contents.ToArray()),
            };
            var request = await Transactions.SignTransactionAsync(transactionBody, signatory);

            var precheck = await Transactions.ExecuteSignedRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to create file, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is FileRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, rec);
                rec.File = Protobuf.FromFileID(receipt.FileID);
            }
            else if (result is FileReceipt rcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, rcpt);
                rcpt.File = Protobuf.FromFileID(receipt.FileID);
            }
            return(result);
예제 #24
0
        /// <summary>
        /// Internal implementation of the Add Claim service.
        /// </summary>
        public async Task <TResult> AddClaimImplementationAsync <TResult>(Claim claim, Action <IContext>?configure) where TResult : new()
        {
            claim = RequireInputParameter.AddParameters(claim);
            var context         = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateEmptyTransactionBody(context, transactionId, "Add Claim");

            transactionBody.CryptoAddClaim = new CryptoAddClaimTransactionBody
            {
                Claim = new Proto.Claim
                {
                    AccountID     = Protobuf.ToAccountID(claim.Address),
                    Hash          = ByteString.CopyFrom(claim.Hash.ToArray()),
                    Keys          = Protobuf.ToPublicKeyList(claim.Endorsements),
                    ClaimDuration = Protobuf.ToDuration(claim.ClaimDuration)
                }
            };
            var request  = Transactions.SignTransaction(transactionBody, payer);
            var precheck = await Transactions.ExecuteRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck.NodeTransactionPrecheckCode);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to attach claim, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, rec);
            }
            else if (result is TransactionReceipt rcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, rcpt);
            }
            return(result);
예제 #25
0
        /// <summary>
        /// Internal implementation of the contract call method.
        /// </summary>
        private async Task <TResult> CallContractImplementationAsync <TResult>(CallContractParams callParmeters, Action <IContext>?configure) where TResult : new()
        {
            callParmeters = RequireInputParameter.CallContractParameters(callParmeters);
            var context         = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateEmptyTransactionBody(context, transactionId, "Call Contract");

            transactionBody.ContractCall = new ContractCallTransactionBody
            {
                ContractID         = Protobuf.ToContractID(callParmeters.Contract),
                Gas                = callParmeters.Gas,
                Amount             = callParmeters.PayableAmount,
                FunctionParameters = Abi.EncodeFunctionWithArguments(callParmeters.FunctionName, callParmeters.FunctionArgs).ToByteString()
            };
            var request  = Transactions.SignTransaction(transactionBody, payer);
            var precheck = await Transactions.ExecuteRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck.NodeTransactionPrecheckCode);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Contract call failed, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is CallContractRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, rec);
                rec.Contract   = Protobuf.FromContractID(record.Receipt.ContractID);
                rec.CallResult = Protobuf.FromContractCallResult(record.ContractCallResult);
            }
            else if (result is ContractReceipt rcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, rcpt);
                rcpt.Contract = Protobuf.FromContractID(receipt.ContractID);
            }
            return(result);
예제 #26
0
        /// <summary>
        /// Retrieves the bytecode for the specified contract.
        /// </summary>
        /// <param name="contract">
        /// The Hedera Network Address of the Contract.
        /// </param>
        /// <param name="configure">
        /// Optional callback method providing an opportunity to modify
        /// the execution configuration for just this method call.
        /// It is executed prior to submitting the request to the network.
        /// </param>
        /// <returns>
        /// The bytecode for the specified contract instance.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">If required arguments are missing.</exception>
        /// <exception cref="InvalidOperationException">If required context configuration is missing.</exception>
        /// <exception cref="PrecheckException">If the gateway node create rejected the request upon submission.</exception>
        public async Task <ReadOnlyMemory <byte> > GetContractBytecodeAsync(Address contract, Action <IContext>?configure = null)
        {
            contract = RequireInputParameter.Contract(contract);
            var context         = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transfers       = Transactions.CreateCryptoTransferList((payer, -context.FeeLimit), (gateway, context.FeeLimit));
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateCryptoTransferTransactionBody(context, transfers, transactionId, "Get Contract Bytecode");
            var query           = new Query
            {
                ContractGetBytecode = new ContractGetBytecodeQuery
                {
                    Header     = Transactions.SignQueryHeader(transactionBody, payer),
                    ContractID = Protobuf.ToContractID(contract)
                }
            };
            var response = await Transactions.ExecuteRequestWithRetryAsync(context, query, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, getResponseCode(response));
            return(response.ContractGetBytecodeResponse.Bytecode.ToByteArray());
예제 #27
0
        /// <summary>
        /// Retrieves the balance in tinybars from the network for a given address.
        /// </summary>
        /// <param name="address">
        /// The hedera network address to retrieve the balance of.
        /// </param>
        /// <param name="configure">
        /// Optional callback method providing an opportunity to modify
        /// the execution configuration for just this method call.
        /// It is executed prior to submitting the request to the network.
        /// </param>
        /// <returns>
        /// The balance of the associated address.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">If required arguments are missing.</exception>
        /// <exception cref="InvalidOperationException">If required context configuration is missing.</exception>
        /// <exception cref="PrecheckException">If the gateway node create rejected the request upon submission.</exception>
        public async Task <ulong> GetAccountBalanceAsync(Address address, Action <IContext>?configure = null)
        {
            address = RequireInputParameter.Address(address);
            var context         = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transfers       = Transactions.CreateCryptoTransferList((payer, -context.FeeLimit), (gateway, context.FeeLimit));
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateCryptoTransferTransactionBody(context, transfers, transactionId, "Get Account Balance");
            var query           = new Query
            {
                CryptogetAccountBalance = new CryptoGetAccountBalanceQuery
                {
                    Header    = Transactions.SignQueryHeader(transactionBody, payer),
                    AccountID = Protobuf.ToAccountID(address)
                }
            };
            var response = await Transactions.ExecuteRequestWithRetryAsync(context, query, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, getResponseCode(response));
            return(response.CryptogetAccountBalance.Balance);
예제 #28
0
        /// <summary>
        /// Retreives the accounts that are proxy staking to this account.
        /// </summary>
        /// <param name="address">
        /// The Hedera Network Address to retrieve the stakers of.
        /// </param>
        /// <param name="configure">
        /// Optional callback method providing an opportunity to modify
        /// the execution configuration for just this method call.
        /// It is executed prior to submitting the request to the network.
        /// </param>
        /// <returns>
        /// A dictionary mapping account addresses to the amount of stake.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">If required arguments are missing.</exception>
        /// <exception cref="InvalidOperationException">If required context configuration is missing.</exception>
        /// <exception cref="PrecheckException">If the gateway node create rejected the request upon submission.</exception>
        // NOTE: Marked internal at this point because it is not yet implemented by the network
        internal async Task <Dictionary <Address, long> > GetStakers(Address address, Action <IContext>?configure = null)
        {
            address = RequireInputParameter.Address(address);
            var context         = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transfers       = Transactions.CreateCryptoTransferList((payer, -context.FeeLimit), (gateway, context.FeeLimit));
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateCryptoTransferTransactionBody(context, transfers, transactionId, "Get Account Info");
            var query           = new Query
            {
                CryptoGetProxyStakers = new CryptoGetStakersQuery
                {
                    Header    = Transactions.SignQueryHeader(transactionBody, payer),
                    AccountID = Protobuf.ToAccountID(address)
                }
            };
            var response = await Transactions.ExecuteRequestWithRetryAsync(context, query, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, getResponseCode(response));
            return(response.CryptoGetProxyStakers.Stakers.ProxyStaker.ToDictionary(ps => Protobuf.FromAccountID(ps.AccountID), ps => ps.Amount));
예제 #29
0
        /// <summary>
        /// Retrieves the details regarding a file stored on the network.
        /// </summary>
        /// <param name="file">
        /// Address of the file to query.
        /// </param>
        /// <param name="configure">
        /// Optional callback method providing an opportunity to modify
        /// the execution configuration for just this method call.
        /// It is executed prior to submitting the request to the network.
        /// </param>
        /// <returns>
        /// The details of the network file, excluding content.
        /// </returns>
        /// <exception cref="ArgumentOutOfRangeException">If required arguments are missing.</exception>
        /// <exception cref="InvalidOperationException">If required context configuration is missing.</exception>
        /// <exception cref="PrecheckException">If the gateway node create rejected the request upon submission.</exception>
        public async Task <FileInfo> GetFileInfoAsync(Address file, Action <IContext>?configure = null)
        {
            file = RequireInputParameter.File(file);
            var context         = CreateChildContext(configure);
            var gateway         = RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transfers       = Transactions.CreateCryptoTransferList((payer, -context.FeeLimit), (gateway, context.FeeLimit));
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateCryptoTransferTransactionBody(context, transfers, transactionId, "Get File Info");
            var query           = new Query
            {
                FileGetInfo = new FileGetInfoQuery
                {
                    Header = Transactions.SignQueryHeader(transactionBody, payer),
                    FileID = Protobuf.ToFileId(file)
                }
            };
            var response = await Transactions.ExecuteRequestWithRetryAsync(context, query, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, getResponseCode(response));
            return(Protobuf.FromFileInfo(response.FileGetInfo.FileInfo));
예제 #30
0
        /// <summary>
        /// Internal implementation of the Delete Claim Methods
        /// </summary>
        public async Task <TResult> DeleteClaimImplementationAsync <TResult>(Address address, ReadOnlyMemory <byte> hash, Action <IContext>?configure = null) where TResult : new()
        {
            address = RequireInputParameter.Address(address);
            hash    = RequireInputParameter.Hash(hash);
            var context = CreateChildContext(configure);

            RequireInContext.Gateway(context);
            var payer           = RequireInContext.Payer(context);
            var transactionId   = Transactions.GetOrCreateTransactionID(context);
            var transactionBody = Transactions.CreateEmptyTransactionBody(context, transactionId, "Delete Claim");

            transactionBody.CryptoDeleteClaim = new CryptoDeleteClaimTransactionBody
            {
                AccountIDToDeleteFrom = Protobuf.ToAccountID(address),
                HashToDelete          = ByteString.CopyFrom(hash.ToArray())
            };
            var request  = Transactions.SignTransaction(transactionBody, payer);
            var precheck = await Transactions.ExecuteRequestWithRetryAsync(context, request, getRequestMethod, getResponseCode);

            ValidateResult.PreCheck(transactionId, precheck.NodeTransactionPrecheckCode);
            var receipt = await GetReceiptAsync(context, transactionId);

            if (receipt.Status != ResponseCodeEnum.Success)
            {
                throw new TransactionException($"Unable to remove Claim, status: {receipt.Status}", Protobuf.FromTransactionId(transactionId), (ResponseCode)receipt.Status);
            }
            var result = new TResult();

            if (result is TransactionRecord rec)
            {
                var record = await GetTransactionRecordAsync(context, transactionId);

                Protobuf.FillRecordProperties(record, rec);
            }
            else if (result is TransactionReceipt rcpt)
            {
                Protobuf.FillReceiptProperties(transactionId, receipt, rcpt);
            }
            return(result);