Example #1
0
        public static async Task CancelOrderDemo(SwitcheoRestService switcheoService,
                                                 AccountSignerTransactionManager accountSigner)
        {
            var cancelRequest = await switcheoService.PrepareCancelOrder("69c60da5-5832-4705-8390-de4bb4ed62c5");

            // turn into json
            var signableParams = JsonConvert.SerializeObject(cancelRequest);
            // serialize request params
            var serializedParams = SwitcheoHelper.PrepareParametersRequest(signableParams);
            // signs the serialized params
            var signature = accountSigner.SignMessage(serializedParams);

            // adds the 'address' and 'signature' fields to the json
            var apiParams = SwitcheoHelper.AddTransactFields(signableParams, signature,
                                                             accountSigner.AddressScriptHash.ToString().Remove(0, 2));

            // sends the 'create cancellation' request
            CreateResponse response = await switcheoService.CreateCancellation(apiParams);

            Debug.WriteLine(JsonConvert.SerializeObject(response));
            // check response to make sure is what you want

            // execute cancellation
            var tx          = Transaction.FromJson(Txn.ToJson(response.Transaction));
            var depositId   = response.Id.ToString();
            var signatureTx = accountSigner.SignTransaction(tx, false).ToHexString();

            // if everything is good it should return OK
            var execute = await switcheoService.ExecuteCancellation(signatureTx, depositId);

            Debug.WriteLine(JsonConvert.SerializeObject(execute));
        }
Example #2
0
        /// <summary>
        ///     Loads the wallet from the filesystem
        /// </summary>
        /// <param name="json">The json string representing the encrypted wallet</param>
        /// <param name="passKey">The pass key to unlock the wallet</param>
        private void LoadFromKeyStore(string json, string passKey)
        {
            var keyStoreService = new KeyStoreService();
            var privateKey      = keyStoreService.DecryptKeyStoreFromJson(passKey, json);
            var key             = new EthECKey(privateKey, true);

            TransactionManager = new AccountSignerTransactionManager(null, key.GetPrivateKey(), ChainId);
        }
Example #3
0
        public static async Task OrderDemo(SwitcheoRestService switcheoService, AccountSignerTransactionManager accountSigner)
        {
            var orderRequest = await switcheoService.PrepareCreateOrder("SWTH_NEO", "buy", "0.00315200", "2050000000", true, "limit");

            // turn into json
            var signableParams = JsonConvert.SerializeObject(orderRequest);
            // serialize request params
            var serializedParams = SwitcheoHelper.PrepareParametersRequest(signableParams);
            // signs the serialized params
            var signature = accountSigner.SignMessage(serializedParams);

            // adds the 'address' and 'signature' fields to the json
            var apiParams = SwitcheoHelper.AddTransactFields(signableParams, signature,
                                                             accountSigner.AddressScriptHash.ToString().Remove(0, 2));

            // sends the 'create withdrawal' request
            OrderResponse response = await switcheoService.CreateOrder(apiParams);

            // check response to make sure is what you want
            Debug.WriteLine(JsonConvert.SerializeObject(response));

            var executeOrderDto = new ExecuteOrder();

            foreach (var responseFill in response.Fills)
            {
                var tx          = Transaction.FromJson(JsonConvert.SerializeObject(responseFill.Txn));
                var signatureTx = accountSigner.SignTransaction(tx, false).ToHexString();
                executeOrderDto.Fills.Add(responseFill.Id.ToString(), signatureTx);
            }

            foreach (var responseMakes in response.Makes)
            {
                var tx          = Transaction.FromJson(JsonConvert.SerializeObject(responseMakes.Txn));
                var signatureTx = accountSigner.SignTransaction(tx, false).ToHexString();
                executeOrderDto.Makes.Add(responseMakes.Id.ToString(), signatureTx);
            }

            ExecuteOrderResponse execute = await switcheoService.ExecuteOrder(executeOrderDto, response.Id.ToString());

            Debug.WriteLine(JsonConvert.SerializeObject(execute));
        }
Example #4
0
        public static async Task WithdrawalDemo(SwitcheoRestService switcheoService, AccountSignerTransactionManager accountSigner)
        {
            // create withdrawal DTO
            var transactObject = await switcheoService.PrepareCreateWithdrawal("neo", "SWTH", "3");

            // turn into json
            var signableParams = JsonConvert.SerializeObject(transactObject);
            // serialize request params
            var serializedParams = SwitcheoHelper.PrepareParametersRequest(signableParams);
            // signs the serialized params
            var signature = accountSigner.SignMessage(serializedParams);

            // adds the 'address' and 'signature' fields to the json
            var apiParams = SwitcheoHelper.AddTransactFields(signableParams, signature,
                                                             accountSigner.AddressScriptHash.ToString().Remove(0, 2));

            // sends the 'create withdrawal' request
            var response = await switcheoService.CreateWithdrawl(apiParams);

            Debug.WriteLine(JsonConvert.SerializeObject(response));

            // execute withdrawal
            JObject createWithdrawalResponse = JObject.Parse(response);

            createWithdrawalResponse.Remove("transaction"); // not in docs

            var executeWithdrawalDto = new ExecuteWithdrawl
            {
                Id        = new Guid(createWithdrawalResponse["id"].ToString()),
                Timestamp = await switcheoService.GetTimeStampAsync()
            };

            // serialize request params
            var serializedResponseParams = SwitcheoHelper.PrepareParametersRequest(JsonConvert.SerializeObject(executeWithdrawalDto));
            var responseSignature        = accountSigner.SignMessage(serializedResponseParams);

            WithdrawlResponse withdrawlResponse = await switcheoService.ExecuteWithdraw(executeWithdrawalDto, responseSignature);

            Debug.WriteLine(JsonConvert.SerializeObject(withdrawlResponse));
        }
Example #5
0
        public async Task <TransactionReturnInfo> CreateTransactionAsync(string ContractAddress, ContractInfo contractInfo, string FunctionName, Account account, object[] inputParams = null, List <string> PrivateFor = null)
        {
            if (web3 == null)
            {
                throw new Exception("web3 handler has not been set - please call SetWeb3Handler First");
            }

            if (PrivateFor != null && PrivateFor?.Count != 0)
            {
                web3.ClearPrivateForRequestParameters();
                web3.SetPrivateRequestParameters(PrivateFor);
            }

            var contract = web3.Eth.GetContract(contractInfo.ContractABI, ContractAddress);

            if (contract == null)
            {
                throw new Exception("Could not find contract with ABI at specified address");
            }

            var contractFunction = contract.GetFunction(FunctionName);

            if (contractFunction == null)
            {
                throw new Exception("Could not find function with name " + FunctionName);
            }

            try
            {
                // var gasCallFunction = await contractFunction.EstimateGasAsync(
                //     from: account.Address,
                //     gas: null,
                //     value: null,
                //     functionInput: inputParams == null ? new object[]{} : inputParams
                // );

                // --- the above call consistently fails - might be because of Web3Quorum --- //

                //var realGas = new HexBigInteger(gasCallFunction.Value + 500000);

                // Seems to be deprecated, using transactionmanager service instead
                // // -- set signer as the account that is sending the transaction --//
                // web3.Client.OverridingRequestInterceptor = new AccountTransactionSigningInterceptor(account.PrivateKey, web3.Client);


                var realGas = new HexBigInteger(500000);

                var txManager = new AccountSignerTransactionManager(web3.Client, account.PrivateKey);

                var txInput = contractFunction.CreateTransactionInput(account.Address, realGas, new HexBigInteger(0), new HexBigInteger(0), inputParams);

                var txCountNonce = await txManager.GetNonceAsync(txInput);

                //--- get transaction count to set nonce ---//
                var txCount = await web3.Eth.Transactions.GetTransactionCount.SendRequestAsync(account.Address, BlockParameter.CreatePending());

                txInput.Nonce = txCountNonce;

                var supposedNextNonce = await account.NonceService.GetNextNonceAsync();

                Console.WriteLine("Nonce txInput Value: " + txCountNonce.Value + "\nNonceManager Value: " + txCount.Value);

                var transactionReceipt = await txManager.SendTransactionAndWaitForReceiptAsync(txInput, null);

                // var transactionReceipt = await TransactionService.SendRequestAndWaitForReceiptAsync(() =>
                //         contractFunction.SendTransactionAsync(
                //                account.Address,
                //                gas: realGas,
                //                gasPrice: new HexBigInteger(0),
                //                value: new HexBigInteger(0),
                //                functionInput: inputParams)
                // );

                if (transactionReceipt != null)
                {
                    Console.WriteLine($"Processed Transaction - txHash: {transactionReceipt.TransactionHash}");

                    return(new TransactionReturnInfo
                    {
                        TransactionHash = transactionReceipt.TransactionHash,
                        BlockHash = transactionReceipt.BlockHash,
                        BlockNumber = transactionReceipt.BlockNumber.Value,
                        ContractAddress = ContractAddress
                    });
                }

                return(null);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return(null);
            }
        }