private void btnNep5SendTran_Click(object sender, EventArgs e) { string api = nep5AccountFrm.RpcUrl; if (string.IsNullOrEmpty(nep5AccountFrm.wif)) { MessageBox.Show("请输入钱包 wif !", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (string.IsNullOrEmpty(tbxNep5Hash.Text)) { MessageBox.Show("Nep5 合约 Hash 不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (string.IsNullOrEmpty(tbxNep5ToAddress.Text)) { MessageBox.Show("接收地址不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (string.IsNullOrEmpty(tbxNep5Value.Text)) { MessageBox.Show("转账金额不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } if (string.IsNullOrEmpty(tbxNep5GasPrice.Text)) { MessageBox.Show("Gas Price 不能为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } ScriptBuilder sb = new ScriptBuilder(); try { var toAddressHash = ZoroHelper.GetPublicKeyHashFromAddress(tbxNep5ToAddress.Text); decimal value = Math.Round(decimal.Parse(tbxNep5Value.Text) * (decimal)Math.Pow(10, 8), 0); Fixed8 gasPrice = Fixed8.FromDecimal(decimal.Parse(tbxNep5GasPrice.Text)); sb.EmitAppCall(UInt160.Parse(tbxNep5Hash.Text), "transfer", nep5AccountFrm.addressHash, toAddressHash, new BigInteger(value)); var tx = ZoroHelper.MakeTransaction(sb.ToArray(), nep5AccountFrm.keypair, Fixed8.Zero, gasPrice); bcpFee = ZoroHelper.EstimateGas(api, tx, ""); tx = ZoroHelper.MakeTransaction(sb.ToArray(), nep5AccountFrm.keypair, Fixed8.FromDecimal(bcpFee), gasPrice); var result = ZoroHelper.SendRawTransaction(api, tx, "") + " gas_consumed: " + bcpFee + "\r\n txid: " + tx.Hash; rtbxNep5Result.Text = result; } catch (Exception ex) { MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } }
/// <summary> /// Get the unspent coin references for a specific address. /// For now it only works using the NeoScan API. /// </summary> /// <param name="address"></param> /// <param name="restService"></param> /// <returns></returns> public static async Task <IEnumerable <Coin> > GetUnspent(string address, INeoscanService restService) { if (restService == null) { throw new NullReferenceException("REST client not configured"); } var addressBalance = await restService.GetBalanceAsync(address); var coinList = new List <Coin>(); if (addressBalance.Balance != null) { coinList.AddRange(from balanceEntry in addressBalance.Balance let child = balanceEntry.Unspent where child?.Count > 0 from unspent in balanceEntry.Unspent select new Coin { Output = new TransactionOutput { AssetId = UInt256.Parse(balanceEntry.AssetHash), ScriptHash = address.ToScriptHash(), Value = Fixed8.FromDecimal((decimal)unspent.Value), }, Reference = new CoinReference { PrevHash = UInt256.Parse(unspent.TxId), PrevIndex = (ushort)unspent.N, } }); } return(coinList); }
public void SystemFee_Get_Version_0_OtherAsset() { uut = TestUtils.GetIssueTransaction(false, 10, new UInt256(TestUtils.GetByteArray(32, 0x42))); uut.Version = 0; uut.SystemFee.Should().Be(Fixed8.FromDecimal(500)); }
public void Value_Set() { Fixed8 val = Fixed8.FromDecimal(42); uut.Value = val; uut.Value.Should().Be(val); }
private Transaction MakeTestTransaction(Random rnd) { Fixed8.TryParse((rnd.Next(1, 10000) * 0.00001).ToString(), out Fixed8 price); using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitSysCall("Zoro.NativeNEP5.Call", "Transfer", Genesis.BcpContractAddress, scriptHash, targetscripthash, new BigInteger(1)); InvocationTransaction tx = new InvocationTransaction { Nonce = Transaction.GetNonce(), Script = sb.ToArray(), GasPrice = price, GasLimit = Fixed8.FromDecimal(1000), Account = ZoroHelper.GetPublicKeyHash(keypair.PublicKey) }; tx.Attributes = new TransactionAttribute[0]; tx.Witnesses = new Witness[0]; byte[] data = ZoroHelper.GetHashData(tx); byte[] signdata = ZoroHelper.Sign(data, keypair.PrivateKey, keypair.PublicKey); ZoroHelper.AddWitness(tx, signdata, keypair.PublicKey); return(tx); } }
private static IssueTransaction getIssueTransaction(decimal outputVal) { return(new IssueTransaction { Attributes = new TransactionAttribute[0], Inputs = new CoinReference[0], Outputs = new[] { new TransactionOutput { AssetId = Blockchain.SystemCoin.Hash, Value = Fixed8.FromDecimal(outputVal), ScriptHash = Contract.CreateMultiSigRedeemScript(1, new ECPoint[] { ECPoint.DecodePoint("03b209fd4f53a7170ea4444e0cb0a6bb6a53c2bd016926989cf85f9b0fba17a70c".HexToBytes(), ECCurve.Secp256r1) }).ToScriptHash() } }, Scripts = new[] { new Witness { InvocationScript = new byte[0], VerificationScript = new[] { (byte)OpCode.PUSHT } } } }); }
//By BHP public static string CheckTxFee(Transaction tx) { if (tx.References == null) { return("Transaction input must not be empty"); } Fixed8 inputSum = tx.References.Values.Where(p => p.AssetId == Blockchain.GoverningToken.Hash).Sum(p => p.Value); Fixed8 outputSum = tx.Outputs.Where(p => p.AssetId == Blockchain.GoverningToken.Hash).Sum(p => p.Value); if (inputSum != Fixed8.Zero) { Fixed8 txFee = BhpTxFee.MinTxFee; int tx_size = tx.Size - tx.Witnesses.Sum(p => p.Size); txFee = Fixed8.FromDecimal(tx_size / BhpTxFee.SizeRadix + (tx_size % BhpTxFee.SizeRadix == 0 ? 0 : 1)) * BhpTxFee.MinTxFee;; txFee = txFee <= BhpTxFee.MaxTxFee ? txFee : BhpTxFee.MaxTxFee; Fixed8 payFee = inputSum - outputSum; if (txFee <= payFee && payFee <= BhpTxFee.MaxTxFee) { return("success"); } if (payFee < BhpTxFee.MinTxFee) { return("TxFee is not enough!"); } if (payFee > BhpTxFee.MaxTxFee) { return("TxFee is too much!"); } } return("success"); }
public TransferDialog(string [] addy = null, Dictionary <UIntBase, decimal> D = null) { InitializeComponent(); textBoxFee.Text = "0"; comboBoxChangeAddress.Items.AddRange(Program.CurrentWallet.GetAccounts().Where(p => !p.WatchOnly).Select(p => p.Address).ToArray()); comboBoxChangeAddress.SelectedItem = Program.CurrentWallet.GetChangeAddress().ToAddress(); comboBoxFrom.Items.AddRange(Program.CurrentWallet.GetAccounts().Where(p => !p.WatchOnly).Select(p => p.Address).ToArray()); if (addy != null && D != null) { foreach (var d in D) { var v = addy.Where(x => !string.IsNullOrEmpty(x)); txOutListBox1.SetItems(v.Select(y => new TransactionOutput { AssetId = (UInt256)d.Key, ScriptHash = y.ToScriptHash(), Value = Fixed8.FromDecimal(d.Value) } ), false); } } }
public void ToJson() { byte[] scriptVal = TestUtils.GetByteArray(32, 0x42); uut.Script = scriptVal; Fixed8 gasVal = Fixed8.FromDecimal(42); uut.Gas = gasVal; uut.Attributes = new TransactionAttribute[0]; uut.Inputs = new CoinReference[0]; uut.Outputs = new TransactionOutput[0]; uut.Scripts = new Witness[0]; JObject jObj = uut.ToJson(); jObj.Should().NotBeNull(); jObj["txid"].AsString().Should().Be("0x8258b950487299376f89ad2d09598b7acbc5cde89b161b3dd73c256f9e2a94b1"); jObj["size"].AsNumber().Should().Be(39); jObj["type"].AsString().Should().Be("InvocationTransaction"); jObj["version"].AsNumber().Should().Be(0); ((JArray)jObj["attributes"]).Count.Should().Be(0); ((JArray)jObj["vin"]).Count.Should().Be(0); ((JArray)jObj["vout"]).Count.Should().Be(0); jObj["sys_fee"].AsString().Should().Be("42"); jObj["net_fee"].AsString().Should().Be("-42"); ((JArray)jObj["scripts"]).Count.Should().Be(0); jObj["script"].AsString().Should().Be("4220202020202020202020202020202020202020202020202020202020202020"); jObj["gas"].AsNumber().Should().Be(42); }
public void SystemFee_Set() { Fixed8 val = Fixed8.FromDecimal(42); uut.Gas = val; uut.SystemFee.Should().Be(val); }
public BigDecimal GetAvailable(UIntBase asset_id) { if (asset_id is UInt160 asset_id_160) { byte[] script; UInt160[] accounts = GetAccounts().Where(p => !p.WatchOnly).Select(p => p.ScriptHash).ToArray(); using (ScriptBuilder sb = new ScriptBuilder()) { sb.EmitPush(0); foreach (UInt160 account in accounts) { sb.EmitAppCall(asset_id_160, "balanceOf", account); sb.Emit(OpCode.ADD); } sb.EmitAppCall(asset_id_160, "decimals"); script = sb.ToArray(); } ApplicationEngine engine = ApplicationEngine.Run(script, extraGAS: Fixed8.FromDecimal(0.2m) * accounts.Length); if (engine.State.HasFlag(VMState.FAULT)) { return(new BigDecimal(0, 0)); } byte decimals = (byte)engine.ResultStack.Pop().GetBigInteger(); BigInteger amount = ((VMArray)engine.ResultStack.Pop()).Aggregate(BigInteger.Zero, (x, y) => x + y.GetBigInteger()); return(new BigDecimal(amount, decimals)); } else { return(new BigDecimal(GetAvailable((UInt256)asset_id).GetData(), 8)); } }
public void Basic_equality() { var a = Fixed8.FromDecimal(1.23456789m); var b = Fixed8.Parse("1.23456789"); a.Should().Be(b); }
public void Gas_Set() { Fixed8 val = Fixed8.FromDecimal(42); uut.Gas = val; uut.Gas.Should().Be(val); }
public void test() { var d = sizeof(decimal); var i = sizeof(int); var l = sizeof(long); var f = sizeof(float); var dd = sizeof(double); var by = sizeof(byte); var c = sizeof(char); var ss = "zzc199231f06e2091f89e0128e7d875fdfb0fb5fc7c4f916af0c50d04ab70e7z"; var cc = ss.Length * c; var bb = ss.HexToBytes(); Fixed8 expected = Fixed8.FromDecimal(123456789m); Fixed8 expected1 = Fixed8.FromDecimal(1.23456789m); Fixed8 fixedMulti = expected * expected1; decimal decimalMulti = 123456789m * 1.23456789m; BigDecimal bd = new BigDecimal(123456789, 1); bd.ChangeDecimals(8); BigDecimal bd1 = new BigDecimal(123456789999, 10); bd1.ChangeDecimals(8); }
public void Can_parse_exponent_notation() { Fixed8 expected = Fixed8.FromDecimal(1.23m); Fixed8 actual = Fixed8.Parse("1.23E-0"); actual.Should().Be(expected); }
public async Task <IEnumerable <Coin> > GetUnspentAsync(string address) { var addressBalance = await GetJson <GetBalanceResponse>($"/get_balance/{address}"); //from https://github.com/CityOfZion/NeoModules/blob/master/src/NeoModules.NEP6/Helpers/TransactionBuilderHelper.cs#L24 var coinList = new List <Coin>(); if (addressBalance.Balances != null) { coinList.AddRange(from balanceEntry in addressBalance.Balances let child = balanceEntry.Unspents where child?.Count > 0 from unspent in balanceEntry.Unspents select new Coin { Output = new TransactionOutput { AssetId = UInt256.Parse(balanceEntry.AssetHash), ScriptHash = address.ToScriptHash(), Value = Fixed8.FromDecimal((decimal)unspent.Value), }, Reference = new CoinReference { PrevHash = UInt256.Parse(unspent.TxId), PrevIndex = (ushort)unspent.N, } }); } return(coinList); }
public InvocationTransaction GetTransaction(Fixed8 fee, UInt160 Change_Address = null) { if (tx.Size > 1024) { Fixed8 sumFee = Fixed8.FromDecimal(tx.Size * 0.00001m) + Fixed8.FromDecimal(0.001m); if (fee < sumFee) { fee = sumFee; } } if (Helper.CostRemind(tx.Gas.Ceiling(), fee)) { InvocationTransaction result = Program.CurrentWallet.MakeTransaction(new InvocationTransaction { Version = tx.Version, Script = tx.Script, Gas = tx.Gas, Attributes = tx.Attributes, Outputs = tx.Outputs }, change_address: Change_Address, fee: fee); return(result); } else { return(null); } }
public void Amount_Set() { Fixed8 val = Fixed8.FromDecimal(42); uut.Amount = val; uut.Amount.Should().Be(val); }
private void button5_Click(object sender, EventArgs e) { byte[] script; try { script = textBox6.Text.Trim().HexToBytes(); } catch (FormatException ex) { MessageBox.Show(ex.Message); return; } if (tx == null) { tx = new InvocationTransaction(); } tx.Version = 1; tx.Script = script; if (tx.Attributes == null) { tx.Attributes = new TransactionAttribute[0]; } if (tx.Inputs == null) { tx.Inputs = new CoinReference[0]; } if (tx.Outputs == null) { tx.Outputs = new TransactionOutput[0]; } if (tx.Scripts == null) { tx.Scripts = new Witness[0]; } ApplicationEngine engine = ApplicationEngine.RunWithDebug(tx.Script, tx); StringBuilder sb = new StringBuilder(); sb.AppendLine($"VM State: {engine.State}"); sb.AppendLine($"Gas Consumed: {engine.GasConsumed}"); sb.AppendLine($"Evaluation Stack: {new JArray(engine.EvaluationStack.Select(p => p.ToParameter().ToJson()))}"); textBox7.Text = sb.ToString(); engine.FullLog.Save(System.IO.Path.Combine(Settings.Default.Paths.FullLog, "0x00.llvmhex.txt")); if (!engine.State.HasFlag(VMState.FAULT)) { tx.Gas = engine.GasConsumed - Fixed8.FromDecimal(10); if (tx.Gas < Fixed8.Zero) { tx.Gas = Fixed8.Zero; } tx.Gas = tx.Gas.Ceiling(); Fixed8 fee = tx.Gas.Equals(Fixed8.Zero) ? net_fee : tx.Gas; label7.Text = fee + " gas"; button3.Enabled = true; } else { MessageBox.Show(Strings.ExecutionFailed); } }
/// <summary> /// Get Gas /// </summary> /// <param name="consumed">Consumed</param> /// <returns>Gas</returns> public static Fixed8 GetGas(Fixed8 consumed) { var gas = consumed - Fixed8.FromDecimal(10); return(gas <= Fixed8.Zero ? Fixed8.Zero : gas.Ceiling()); }
public static void init(string configPath) { configJson = MyJson.Parse(File.ReadAllText(configPath)); GasLimit["NEP5Transfer"] = Fixed8.FromDecimal(4500); GasLimit["NativeNEP5Transfer"] = Fixed8.FromDecimal(1000); GasLimit["BCPTransfer"] = Fixed8.FromDecimal(1000); }
public void Size_Get() { uut.AssetId = new UInt256(TestUtils.GetByteArray(32, 0x42)); uut.Value = Fixed8.FromDecimal(42); uut.ScriptHash = new UInt160(TestUtils.GetByteArray(20, 0x42)); uut.Size.Should().Be(60); // 32 + 8 + 20 }
public void Value_Get() { TransactionOutput val = new TransactionOutput(); val.Value = Fixed8.FromDecimal(42); uut.Output = val; uut.Value.Should().Be(val.Value); }
private void button5_Click(object sender, EventArgs e) { byte[] script; try { script = textBox6.Text.Trim().HexToBytes(); } catch (FormatException ex) { MessageBox.Show(ex.Message); return; } if (tx == null) { tx = new InvocationTransaction(); } tx.Version = 1; tx.Script = script; if (tx.Attributes == null) { tx.Attributes = new TransactionAttribute[0]; } if (tx.Inputs == null) { tx.Inputs = new CoinReference[0]; } if (tx.Outputs == null) { tx.Outputs = new TransactionOutput[0]; } if (tx.Witnesses == null) { tx.Witnesses = new Witness[0]; } ApplicationEngine engine = ApplicationEngine.Run(tx.Script, tx, testMode: true); StringBuilder sb = new StringBuilder(); sb.AppendLine($"VM State: {engine.State}"); sb.AppendLine($"OXC Consumed: {engine.GasConsumed}"); sb.AppendLine($"Evaluation Stack: {new JArray(engine.ResultStack.Select(p => p.ToParameter().ToJson()))}"); textBox7.Text = sb.ToString(); if (!engine.State.HasFlag(VMState.FAULT)) { tx.Gas = engine.GasConsumed - Fixed8.FromDecimal(10); if (tx.Gas < Fixed8.Zero) { tx.Gas = Fixed8.Zero; } tx.Gas = tx.Gas.Ceiling(); Fixed8 fee = tx.Gas; label7.Text = fee + " oxc"; button3.Enabled = true; } else { MessageBox.Show(LanHelper.LocalLanguage("Execution terminated in fault state.")); } }
public static Unspent FromJson(JObject json) { return(new Unspent { TxId = json["txid"].AsString(), N = int.Parse(json["n"].AsString()), Value = Fixed8.FromDecimal(decimal.Parse(json["value"].AsString())) }); }
public void FromDecimal_ValidValue_ReturnValidFixed8Object() { const decimal validDecimalValue = 1000; var actual = Fixed8.FromDecimal(validDecimalValue); actual.Should().BeOfType(typeof(Fixed8)); actual.ToString().Should().Be(validDecimalValue.ToString(CultureInfo.InvariantCulture)); }
private JObject SendMany(UInt160 from, JArray to, Fixed8 fee, UInt160 change_address) { CheckWallet(); if (to.Count == 0) { throw new RpcException(-32602, "Invalid params"); } TransferOutput[] outputs = new TransferOutput[to.Count]; for (int i = 0; i < to.Count; i++) { UIntBase asset_id = UIntBase.Parse(to[i]["asset"].AsString()); AssetDescriptor descriptor = new AssetDescriptor(asset_id); outputs[i] = new TransferOutput { AssetId = asset_id, Value = BigDecimal.Parse(to[i]["value"].AsString(), descriptor.Decimals), ScriptHash = to[i]["address"].AsString().ToScriptHash() }; if (outputs[i].Value.Sign <= 0) { throw new RpcException(-32602, "Invalid params"); } } if (fee < Fixed8.Zero) { throw new RpcException(-32602, "Invalid params"); } Transaction tx = Wallet.MakeTransaction(null, outputs, from: from, change_address: change_address, fee: fee); if (tx == null) { throw new RpcException(-300, "Insufficient funds"); } ContractParametersContext transContext = new ContractParametersContext(tx); Wallet.Sign(transContext); tx.Witnesses = transContext.GetWitnesses(); if (tx.Size > 1024) { Fixed8 calFee = Fixed8.FromDecimal(tx.Size * 0.00001m + 0.001m); if (fee < calFee) { fee = calFee; tx = Wallet.MakeTransaction(null, outputs, from: from, change_address: change_address, fee: fee); if (tx == null) { throw new RpcException(-300, "Insufficient funds"); } } } if (fee > Settings.Default.MaxFee) { throw new RpcException(-301, "The necessary fee is more than the Max_fee, this transaction is failed. Please increase your Max_fee value."); } return(SignAndRelay(tx)); }
public void FromDecimal_ValidValue_ReturnValidFixed8Object() { const decimal validDecimalValue = 1000; var actual = Fixed8.FromDecimal(validDecimalValue); Assert.IsInstanceOfType(actual, typeof(Fixed8)); Assert.AreEqual(validDecimalValue.ToString(CultureInfo.InvariantCulture), actual.ToString()); }
public ApplicationEngine CallScript(byte[] script, bool bDebug = false) { ApplicationEngine engine = null; Fixed8 net_fee = Fixed8.FromDecimal(0.001m); //生成交易 InvocationTransaction tx = new InvocationTransaction(); { tx.Version = 1; tx.Script = script; tx.Attributes = new TransactionAttribute[0]; tx.Inputs = new CoinReference[0]; tx.Outputs = new TransactionOutput[0]; if (bDebug) { engine = ApplicationEngine.RunWithDebug(tx.Script, tx); engine.FullLog.Save("d:\\0x00.llvmhex.txt"); } else { engine = ApplicationEngine.Run(tx.Script, tx); } if (!engine.State.HasFlag(VMState.FAULT)) { tx.Gas = engine.GasConsumed - Fixed8.FromDecimal(10); if (tx.Gas < Fixed8.Zero) { tx.Gas = Fixed8.Zero; } tx.Gas = tx.Gas.Ceiling(); } else { MessageBox.Show("脚本错误"); return(null); } } InvocationTransaction stx = null; Fixed8 fee = tx.Gas.Equals(Fixed8.Zero) ? net_fee : Fixed8.Zero; { stx = api.CurrentWallet.MakeTransaction(new InvocationTransaction { Version = tx.Version, Script = tx.Script, Gas = tx.Gas, Attributes = tx.Attributes, Inputs = tx.Inputs, Outputs = tx.Outputs }, fee: fee); } //签名发送交易 api.SignAndShowInformation(stx); return(engine); }
private JObject GetInvokeResult(UInt160 chain_hash, byte[] script) { Blockchain blockchain = Blockchain.GetBlockchain(chain_hash); if (blockchain == null) { throw new RpcException(-100, "Unknown blockchain"); } ApplicationEngine engine = ApplicationEngine.Run(script, blockchain.GetSnapshot()); JObject json = new JObject(); json["script"] = script.ToHexString(); json["state"] = engine.State; json["gas_consumed"] = engine.GasConsumed.ToString(); try { json["stack"] = new JArray(engine.ResultStack.Select(p => p.ToParameter().ToJson())); } catch (InvalidOperationException) { json["stack"] = "error: recursive reference"; } if (wallet != null) { InvocationTransaction tx = new InvocationTransaction { Version = 1, Script = json["script"].AsString().HexToBytes(), Gas = Fixed8.Parse(json["gas_consumed"].AsString()) }; tx.Gas -= Fixed8.FromDecimal(10); if (tx.Gas < Fixed8.Zero) { tx.Gas = Fixed8.Zero; } tx.Gas = tx.Gas.Ceiling(); tx = wallet.MakeTransaction(tx); if (tx != null) { ContractParametersContext context = new ContractParametersContext(tx, blockchain); wallet.Sign(context); if (context.Completed) { tx.Witnesses = context.GetWitnesses(); } else { tx = null; } } json["tx"] = tx?.ToArray().ToHexString(); } return(json); }