Exemplo n.º 1
0
        public void ShouldConvertFromWeiAndBackToEth()
        {
            var unitConversion = new UnitConversion();
            var val = BigInteger.Parse("1000000000000000000000000001");
            var result = unitConversion.FromWei(val, 18);
            var result2 = unitConversion.FromWei(val);
            Assert.Equal(result, result2);
            result2 = unitConversion.FromWei(val, BigInteger.Parse("1000000000000000000"));
            Assert.Equal(result, result2);
            Assert.Equal(val, UnitConversion.Convert.ToWei(result));

        }
Exemplo n.º 2
0
        public ChainSimulator(Nexus nexus, KeyPair ownerKey, int seed, Logger logger = null)
        {
            this.Logger = logger != null ? logger : new DummyLogger();

            _owner     = ownerKey;
            this.Nexus = nexus;

            CurrentTime = new DateTime(2018, 8, 26);

            if (!Nexus.Ready)
            {
                if (!Nexus.CreateGenesisBlock("simnet", _owner, CurrentTime))
                {
                    throw new ChainException("Genesis block failure");
                }
            }

            this.bankChain = Nexus.FindChainByName("bank");

            _rnd = new Random(seed);
            _keys.Add(_owner);

            var oneFuel      = UnitConversion.ToBigInteger(1, Nexus.FuelTokenDecimals);
            var localBalance = Nexus.RootChain.GetTokenBalance(Nexus.FuelTokenSymbol, _owner.Address);

            if (localBalance < oneFuel)
            {
                throw new Exception("Funds missing oops");
            }

            var neoPlatform = Pay.Chains.NeoWallet.NeoPlatform;
            var neoKeys     = InteropUtils.GenerateInteropKeys(_owner, neoPlatform);
            var neoText     = Phantasma.Neo.Core.NeoKey.FromWIF(neoKeys.ToWIF()).address;
            var neoAddress  = Phantasma.Pay.Chains.NeoWallet.EncodeAddress(neoText);

            var ethPlatform = Pay.Chains.EthereumWallet.EthereumPlatform;
            var ethKeys     = InteropUtils.GenerateInteropKeys(_owner, ethPlatform);
            var ethText     = Phantasma.Ethereum.EthereumKey.FromWIF(ethKeys.ToWIF()).address;
            var ethAddress  = Phantasma.Pay.Chains.EthereumWallet.EncodeAddress(ethText);

            BeginBlock();
            GenerateAppRegistration(_owner, "mystore", "https://my.store", "The future of digital content distribution!");

            GenerateCustomTransaction(_owner, 0, () => new ScriptBuilder().AllowGas(_owner.Address, Address.Null, MinimumFee, 9999).
                                      CallContract("nexus", "CreatePlatform", neoAddress, "GAS").
                                      CallContract("nexus", "CreatePlatform", ethAddress, "ETH").
                                      SpendGas(_owner.Address).EndScript());

            GenerateToken(_owner, "NEO", "NEO", neoPlatform, Hash.FromUnpaddedHex("c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b"), UnitConversion.ToBigInteger(100000000, 0), 0, TokenFlags.Fungible | TokenFlags.Transferable | TokenFlags.Finite | TokenFlags.External);
            GenerateToken(_owner, "GAS", "GAS", neoPlatform, Hash.FromUnpaddedHex("602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"), UnitConversion.ToBigInteger(100000000, 8), 8, TokenFlags.Fungible | TokenFlags.Transferable | TokenFlags.Divisible | TokenFlags.Finite | TokenFlags.External);
            GenerateToken(_owner, "ETH", "Ethereum", ethPlatform, Hash.FromString("ETH"), UnitConversion.ToBigInteger(0, 18), 18, TokenFlags.Fungible | TokenFlags.Transferable | TokenFlags.Divisible | TokenFlags.External);
            GenerateToken(_owner, "DAI", "Dai Stablecoin", ethPlatform, Hash.FromUnpaddedHex("89d24a6b4ccb1b6faa2625fe562bdd9a23260359"), UnitConversion.ToBigInteger(0, 18), 18, TokenFlags.Fungible | TokenFlags.Transferable | TokenFlags.Divisible | TokenFlags.External);
            //GenerateToken(_owner, "EOS", "EOS", "EOS", UnitConversion.ToBigInteger(1006245120, 18), 18, TokenFlags.Fungible | TokenFlags.Transferable | TokenFlags.Finite | TokenFlags.Divisible | TokenFlags.External);

            EndBlock();

            /*
             * var market = Nexus.FindChainByName("market");
             * var nftSales = new List<KeyValuePair<KeyPair, BigInteger>>();
             *
             * BeginBlock();
             * for (int i = 1; i < 7; i++)
             * {
             *  BigInteger ID = i + 100;
             *  TokenContent info;
             *  try
             *  {
             *      info = Nexus.GetNFT(nachoSymbol, ID);
             *  }
             *  catch
             *  {
             *      continue;
             *  }
             *
             *  var chain = Nexus.FindChainByAddress(info.CurrentChain);
             *  if (chain == null)
             *  {
             *      continue;
             *  }
             *
             *  var nftOwner = chain.GetTokenOwner(nachoSymbol, ID);
             *
             *  if (nftOwner == Address.Null)
             *  {
             *      continue;
             *  }
             *
             *  foreach (var key in _keys)
             *  {
             *      if (key.Address == nftOwner)
             *      {
             *          nftSales.Add(new KeyValuePair<KeyPair, BigInteger>(key, ID));
             *          // send some gas to the sellers
             *          GenerateTransfer(_owner, key.Address, Nexus.RootChain, Nexus.FuelTokenSymbol, UnitConversion.ToBigInteger(0.01m, Nexus.FuelTokenDecimals));
             *      }
             *  }
             * }
             *
             * EndBlock();
             *
             * BeginBlock();
             * foreach (var sale in nftSales)
             * {
             *  // TODO this later should be the market chain instead of root
             *  GenerateNftSale(sale.Key, Nexus.RootChain, nachoSymbol, sale.Value, UnitConversion.ToBigInteger(100 + 5 * _rnd.Next() % 50, Nexus.FuelTokenDecimals));
             * }
             * EndBlock();
             */
        }
Exemplo n.º 3
0
 public static BigInteger StakeToFuel(BigInteger stakeAmount, uint _BaseEnergyRatioDivisor)
 {
     return(UnitConversion.ConvertDecimals(stakeAmount, DomainSettings.StakingTokenDecimals, DomainSettings.FuelTokenDecimals) / _BaseEnergyRatioDivisor);
 }
Exemplo n.º 4
0
        public void MeshLoadProfiling()
        {
            var k3d = new Toolkit();

            int    nBeams      = 20;
            int    nFaces      = 1500;
            double lengthBeams = 10.0;
            double xIncBeam    = lengthBeams / nBeams;
            double xIncMesh    = lengthBeams / nFaces;
            double limit_dist  = xIncBeam / 100.0;

            // create beams
            var lines = new List <Line3>();
            var nodeI = new Point3(0, 0, 0);

            for (int beamInd = 0; beamInd < nBeams; ++beamInd)
            {
                var nodeK = new Point3(nodeI.X + xIncBeam, 0, 0);
                lines.Add(new Line3(nodeI, nodeK));
                nodeI = nodeK;
            }
            LineToBeam.solve(new List <Point3>(), lines, true, true, limit_dist, new List <Vector3>(), new List <string>(),
                             new List <Color>(), new List <CroSec>(), true,
                             out List <Point3> outPoints, out List <BuilderBeam> builderElements, out string info);

            // create a MeshLoad
            var meshUnitLoadsBuffer = new Dictionary <MeshUnitLoad, MeshUnitLoad>();
            var mesh = new Mesh();

            mesh.Vertices.Add(new Point3d(0, -0.5, 0));
            mesh.Vertices.Add(new Point3d(0, 0.5, 0));
            for (var faceInd = 0; faceInd < nFaces; ++faceInd)
            {
                mesh.Vertices.Add(new Point3d((faceInd + 1) * xIncMesh, -0.5, 0));
                mesh.Vertices.Add(new Point3d((faceInd + 1) * xIncMesh, 0.5, 0));
                var nV = mesh.Vertices.Count;
                mesh.Faces.AddFace(new MeshFace(nV - 4, nV - 3, nV - 1, nV - 2));
            }
            UnitsConversionFactory ucf = UnitsConversionFactories.Conv();
            UnitConversion         m   = ucf.m();
            var baseMesh = m.toBaseMesh(new RhinoMesh(mesh));

            var load = new MeshLoad(new List <Vector3>()
            {
                new Vector3(0, 0, -1)
            });

            load.InitUnitLoads(meshUnitLoadsBuffer, baseMesh, LoadOrientation.global, new List <bool>()
            {
                true, true
            },
                               new List <Point3>(), new List <string>());

            // create a Support
            var support = k3d.Support.Support(new Point3(0, 0, 0), k3d.Support.SupportFixedConditions);

            // assemble the model
            var model = k3d.Model.AssembleModel(builderElements, new List <Support>()
            {
                support
            }, new List <Load>()
            {
                load
            },
                                                out info, out var mass, out var cog, out var msg, out var runtimeWarning);

            ThIAnalyze.solve(model, out var outMaxDisp, out var outG, out var outComp, out var warning, out model);

            Assert.AreEqual(outMaxDisp[0], 2.8232103119331837, 1E-5);
            // Assert.AreEqual(1, 1, 1E-8);
        }
Exemplo n.º 5
0
 public OSM_To_Revit(Length_Unit_Types OSM_unit)
 {
     //revit uses double values to represent feet imperial unit
     this.unitConversion = new UnitConversion(OSM_unit, Length_Unit_Types.FEET);
 }
Exemplo n.º 6
0
        public void SingleUploadSuccess()
        {
            var owner = KeyPair.Generate();

            var simulator = new ChainSimulator(owner, 1234);
            var nexus     = simulator.Nexus;

            var testUser = KeyPair.Generate();

            var accountBalance = MinimumValidStake * 5;

            Transaction tx = null;

            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.FuelTokenSymbol, 100000000);
            simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, Nexus.StakingTokenSymbol, accountBalance);
            simulator.EndBlock();

            //-----------
            //Perform a valid Stake call for minimum staking amount
            var stakeAmount         = accountBalance / 2;
            var startingSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address);

            simulator.BeginBlock();
            tx = simulator.GenerateCustomTransaction(testUser, () =>
                                                     ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999)
                                                     .CallContract("energy", "Stake", testUser.Address, stakeAmount).
                                                     SpendGas(testUser.Address).EndScript());
            simulator.EndBlock();

            BigInteger stakedAmount = (BigInteger)simulator.Nexus.RootChain.InvokeContract("energy", "GetStake", testUser.Address);

            Assert.IsTrue(stakedAmount == stakeAmount);

            var finalSoulBalance = simulator.Nexus.RootChain.GetTokenBalance(Nexus.StakingTokenSymbol, testUser.Address);

            Assert.IsTrue(stakeAmount == startingSoulBalance - finalSoulBalance);

            //-----------
            //Upload a file: should succeed
            var filename    = "notAVirus.exe";
            var headerSize  = CalculateRequiredSize(filename, 0);
            var contentSize = (long)(((UnitConversion.ToDecimal(stakedAmount, Nexus.StakingTokenDecimals)) * KilobytesPerStake) * 1024) - (long)headerSize;
            var content     = new byte[contentSize];
            var rnd         = new Random();

            for (int i = 0; i < content.Length; i++)
            {
                content[i] = (byte)rnd.Next();
            }

            var contentMerkle = new MerkleTree(content);

            simulator.BeginBlock();
            tx = simulator.GenerateCustomTransaction(testUser, () =>
                                                     ScriptUtils.BeginScript().AllowGas(testUser.Address, Address.Null, 1, 9999)
                                                     .CallContract("storage", "UploadFile", testUser.Address, filename, contentSize, contentMerkle, ArchiveFlags.None, new byte[0]).
                                                     SpendGas(testUser.Address).EndScript());

            //System.IO.File.WriteAllText(@"c:\code\bug_vm.txt", string.Join('\n', new VM.Disassembler(tx.Script).Instructions));
            simulator.EndBlock();

            var usedSpace = (BigInteger)simulator.Nexus.RootChain.InvokeContract("storage", "GetUsedSpace", testUser.Address);

            Assert.IsTrue(usedSpace == 0);

            Assert.IsTrue(simulator.Nexus.ArchiveExists(contentMerkle.Root));
            var archive = simulator.Nexus.FindArchive(contentMerkle.Root);

            for (int i = 0; i < archive.BlockCount; i++)
            {
                int ofs          = (int)(i * Archive.BlockSize);
                var blockContent = content.Skip(ofs).Take((int)Archive.BlockSize).ToArray();
                simulator.Nexus.WriteArchiveBlock(archive, blockContent, i);
            }
        }
Exemplo n.º 7
0
        public static string GetTxDescription(TransactionDto tx, List <ChainDto> phantasmaChains, List <TokenDto> phantasmaTokens, string addressfrom)
        {
            string description = null;

            string  senderToken   = null;
            string  senderChain   = phantasmaChains.Where(x => x.Address == tx.ChainAddress).Select(x => x.Name).FirstOrDefault();
            Address senderAddress = Address.Null;

            string  receiverToken   = null;
            string  receiverChain   = "";
            Address receiverAddress = Address.Null;

            BigInteger amount = 0;

            foreach (var evt in tx.Events)
            {
                switch (evt.EventKind)
                {
                case EventKind.TokenClaim:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    if (data.Symbol == "SOUL")
                    {
                        return(description = $"Custom transaction");
                    }
                }
                break;


                case EventKind.TokenStake:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount = data.Value;
                    if (amount >= 1000000000)
                    {
                        if (data.Symbol != "KCAL" && data.Symbol != "NEO" && data.Symbol != "GAS")
                        {
                            //return description = $"Stake transaction";
                            return(description = $"Custom transaction");
                        }
                    }
                }
                break;

                case EventKind.TokenMint:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    if (data.Symbol == "TTRS")
                    {
                        return(description = $"Custom transaction");
                    }
                    return(description = $"Claim transaction");
                }
                break;

                case EventKind.AddressRegister:
                {
                    var name = Serialization.Unserialize <string>(evt.Data.Decode());
                    description = $"Register transaction: name '{name}' registered";
                }
                break;

                case EventKind.TokenSend:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount        = data.Value;
                    senderAddress = Address.FromText(evt.EventAddress);
                    senderToken   = data.Symbol;
                }
                break;

                case EventKind.TokenReceive:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount          = data.Value;
                    receiverAddress = Address.FromText(evt.EventAddress);
                    receiverChain   = data.ChainName;
                    receiverToken   = data.Symbol;
                }
                break;
                }
            }

            if (description == null)
            {
                if (amount > 0 && senderAddress != Address.Null && receiverAddress != Address.Null &&
                    senderToken != null && senderToken == receiverToken)
                {
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == senderToken).Decimals);

                    if (addressfrom == senderAddress.ToString())
                    {
                        description =
                            $"Send transaction: to {receiverAddress.ToString()}";
                    }
                    else
                    {
                        description =
                            $"Receive transaction: from {senderAddress.ToString()}";
                    }
                }
                else if (amount > 0 && receiverAddress != Address.Null && receiverToken != null)
                {
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == receiverToken).Decimals);

                    description = $"Send transaction: to {receiverAddress.Text} ";
                }
                else
                {
                    description = "Custom transaction";
                }
            }

            return(description);
        }
Exemplo n.º 8
0
 private void Start()
 {
     startScale    = transform.localScale;
     startPosition = UnitConversion.PointToScreenRatio(transform.position);
     Update();
 }
Exemplo n.º 9
0
        /*
         * TODO: implement methods that allow cleaning up the order history book.. make sure only the exchange that placed the orders can clear them
         */

        /*
         * TODO: implement code for trail stops and a method to allow a 3rd party to update the trail stop, without revealing user or order info
         */

        public BigInteger CalculateEscrowAmount(BigInteger orderSize, BigInteger orderPrice, TokenInfo baseToken, TokenInfo quoteToken, ExchangeOrderSide side)
        {
            switch (side)
            {
            case Sell:
                return(orderSize);

            case Buy:
                return(UnitConversion.ToBigInteger(UnitConversion.ToDecimal(orderSize, baseToken.Decimals) * UnitConversion.ToDecimal(orderPrice, quoteToken.Decimals), quoteToken.Decimals));

            default: throw new ContractException("invalid order side");
            }
        }
Exemplo n.º 10
0
        public void NoGasTestSideChainTransfer()
        {
            var owner = KeyPair.Generate();

            var simulator = new ChainSimulator(owner, 1234);
            var nexus     = simulator.Nexus;

            var sourceChain = nexus.RootChain;
            var targetChain = nexus.FindChainByName("privacy");

            var symbol = Nexus.FuelTokenSymbol;
            var token  = nexus.GetTokenInfo(symbol);

            var sender   = KeyPair.Generate();
            var receiver = KeyPair.Generate();

            var originalAmount = UnitConversion.ToBigInteger(10, token.Decimals);
            var sideAmount     = originalAmount / 2;

            Assert.IsTrue(sideAmount > 0);

            // Send from Genesis address to "sender" user
            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, sender.Address, nexus.RootChain, symbol, originalAmount);
            simulator.EndBlock();

            // verify test user balance
            var balance = nexus.RootChain.GetTokenBalance(symbol, sender.Address);

            Assert.IsTrue(balance == originalAmount);

            Transaction txA = null, txB = null;

            try
            {
                // do a side chain send using test user balance from root to account chain
                simulator.BeginBlock();
                txA = simulator.GenerateSideChainSend(sender, symbol, sourceChain, receiver.Address, targetChain,
                                                      originalAmount, 1);
                simulator.EndBlock();
            }
            catch (Exception e)
            {
                Assert.IsNotNull(e);
            }

            try
            {
                var blockA = nexus.RootChain.LastBlock;

                // finish the chain transfer
                simulator.BeginBlock();
                txB = simulator.GenerateSideChainSettlement(sender, nexus.RootChain, targetChain, blockA.Hash);
                Assert.IsTrue(simulator.EndBlock().Any());
            }
            catch (Exception e)
            {
                Assert.IsNotNull(e);
            }


            // verify balances, receiver should have 0 balance
            balance = targetChain.GetTokenBalance(symbol, receiver.Address);
            Assert.IsTrue(balance == 0);
        }
Exemplo n.º 11
0
        public void SidechainNftTransfer()
        {
            var owner = KeyPair.Generate();

            var simulator = new ChainSimulator(owner, 1234);
            var nexus     = simulator.Nexus;

            var sourceChain = nexus.RootChain;
            var targetChain = nexus.FindChainByName("privacy");

            var nftSymbol = "COOL";

            var sender   = KeyPair.Generate();
            var receiver = KeyPair.Generate();

            var fullAmount  = UnitConversion.ToBigInteger(10, Nexus.FuelTokenDecimals);
            var smallAmount = fullAmount / 2;

            Assert.IsTrue(smallAmount > 0);

            // Send some SOUL to the test user (required for gas used in "transfer" transaction)
            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, sender.Address, sourceChain, Nexus.FuelTokenSymbol, fullAmount);
            simulator.EndBlock();

            // Create the token CoolToken as an NFT
            simulator.BeginBlock();
            simulator.GenerateToken(owner, nftSymbol, "CoolToken", 0, 0, Blockchain.Tokens.TokenFlags.None);
            simulator.EndBlock();

            var token     = simulator.Nexus.GetTokenInfo(nftSymbol);
            var tokenData = new byte[] { 0x1, 0x3, 0x3, 0x7 };

            Assert.IsTrue(nexus.TokenExists(nftSymbol), "Can't find the token symbol");

            // verify nft presence on the sender pre-mint
            var ownedTokenList = sourceChain.GetTokenOwnerships(nftSymbol).Get(sourceChain.Storage, sender.Address);

            Assert.IsTrue(!ownedTokenList.Any(), "How does the sender already have a CoolToken?");

            // Mint a new CoolToken directly on the sender
            simulator.BeginBlock();
            simulator.GenerateNft(owner, sender.Address, sourceChain, nftSymbol, tokenData, new byte[0]);
            simulator.EndBlock();

            // verify nft presence on the sender post-mint
            ownedTokenList = sourceChain.GetTokenOwnerships(nftSymbol).Get(sourceChain.Storage, sender.Address);
            Assert.IsTrue(ownedTokenList.Count() == 1, "How does the sender not have one now?");

            //verify that the present nft is the same we actually tried to create
            var tokenId = ownedTokenList.ElementAt(0);
            var nft     = nexus.GetNFT(nftSymbol, tokenId);

            Assert.IsTrue(nft.ROM.SequenceEqual(tokenData) || nft.RAM.SequenceEqual(tokenData),
                          "And why is this NFT different than expected? Not the same data");

            // verify nft presence on the receiver pre-transfer
            ownedTokenList = targetChain.GetTokenOwnerships(nftSymbol).Get(targetChain.Storage, receiver.Address);
            Assert.IsTrue(!ownedTokenList.Any(), "How does the receiver already have a CoolToken?");

            var extraFee = UnitConversion.ToBigInteger(0.001m, Nexus.FuelTokenDecimals);

            // transfer that nft from sender to receiver
            simulator.BeginBlock();
            simulator.GenerateSideChainSend(sender, Nexus.FuelTokenSymbol, sourceChain, receiver.Address, targetChain, smallAmount, extraFee);
            var txA = simulator.GenerateNftSidechainTransfer(sender, receiver.Address, sourceChain, targetChain, nftSymbol, tokenId);

            simulator.EndBlock();

            var blockA = nexus.RootChain.LastBlock;

            // finish the chain transfer
            simulator.BeginBlock();
            simulator.GenerateSideChainSettlement(receiver, nexus.RootChain, targetChain, blockA.Hash);
            Assert.IsTrue(simulator.EndBlock().Any());

            // verify the sender no longer has it
            ownedTokenList = sourceChain.GetTokenOwnerships(nftSymbol).Get(sourceChain.Storage, sender.Address);
            Assert.IsTrue(!ownedTokenList.Any(), "How does the sender still have one?");

            // verify nft presence on the receiver post-transfer
            ownedTokenList = targetChain.GetTokenOwnerships(nftSymbol).Get(targetChain.Storage, receiver.Address);
            Assert.IsTrue(ownedTokenList.Count() == 1, "How does the receiver not have one now?");

            //verify that the transfered nft is the same we actually tried to create
            tokenId = ownedTokenList.ElementAt(0);
            nft     = nexus.GetNFT(nftSymbol, tokenId);
            Assert.IsTrue(nft.ROM.SequenceEqual(tokenData) || nft.RAM.SequenceEqual(tokenData),
                          "And why is this NFT different than expected? Not the same data");
        }
Exemplo n.º 12
0
        public void NftTransfer()
        {
            var owner = KeyPair.Generate();

            var simulator = new ChainSimulator(owner, 1234);
            var nexus     = simulator.Nexus;

            var chain = nexus.RootChain;

            var nftKey    = KeyPair.Generate();
            var nftSymbol = "COOL";
            var nftName   = "CoolToken";

            var sender   = KeyPair.Generate();
            var receiver = KeyPair.Generate();

            // Send some SOUL to the test user (required for gas used in "transfer" transaction)
            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, sender.Address, chain, Nexus.FuelTokenSymbol, UnitConversion.ToBigInteger(1, Nexus.FuelTokenDecimals));
            simulator.EndBlock();

            // Create the token CoolToken as an NFT
            simulator.BeginBlock();
            simulator.GenerateToken(owner, nftSymbol, nftName, 0, 0, Blockchain.Tokens.TokenFlags.None);
            simulator.EndBlock();

            var token     = simulator.Nexus.GetTokenInfo(nftSymbol);
            var tokenData = new byte[] { 0x1, 0x3, 0x3, 0x7 };

            Assert.IsTrue(nexus.TokenExists(nftSymbol), "Can't find the token symbol");

            // verify nft presence on the sender pre-mint
            var ownedTokenList = chain.GetTokenOwnerships(nftSymbol).Get(chain.Storage, sender.Address);

            Assert.IsTrue(!ownedTokenList.Any(), "How does the sender already have a CoolToken?");

            // Mint a new CoolToken directly on the sender
            simulator.BeginBlock();
            simulator.GenerateNft(owner, sender.Address, chain, nftSymbol, tokenData, new byte[0]);
            simulator.EndBlock();

            // verify nft presence on the sender post-mint
            ownedTokenList = chain.GetTokenOwnerships(nftSymbol).Get(chain.Storage, sender.Address);
            Assert.IsTrue(ownedTokenList.Count() == 1, "How does the sender not have one now?");

            //verify that the present nft is the same we actually tried to create
            var tokenId = ownedTokenList.ElementAt(0);
            var nft     = nexus.GetNFT(nftSymbol, tokenId);

            Assert.IsTrue(nft.ROM.SequenceEqual(tokenData) || nft.RAM.SequenceEqual(tokenData),
                          "And why is this NFT different than expected? Not the same data");

            // verify nft presence on the receiver pre-transfer
            ownedTokenList = chain.GetTokenOwnerships(nftSymbol).Get(chain.Storage, receiver.Address);
            Assert.IsTrue(!ownedTokenList.Any(), "How does the receiver already have a CoolToken?");

            // transfer that nft from sender to receiver
            simulator.BeginBlock();
            var txA = simulator.GenerateNftTransfer(sender, receiver.Address, chain, nftSymbol, tokenId);

            simulator.EndBlock();

            // verify nft presence on the receiver post-transfer
            ownedTokenList = chain.GetTokenOwnerships(nftSymbol).Get(chain.Storage, receiver.Address);
            Assert.IsTrue(ownedTokenList.Count() == 1, "How does the receiver not have one now?");

            //verify that the transfered nft is the same we actually tried to create
            tokenId = ownedTokenList.ElementAt(0);
            nft     = nexus.GetNFT(nftSymbol, tokenId);
            Assert.IsTrue(nft.ROM.SequenceEqual(tokenData) || nft.RAM.SequenceEqual(tokenData),
                          "And why is this NFT different than expected? Not the same data");
        }
Exemplo n.º 13
0
        public void SideChainTransferMultipleSteps()
        {
            var owner = KeyPair.Generate();

            var simulator = new ChainSimulator(owner, 1234);
            var nexus     = simulator.Nexus;

            var sourceChain = nexus.RootChain;
            var appsChain   = nexus.FindChainByName("apps");

            var symbol = Nexus.FuelTokenSymbol;
            var token  = nexus.GetTokenInfo(symbol);

            var sender   = KeyPair.Generate();
            var receiver = KeyPair.Generate();

            var originalAmount = UnitConversion.ToBigInteger(10, token.Decimals);
            var sideAmount     = originalAmount / 2;

            Assert.IsTrue(sideAmount > 0);

            var newChainName = "testing";

            // Send from Genesis address to "sender" user
            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, sender.Address, nexus.RootChain, symbol, originalAmount);
            simulator.GenerateChain(owner, appsChain, newChainName);
            simulator.EndBlock();

            var targetChain = nexus.FindChainByName(newChainName);

            // verify test user balance
            var balance = nexus.RootChain.GetTokenBalance(symbol, sender.Address);

            Assert.IsTrue(balance == originalAmount);

            // do a side chain send using test user balance from root to apps chain
            simulator.BeginBlock();
            var txA    = simulator.GenerateSideChainSend(sender, symbol, sourceChain, sender.Address, appsChain, sideAmount, 0);
            var blockA = simulator.EndBlock().FirstOrDefault();

            // finish the chain transfer
            simulator.BeginBlock();
            var txB = simulator.GenerateSideChainSettlement(sender, nexus.RootChain, appsChain, blockA.Hash);

            Assert.IsTrue(simulator.EndBlock().Any());

            // we cant transfer the full side amount due to fees
            // TODO  calculate the proper fee values instead of this
            sideAmount /= 2;
            var extraFree = UnitConversion.ToBigInteger(0.01m, token.Decimals);

            // do another side chain send using test user balance from apps to target chain
            simulator.BeginBlock();
            var txC    = simulator.GenerateSideChainSend(sender, symbol, appsChain, receiver.Address, targetChain, sideAmount, extraFree);
            var blockC = simulator.EndBlock().FirstOrDefault();

            // finish the chain transfer
            simulator.BeginBlock();
            var txD = simulator.GenerateSideChainSettlement(sender, appsChain, targetChain, blockC.Hash);

            Assert.IsTrue(simulator.EndBlock().Any());

            // TODO  verify balances
        }
Exemplo n.º 14
0
        public void TransferToAccountName()
        {
            var owner     = KeyPair.Generate();
            var simulator = new ChainSimulator(owner, 1234);

            var nexus  = simulator.Nexus;
            var symbol = Nexus.FuelTokenSymbol;

            Func <KeyPair, string, bool> registerName = (keypair, name) =>
            {
                bool result = true;

                try
                {
                    simulator.BeginBlock();
                    var tx        = simulator.GenerateAccountRegistration(keypair, name);
                    var lastBlock = simulator.EndBlock().FirstOrDefault();

                    if (lastBlock != null)
                    {
                        Assert.IsTrue(tx != null);

                        var evts = lastBlock.GetEventsForTransaction(tx.Hash);
                        Assert.IsTrue(evts.Any(x => x.Kind == Blockchain.Contracts.EventKind.AddressRegister));
                    }
                }
                catch (Exception)
                {
                    result = false;
                }

                return(result);
            };

            var targetName = "hello";
            var testUser   = KeyPair.Generate();
            var token      = nexus.GetTokenInfo(symbol);
            var amount     = UnitConversion.ToBigInteger(10, token.Decimals);

            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, symbol, amount);
            simulator.EndBlock();

            Assert.IsTrue(registerName(testUser, targetName));

            // Send from Genesis address to test user
            var transferAmount = 1;

            var initialFuelBalance = simulator.Nexus.RootChain.GetTokenBalance(symbol, testUser.Address);

            simulator.BeginBlock();
            simulator.GenerateCustomTransaction(testUser, () =>
                                                ScriptUtils.BeginScript().AllowGas(owner.Address, Address.Null, 1, 9999)
                                                .CallContract("token", "TransferTokens", owner.Address, targetName, token.Symbol, transferAmount)
                                                .SpendGas(owner.Address).EndScript());
            simulator.EndBlock();

            var finalFuelBalance = simulator.Nexus.RootChain.GetTokenBalance(symbol, testUser.Address);

            Assert.IsTrue(finalFuelBalance - initialFuelBalance == transferAmount);
        }
Exemplo n.º 15
0
        public void AccountRegister()
        {
            var owner     = KeyPair.Generate();
            var simulator = new ChainSimulator(owner, 1234);

            var nexus  = simulator.Nexus;
            var symbol = Nexus.FuelTokenSymbol;

            Func <KeyPair, string, bool> registerName = (keypair, name) =>
            {
                bool result = true;

                try
                {
                    simulator.BeginBlock();
                    var tx        = simulator.GenerateAccountRegistration(keypair, name);
                    var lastBlock = simulator.EndBlock().FirstOrDefault();

                    if (lastBlock != null)
                    {
                        Assert.IsTrue(tx != null);

                        var evts = lastBlock.GetEventsForTransaction(tx.Hash);
                        Assert.IsTrue(evts.Any(x => x.Kind == Blockchain.Contracts.EventKind.AddressRegister));
                    }
                }
                catch (Exception)
                {
                    result = false;
                }

                return(result);
            };

            var testUser = KeyPair.Generate();

            var token  = nexus.GetTokenInfo(symbol);
            var amount = UnitConversion.ToBigInteger(10, token.Decimals);

            // Send from Genesis address to test user
            simulator.BeginBlock();
            simulator.GenerateTransfer(owner, testUser.Address, nexus.RootChain, symbol, amount);
            simulator.EndBlock();

            // verify test user balance
            var balance = nexus.RootChain.GetTokenBalance(symbol, testUser.Address);

            Assert.IsTrue(balance == amount);

            var targetName = "hello";

            Assert.IsTrue(targetName == targetName.ToLower());

            Assert.IsFalse(registerName(testUser, targetName.Substring(3)));
            Assert.IsFalse(registerName(testUser, targetName.ToUpper()));
            Assert.IsFalse(registerName(testUser, targetName + "!"));
            Assert.IsTrue(registerName(testUser, targetName));

            var currentName = nexus.LookUpAddress(testUser.Address);

            Assert.IsTrue(currentName == targetName);

            var someAddress = nexus.LookUpName(targetName);

            Assert.IsTrue(someAddress == testUser.Address);

            Assert.IsFalse(registerName(testUser, "other"));
        }
Exemplo n.º 16
0
        public ActionResult PostMaterial(MaterialViewModel pvm)
        {
            Product      pt1   = new Product();
            ProductGroup group = new ProductGroupService(_unitOfWork).Find(pvm.ProductGroupId);
            ProductType  Type  = new ProductTypeService(_unitOfWork).Find(group.ProductTypeId);

            if (pvm.ProductGroupId <= 0)
            {
                ModelState.AddModelError("ProductGroupId", "Product Group field is required");
            }
            if (ModelState.IsValid)
            {
                //Checking for Create or Edit(<=0 =====>CREATE)
                if (pvm.ProductId <= 0)
                {
                    var ProductSKu = db.Product.Find(pvm.ProductSKUId);

                    var PRoductSize = db.ProductSize.Where(m => m.ProductId == ProductSKu.ProductId && m.ProductSizeTypeId == (int)ProductSizeTypeConstants.MapSize).FirstOrDefault();

                    var Size = db.Size.Find(PRoductSize.SizeId);

                    pt1.ProductName            = pvm.ProductName;
                    pt1.ProductCode            = pvm.ProductCode;
                    pt1.ProductGroupId         = pvm.ProductGroupId;
                    pt1.StandardCost           = pvm.StandardCost;
                    pt1.UnitId                 = pvm.UnitId;
                    pt1.SalesTaxGroupProductId = pvm.SalesTaxGroupProductId;
                    pt1.UnitId                 = UnitConstants.Pieces;
                    pt1.IsActive               = pvm.IsActive;
                    pt1.DivisionId             = pvm.DivisionId;
                    pt1.CreatedDate            = DateTime.Now;
                    pt1.ModifiedDate           = DateTime.Now;
                    pt1.CreatedBy              = User.Identity.Name;
                    pt1.ModifiedBy             = User.Identity.Name;
                    pt1.ReferenceDocId         = pvm.ProductSKUId;
                    pt1.ReferenceDocTypeId     = new DocumentTypeService(_unitOfWork).Find(MasterDocTypeConstants.Product).DocumentTypeId;
                    pt1.IsActive               = true;

                    pt1.ObjectState = Model.ObjectState.Added;
                    _ProductService.Create(pt1);


                    //Standard Size Data
                    ProductSize standardsize = new ProductSize();
                    standardsize.ProductSizeTypeId = (int)(ProductSizeTypeConstants.StandardSize);
                    //standardsize.ProductSizeTypeId = 1;
                    standardsize.SizeId       = PRoductSize.SizeId;
                    standardsize.ProductId    = pt1.ProductId;
                    standardsize.CreatedBy    = User.Identity.Name;
                    standardsize.CreatedDate  = DateTime.Now;
                    standardsize.ModifiedBy   = User.Identity.Name;
                    standardsize.ModifiedDate = DateTime.Now;
                    standardsize.IsActive     = true;
                    new ProductSizeService(_unitOfWork).Create(standardsize);


                    UnitConversion UnitConv = new UnitConversion();
                    UnitConv.CreatedBy           = User.Identity.Name;
                    UnitConv.CreatedDate         = DateTime.Now;
                    UnitConv.ModifiedBy          = User.Identity.Name;
                    UnitConv.ModifiedDate        = DateTime.Now;
                    UnitConv.ProductId           = pt1.ProductId;
                    UnitConv.FromQty             = 1;
                    UnitConv.FromUnitId          = UnitConstants.Pieces;
                    UnitConv.ToUnitId            = UnitConstants.SqYard;
                    UnitConv.UnitConversionForId = (byte)UnitConversionFors.Standard;



                    using (SqlConnection sqlConnection = new SqlConnection((string)System.Web.HttpContext.Current.Session["DefaultConnectionString"]))
                    {
                        sqlConnection.Open();

                        SqlCommand Totalf = new SqlCommand("SELECT * FROM Web.FuncConvertSqFeetToSqYard( " + Size.Area + ")", sqlConnection);

                        UnitConv.ToQty = Convert.ToDecimal(Totalf.ExecuteScalar() == DBNull.Value ? 0 : Totalf.ExecuteScalar());
                    }


                    new UnitConversionService(_unitOfWork).Create(UnitConv);


                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        PrepareMaterialViewBag(null);
                        ViewBag.Name             = Type.ProductTypeName;
                        ViewBag.id               = group.ProductTypeId;
                        ViewBag.ProductGroupList = new ProductGroupService(_unitOfWork).GetProductGroupListForItemType(group.ProductTypeId);
                        return(View("CreateMaterial", pvm));
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId    = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.Product).DocumentTypeId,
                        DocId        = pt1.ProductId,
                        ActivityType = (int)ActivityTypeContants.Added,
                    }));

                    #region

                    //Saving Images if any uploaded after UnitOfWorkSave

                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        //For checking the first time if the folder exists or not-----------------------------
                        string uploadfolder;
                        int    MaxLimit;
                        int.TryParse(ConfigurationManager.AppSettings["MaxFileUploadLimit"], out MaxLimit);
                        var x = (from iid in db.Counter
                                 select iid).FirstOrDefault();
                        if (x == null)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            Counter img = new Counter();
                            img.ImageFolderName = uploadfolder;
                            img.ModifiedBy      = User.Identity.Name;
                            img.CreatedBy       = User.Identity.Name;
                            img.ModifiedDate    = DateTime.Now;
                            img.CreatedDate     = DateTime.Now;
                            new CounterService(_unitOfWork).Create(img);
                            _unitOfWork.Save();
                        }

                        else
                        {
                            uploadfolder = x.ImageFolderName;
                        }


                        //For checking if the image contents length is greater than 100 then create a new folder------------------------------------

                        if (!Directory.Exists(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)))
                        {
                            Directory.CreateDirectory(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder));
                        }

                        int count = Directory.GetFiles(System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder)).Length;

                        if (count >= MaxLimit)
                        {
                            uploadfolder = System.Guid.NewGuid().ToString();
                            var u = new CounterService(_unitOfWork).Find(x.CounterId);
                            u.ImageFolderName = uploadfolder;
                            new CounterService(_unitOfWork).Update(u);
                            _unitOfWork.Save();
                        }


                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg

                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, pvm.ProductName + "_" + filename);

                            //pfile.SaveAs(filecontent);
                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));


                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, pvm.ProductName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, pvm.ProductName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }

                            //var tempsave = _FinishedProductService.Find(pt.ProductId);

                            var tempsave = _ProductService.Find(pt1.ProductId);

                            tempsave.ImageFileName   = pvm.ProductName + "_" + filename + temp2;
                            tempsave.ImageFolderName = uploadfolder;
                            _ProductService.Update(tempsave);
                            _unitOfWork.Save();
                        }
                    }

                    #endregion



                    return(RedirectToAction("CreateMaterial", new { id = group.ProductTypeId }).Success("Data saved successfully"));
                }
                else
                {
                    List <LogTypeViewModel> LogList = new List <LogTypeViewModel>();


                    Product pt    = _ProductService.Find(pvm.ProductId);
                    Product ExRec = Mapper.Map <Product>(pt);

                    pt.ProductName            = pvm.ProductName;
                    pt.ProductCode            = pvm.ProductCode;
                    pt.StandardCost           = pvm.StandardCost;
                    pt.ProductGroupId         = pvm.ProductGroupId;
                    pt.SalesTaxGroupProductId = pvm.SalesTaxGroupProductId;
                    pt.IsActive     = pvm.IsActive;
                    pt.ModifiedDate = DateTime.Now;
                    pt.ModifiedBy   = User.Identity.Name;
                    pt.ObjectState  = Model.ObjectState.Modified;
                    _ProductService.Update(pt);

                    LogList.Add(new LogTypeViewModel
                    {
                        ExObj = ExRec,
                        Obj   = pt,
                    });
                    XElement Modifications = new ModificationsCheckService().CheckChanges(LogList);

                    try
                    {
                        _unitOfWork.Save();
                    }

                    catch (Exception ex)
                    {
                        string message = _exception.HandleException(ex);
                        ModelState.AddModelError("", message);
                        PrepareMaterialViewBag(pvm);
                        ViewBag.Name             = Type.ProductTypeName;
                        ViewBag.id               = group.ProductTypeId;
                        ViewBag.ProductGroupList = new ProductGroupService(_unitOfWork).GetProductGroupListForItemType(group.ProductTypeId);
                        return(View("CreateMaterial", pvm));
                    }

                    LogActivity.LogActivityDetail(LogVm.Map(new ActiivtyLogViewModel
                    {
                        DocTypeId       = new DocumentTypeService(_unitOfWork).FindByName(MasterDocTypeConstants.Product).DocumentTypeId,
                        DocId           = pt.ProductId,
                        ActivityType    = (int)ActivityTypeContants.Modified,
                        xEModifications = Modifications,
                    }));

                    #region

                    //Saving Image if file is uploaded
                    if (Request.Files[0] != null && Request.Files[0].ContentLength > 0)
                    {
                        string uploadfolder = pt.ImageFolderName;
                        string tempfilename = pt.ImageFileName;
                        if (uploadfolder == null)
                        {
                            var x = (from iid in db.Counter
                                     select iid).FirstOrDefault();
                            if (x == null)
                            {
                                uploadfolder = System.Guid.NewGuid().ToString();
                                Counter img = new Counter();
                                img.ImageFolderName = uploadfolder;
                                img.ModifiedBy      = User.Identity.Name;
                                img.CreatedBy       = User.Identity.Name;
                                img.ModifiedDate    = DateTime.Now;
                                img.CreatedDate     = DateTime.Now;
                                new CounterService(_unitOfWork).Create(img);
                                _unitOfWork.Save();
                            }
                            else
                            {
                                uploadfolder = x.ImageFolderName;
                            }
                        }
                        //Deleting Existing Images

                        var xtemp = System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename);
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/" + tempfilename));
                        }

                        //Deleting Thumbnail Image:

                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Thumbs/" + tempfilename));
                        }

                        //Deleting Medium Image:
                        if (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename)))
                        {
                            System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/" + uploadfolder + "/Medium/" + tempfilename));
                        }

                        //Saving Thumbnails images:
                        Dictionary <string, string> versions = new Dictionary <string, string>();

                        //Define the versions to generate
                        versions.Add("_thumb", "maxwidth=100&maxheight=100");  //Crop to square thumbnail
                        versions.Add("_medium", "maxwidth=200&maxheight=200"); //Fit inside 400x400 area, jpeg
                        var    temo     = pt.ProductName.Replace(" ", string.Empty);
                        string temp2    = "";
                        string filename = System.Guid.NewGuid().ToString();
                        foreach (string filekey in System.Web.HttpContext.Current.Request.Files.Keys)
                        {
                            HttpPostedFile pfile = System.Web.HttpContext.Current.Request.Files[filekey];
                            if (pfile.ContentLength <= 0)
                            {
                                continue;                           //Skip unused file controls.
                            }
                            temp2 = Path.GetExtension(pfile.FileName);

                            string uploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder);
                            if (!Directory.Exists(uploadFolder))
                            {
                                Directory.CreateDirectory(uploadFolder);
                            }

                            string filecontent = Path.Combine(uploadFolder, pt.ProductName + "_" + filename);

                            //pfile.SaveAs(filecontent);

                            ImageBuilder.Current.Build(new ImageJob(pfile, filecontent, new Instructions(), false, true));

                            //Generate each version
                            foreach (string suffix in versions.Keys)
                            {
                                if (suffix == "_thumb")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Thumbs");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, pt.ProductName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                                else if (suffix == "_medium")
                                {
                                    string tuploadFolder = System.Web.HttpContext.Current.Request.MapPath("~/Uploads/" + uploadfolder + "/Medium");
                                    if (!Directory.Exists(tuploadFolder))
                                    {
                                        Directory.CreateDirectory(tuploadFolder);
                                    }

                                    //Generate a filename (GUIDs are best).
                                    string tfileName = Path.Combine(tuploadFolder, pt.ProductName + "_" + filename);

                                    //Let the image builder add the correct extension based on the output file type
                                    //fileName = ImageBuilder.Current.Build(file, fileName, new ResizeSettings(versions[suffix]), false, true);
                                    ImageBuilder.Current.Build(new ImageJob(pfile, tfileName, new Instructions(versions[suffix]), false, true));
                                }
                            }
                        }
                        var temsave = _ProductService.Find(pt.ProductId);
                        temsave.ImageFileName   = pt.ProductName + "_" + filename + temp2;
                        temsave.ImageFolderName = uploadfolder;
                        _ProductService.Update(temsave);
                        _unitOfWork.Save();
                    }

                    #endregion


                    return(RedirectToAction("MaterialIndex", new { id = group.ProductTypeId }).Success("Data saved successfully"));
                }
            }
            PrepareMaterialViewBag(pvm);
            return(View("CreateMaterial", pvm));
        }
Exemplo n.º 17
0
 private BigInteger ConvertQuoteToBase(BigInteger quoteAmount, BigInteger orderPrice, TokenInfo baseToken, TokenInfo quoteToken)
 {
     return(UnitConversion.ToBigInteger(UnitConversion.ToDecimal(quoteAmount, quoteToken.Decimals) / UnitConversion.ToDecimal(orderPrice, quoteToken.Decimals), baseToken.Decimals));
 }
Exemplo n.º 18
0
 void ApplyPosition(Vector2 position)
 {
     transform.position   = UnitConversion.ScreenRatioToPoint(position);
     transform.localScale = startScale * (1f - perspective);
 }
Exemplo n.º 19
0
        public void TestTransactions()
        {
            InitMainNode();

            int addressCount = 20;
            LinkedList <KeyPair> addressList = new LinkedList <KeyPair>();

            for (int i = 0; i < addressCount; i++)
            {
                var key = KeyPair.Generate();

                if (addressList.Contains(key) == false)
                {
                    addressList.AddLast(key);
                }
            }

            var currentKey = addressList.First;

            var masterKeys = KeyPair.FromWIF(nexusWif);
            //Trace.Message($"Connecting to host: {host} with address {masterKeys.Address.Text}");

            var amount = UnitConversion.ToBigInteger(1000000, Nexus.StakingTokenDecimals);
            var hash   = SendTransfer(host, masterKeys, currentKey.Value.Address, amount);

            if (hash == Hash.Null)
            {
                return;
            }

            ConfirmTransaction(host, hash);

            int totalTxs = 0;
            int okTxs    = 0;

            BigInteger currentKeyBalance = GetBalance(currentKey.Value.Address);

            amount = UnitConversion.ToBigInteger(1000000, Nexus.FuelTokenDecimals);
            SendTransfer(host, masterKeys, currentKey.Value.Address, amount, "KCAL");

            //while (currentKeyBalance > 9999)
            while (totalTxs < 10)
            {
                var destKey = currentKey.Next != null ? currentKey.Next : addressList.First;

                var txHash = SendTransfer(host, currentKey.Value, destKey.Value.Address, currentKeyBalance - 9999);
                if (txHash == Hash.Null)
                {
                    amount = UnitConversion.ToBigInteger(1000000, Nexus.FuelTokenDecimals);
                    SendTransfer(host, masterKeys, currentKey.Value.Address, amount);
                }

                do
                {
                    Thread.Sleep(100);
                } while (mempool.Size > 0);

                var confirmation = ConfirmTransaction(host, hash);

                okTxs += confirmation ? 1 : 0;

                totalTxs++;
                currentKey        = destKey;
                currentKeyBalance = GetBalance(currentKey.Value.Address);

                Trace.WriteLine(currentKeyBalance);
            }
            Assert.IsTrue(okTxs == totalTxs);

            CloseNode();
        }
Exemplo n.º 20
0
        public static string GetTxAmount(TransactionDto tx, List <ChainDto> phantasmaChains, List <TokenDto> phantasmaTokens)
        {
            string amountsymbol = null;

            string  senderToken   = null;
            Address senderChain   = Address.FromText(tx.ChainAddress);
            Address senderAddress = Address.Null;

            string  receiverToken   = null;
            string  receiverChain   = "";
            Address receiverAddress = Address.Null;

            BigInteger amount = 0;

            tx.Events.Reverse();
            foreach (var evt in tx.Events) //todo move this
            {
                switch (evt.EventKind)
                {
                case EventKind.TokenStake:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount          = data.Value;
                    receiverAddress = Address.FromText(evt.EventAddress);
                    receiverChain   = data.ChainName;
                    if (data.Symbol == "TTRS")
                    {
                        amountsymbol = $"{data.Symbol} • NFT";
                        break;
                    }
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == data.Symbol).Decimals);
                    if (data.Symbol != "KCAL" && data.Symbol != "NEO" && data.Symbol != "GAS")
                    {
                        amountsymbol = $"{amountDecimal.ToString("#,0.##########").ToString(new CultureInfo("en-US"))} {data.Symbol}";
                    }
                }
                break;

                case EventKind.TokenClaim:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount          = data.Value;
                    receiverAddress = Address.FromText(evt.EventAddress);
                    receiverChain   = data.ChainName;
                    if (data.Symbol == "TTRS")
                    {
                        amountsymbol = $"{data.Symbol} • NFT";
                        break;
                    }
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == data.Symbol).Decimals);
                    if (data.Symbol != "KCAL" && data.Symbol != "NEO" && data.Symbol != "GAS")
                    {
                        amountsymbol = $"{amountDecimal.ToString("#,0.##########").ToString(new CultureInfo("en-US"))} {data.Symbol}";
                    }
                }
                break;

                case EventKind.TokenSend:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount        = data.Value;
                    senderAddress = Address.FromText(evt.EventAddress);
                    senderToken   = data.Symbol;
                    if (data.Symbol == "TTRS")
                    {
                        amountsymbol = $"{data.Symbol} • NFT";
                        break;
                    }
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == senderToken).Decimals);
                    amountsymbol = $"{amountDecimal.ToString("#,0.##########").ToString(new CultureInfo("en-US"))} {senderToken}";
                }
                break;

                case EventKind.TokenReceive:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount          = data.Value;
                    receiverAddress = Address.FromText(evt.EventAddress);
                    receiverChain   = data.ChainName;
                    receiverToken   = data.Symbol;
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == receiverToken).Decimals);
                    if (data.Symbol == "TTRS")
                    {
                        amountsymbol = $"{data.Symbol} • NFT";
                        break;
                    }
                    amountsymbol = $"{amountDecimal.ToString("#,0.##########").ToString(new CultureInfo("en-US"))} {receiverToken}";
                }
                break;

                case EventKind.TokenMint:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount          = data.Value;
                    receiverAddress = Address.FromText(evt.EventAddress);
                    receiverChain   = data.ChainName;
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == data.Symbol).Decimals);
                    amountsymbol = $"{amountDecimal.ToString("#,0.##########").ToString(new CultureInfo("en-US"))} {data.Symbol}";
                    if (data.Symbol == "TTRS")
                    {
                        amountsymbol = $"{data.Symbol} • NFT";
                    }
                }
                break;

                case EventKind.AddressRegister:
                {
                    return(amountsymbol = $"");
                }
                break;
                }
            }

            return(amountsymbol);
        }
Exemplo n.º 21
0
 public static BigInteger FuelToStake(BigInteger fuelAmount)
 {
     return(UnitConversion.ConvertDecimals(fuelAmount * BaseEnergyRatioDivisor, Nexus.FuelTokenDecimals, Nexus.StakingTokenDecimals));
 }
Exemplo n.º 22
0
        static void DumpBalances(string symbol, int decimals)
        {
            var prefix = BalanceSheet.MakePrefix(symbol);

            var storage = new KeyStoreStorage(store);

            var stakeMapKey = GetKeyForField <StakeContract>("_stakes");
            var stakeMap    = new StorageMap(stakeMapKey, storage);
            var stakeCount  = stakeMap.Count();

            var addresses = new HashSet <Address>();

            //Console.WriteLine($"************ BALANCE LIST FOR {symbol} ************");

            decimal total = 0;

            store.Visit((key, value) =>
            {
                if (HasPrefix(prefix, key))
                {
                    var bytes = new byte[key.Length - prefix.Length];
                    ByteArrayUtils.CopyBytes(key, prefix.Length, bytes, 0, bytes.Length);

                    var addr = Address.FromBytes(bytes);
                    if (addr.IsSystem || addr.Text == "P2KFNXEbt65rQiWqogAzqkVGMqFirPmqPw8mQyxvRKsrXV8")
                    {
                        return;
                    }

                    BigInteger amount;

                    if (value.Length > 0)
                    {
                        amount = BigInteger.FromSignedArray(value);
                    }
                    else
                    {
                        amount = 0;
                    }

                    /*if (symbol == DomainSettings.StakingTokenSymbol && stakeMap.ContainsKey<Address>(addr))
                     * {
                     *  var temp = stakeMap.Get<Address, EnergyStake>(addr);
                     *  amount += temp.stakeAmount;
                     * }*/

                    addresses.Add(addr);

                    string s;

                    if (PrettyPrint)
                    {
                        var dec = UnitConversion.ToDecimal(amount, decimals);
                        total  += dec;
                        s       = dec.ToString();
                    }
                    else
                    {
                        s = amount.ToString();
                    }

                    Console.WriteLine($"{addr.Text},{symbol},{s}");
                }
            });

            /*
             * if (symbol == DomainSettings.StakingTokenSymbol)
             * {
             *  var masterListKey = GetKeyForField<StakeContract>("_mastersList");
             *  var masterList = new StorageList(masterListKey, storage);
             *  var masterCount = masterList.Count();
             *  for (int i = 0; i < masterCount; i++)
             *  {
             *      var master = masterList.Get<EnergyMaster>(i);
             *      if (addresses.Contains(master.address))
             *      {
             *          continue;
             *      }
             *
             *      var temp = stakeMap.Get<Address, EnergyAction>(master.address);
             *
             *      string s;
             *
             *      if (PrettyPrint)
             *      {
             *          var stake = UnitConversion.ToDecimal(temp.totalAmount, decimals);
             *          s = stake.ToString();
             *          total += stake;
             *      }
             *      else
             *      {
             *          s = temp.totalAmount.ToString();
             *      }
             *
             *      Console.WriteLine($"{master.address.Text},{symbol},{s}");
             *  }
             * }*/

            if (PrettyPrint)
            {
                Console.WriteLine($"Total,{symbol},{total}");
            }
        }
Exemplo n.º 23
0
 public static BigInteger StakeToFuel(BigInteger stakeAmount)
 {
     return(UnitConversion.ConvertDecimals(stakeAmount, Nexus.StakingTokenDecimals, Nexus.FuelTokenDecimals) / BaseEnergyRatioDivisor);
 }
Exemplo n.º 24
0
        public static string GetTxDescription(TransactionDto tx, List <ChainDto> phantasmaChains, List <TokenDto> phantasmaTokens)
        {
            string description = null;

            string  senderToken   = null;
            Address senderChain   = Address.FromText(tx.ChainAddress);
            Address senderAddress = Address.Null;

            string  receiverToken   = null;
            Address receiverChain   = Address.Null;
            Address receiverAddress = Address.Null;

            BigInteger amount = 0;

            foreach (var evt in tx.Events) //todo move this
            {
                switch (evt.EventKind)
                {
                case EventKind.TokenSend:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount        = data.value;
                    senderAddress = Address.FromText(evt.EventAddress);
                    senderToken   = data.symbol;
                }
                break;

                case EventKind.TokenReceive:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount          = data.value;
                    receiverAddress = Address.FromText(evt.EventAddress);
                    receiverChain   = data.chainAddress;
                    receiverToken   = data.symbol;
                }
                break;

                case EventKind.TokenEscrow:
                {
                    var data = Serialization.Unserialize <TokenEventData>(evt.Data.Decode());
                    amount = data.value;
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == data.symbol).Decimals);
                    receiverAddress = Address.FromText(evt.EventAddress);
                    receiverChain   = data.chainAddress;
                    var chain = GetChainName(receiverChain.Text, phantasmaChains);
                    description =
                        $"{amountDecimal} {data.symbol} tokens escrowed for address {receiverAddress} in {chain}";
                }
                break;

                case EventKind.AddressRegister:
                {
                    var name = Serialization.Unserialize <string>(evt.Data.Decode());
                    description = $"{evt.EventAddress} registered the name '{name}'";
                }
                break;

                case EventKind.AddFriend:
                {
                    var address = Serialization.Unserialize <Address>(evt.Data.Decode());
                    description = $"{evt.EventAddress} added '{address.ToString()} to friends.'";
                }
                break;

                case EventKind.RemoveFriend:
                {
                    var address = Serialization.Unserialize <Address>(evt.Data.Decode());
                    description = $"{evt.EventAddress} removed '{address.ToString()} from friends.'";
                }
                break;
                }
            }

            if (description == null)
            {
                if (amount > 0 && senderAddress != Address.Null && receiverAddress != Address.Null &&
                    senderToken != null && senderToken == receiverToken)
                {
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == senderToken).Decimals);

                    description =
                        $"{amountDecimal} {senderToken} sent from {senderAddress.ToString()} to {receiverAddress.ToString()}";
                }
                else if (amount > 0 && receiverAddress != Address.Null && receiverToken != null)
                {
                    var amountDecimal = UnitConversion.ToDecimal(amount, phantasmaTokens.Single(p => p.Symbol == receiverToken).Decimals);

                    description = $"{amountDecimal} {receiverToken} received on {receiverAddress.Text} ";
                }
                else
                {
                    description = "Custom transaction";
                }

                if (receiverChain != Address.Null && receiverChain != senderChain)
                {
                    description +=
                        $" from {GetChainName(senderChain.Text, phantasmaChains)} chain to {GetChainName(receiverChain.Text, phantasmaChains)} chain";
                }
            }

            return(description);
        }
Exemplo n.º 25
0
        public byte[] Read(string url)
        {
            if (_entries.ContainsKey(url))
            {
                return(_entries[url].Content);
            }

            byte[] content;

            if (url.StartsWith(interopTag))
            {
                url = url.Substring(interopTag.Length);
                var args = url.Split('/');

                var platformName = args[0];
                if (Nexus.PlatformExists(platformName))
                {
                    args = args.Skip(1).ToArray();
                    return(ReadChainOracle(platformName, args));
                }
                else
                {
                    throw new OracleException("invalid oracle platform: " + platformName);
                }
            }
            else
            if (url.StartsWith(priceTag))
            {
                url = url.Substring(priceTag.Length);
                var symbols = url.Split('/');

                if (symbols.Length < 1 || symbols.Length > 2)
                {
                    throw new OracleException("invalid oracle price request");
                }

                var baseSymbol  = symbols[0];
                var quoteSymbol = symbols.Length > 1 ? symbols[1] : Nexus.FiatTokenSymbol;

                if (!Nexus.TokenExists(baseSymbol))
                {
                    throw new OracleException("unknown token: " + baseSymbol);
                }

                if (!Nexus.TokenExists(quoteSymbol))
                {
                    throw new OracleException("unknown token: " + quoteSymbol);
                }

                var tokenInfo = Nexus.GetTokenInfo(quoteSymbol);

                var price = PullPrice(baseSymbol, quoteSymbol);
                var val   = UnitConversion.ToBigInteger(price, tokenInfo.Decimals);
                return(val.ToUnsignedByteArray());
            }
            else
            {
                content = PullData(url);
            }

            var entry = new OracleEntry(url, content);

            _entries[url] = entry;

            return(content);
        }
Exemplo n.º 26
0
 public static BigInteger FuelToStake(BigInteger fuelAmount, uint _BaseEnergyRatioDivisor)
 {
     return(UnitConversion.ConvertDecimals(fuelAmount * _BaseEnergyRatioDivisor, DomainSettings.FuelTokenDecimals, DomainSettings.StakingTokenDecimals));
 }
 public BigInteger GetRequiredStake()
 {
     return(UnitConversion.ToBigInteger(50000, Nexus.StakingTokenDecimals)); // TODO this should be dynamic
 }
 // Start is called before the first frame update
 void Start()
 {
     result = UnitConversion.ConvertAcelMilesToMeters(mi);
 }
Exemplo n.º 29
0
        public void ApplyInflation(Address from)
        {
            Runtime.Expect(_inflationReady, "inflation not ready");

            Runtime.Expect(Runtime.IsRootChain(), "only on root chain");

            var currentSupply = Runtime.GetTokenSupply(DomainSettings.StakingTokenSymbol);

            var minExpectedSupply = UnitConversion.ToBigInteger(100000000, DomainSettings.StakingTokenDecimals);

            if (currentSupply < minExpectedSupply)
            {
                currentSupply = minExpectedSupply;
            }

            // NOTE this gives an approximate inflation of 3% per year (0.75% per season)
            var        inflationAmount = currentSupply / 133;
            BigInteger mintedAmount    = 0;

            Runtime.Expect(inflationAmount > 0, "invalid inflation amount");

            var masterOrg = Runtime.GetOrganization(DomainSettings.MastersOrganizationName);
            var masters   = masterOrg.GetMembers();

            var rewardList = new List <Address>();

            foreach (var addr in masters)
            {
                var masterDate = Runtime.CallNativeContext(NativeContractKind.Stake, nameof(StakeContract.GetMasterDate), addr).AsTimestamp();

                if (masterDate <= _lastInflationDate)
                {
                    rewardList.Add(addr);
                }
            }

            if (rewardList.Count > 0)
            {
                var rewardAmount = inflationAmount / 10;

                var rewardStake = rewardAmount / rewardList.Count;
                rewardAmount = rewardList.Count * rewardStake; // eliminate leftovers

                var rewardFuel = _rewardAccum / rewardList.Count;

                BigInteger stakeAmount;

                if (Runtime.ProtocolVersion > 5)
                {
                    stakeAmount = UnitConversion.ToBigInteger(2, DomainSettings.StakingTokenDecimals);
                }
                else
                {
                    stakeAmount = UnitConversion.ToBigInteger(1, DomainSettings.StakingTokenDecimals);
                }

                Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, this.Address, rewardAmount);

                var crownAddress = TokenUtils.GetContractAddress(DomainSettings.RewardTokenSymbol);
                Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, crownAddress, stakeAmount);
                Runtime.CallNativeContext(NativeContractKind.Stake, nameof(StakeContract.Stake), crownAddress, stakeAmount);

                foreach (var addr in rewardList)
                {
                    var reward = new StakeReward(addr, Runtime.Time);

                    /*var temp = VMObject.FromObject(reward);
                     * temp = VMObject.CastTo(temp, VMType.Struct);
                     *
                     * var rom = temp.Serialize();*/

                    var rom = Serialization.Serialize(reward);

                    var tokenID = Runtime.MintToken(DomainSettings.RewardTokenSymbol, this.Address, this.Address, rom, new byte[0], 0);
                    Runtime.InfuseToken(DomainSettings.RewardTokenSymbol, this.Address, tokenID, DomainSettings.FuelTokenSymbol, rewardFuel);
                    Runtime.InfuseToken(DomainSettings.RewardTokenSymbol, this.Address, tokenID, DomainSettings.StakingTokenSymbol, rewardStake);
                    Runtime.TransferToken(DomainSettings.RewardTokenSymbol, this.Address, addr, tokenID);
                }

                _rewardAccum -= rewardList.Count * rewardFuel;
                Runtime.Expect(_rewardAccum >= 0, "invalid reward leftover");

                inflationAmount -= rewardAmount;
                inflationAmount -= stakeAmount;
            }

            var refillAmount  = inflationAmount / 50;
            var cosmicAddress = SmartContract.GetAddressForNative(NativeContractKind.Swap);

            Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, cosmicAddress, refillAmount);
            inflationAmount -= refillAmount;

            var phantomOrg = Runtime.GetOrganization(DomainSettings.PhantomForceOrganizationName);

            if (phantomOrg != null)
            {
                var phantomFunding = inflationAmount / 3;
                Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, phantomOrg.Address, phantomFunding);
                inflationAmount -= phantomFunding;

                if (phantomOrg.Size == 1)
                {
                    Runtime.CallNativeContext(NativeContractKind.Stake, nameof(StakeContract.Stake), phantomOrg.Address, phantomFunding);
                }
            }

            var bpOrg = Runtime.GetOrganization(DomainSettings.ValidatorsOrganizationName);

            if (bpOrg != null)
            {
                Runtime.MintTokens(DomainSettings.StakingTokenSymbol, this.Address, bpOrg.Address, inflationAmount);

                if (bpOrg.Size == 1)
                {
                    Runtime.CallNativeContext(NativeContractKind.Stake, nameof(StakeContract.Stake), bpOrg.Address, inflationAmount);
                }
            }

            Runtime.Notify(EventKind.Inflation, from, new TokenEventData(DomainSettings.StakingTokenSymbol, mintedAmount, Runtime.Chain.Name));

            _lastInflationDate = Runtime.Time;
            _inflationReady    = false;
        }
Exemplo n.º 30
0
        public void GenerateRandomBlock(Mempool mempool = null)
        {
            //Console.WriteLine("begin block #" + Nexus.RootChain.BlockHeight);
            BeginBlock();

            int transferCount = 1 + _rnd.Next() % 10;
            int tries         = 0;

            while (tries < 10000)
            {
                if (transactions.Count >= transferCount)
                {
                    break;
                }

                tries++;
                var source = _keys[_rnd.Next() % _keys.Count];

                if (usedAddresses.Contains(source.Address))
                {
                    continue;
                }

                var prevTxCount = transactions.Count;

                var sourceChain = Nexus.RootChain;
                var fee         = 9999;

                string tokenSymbol;

                switch (_rnd.Next() % 4)
                {
                case 1: tokenSymbol = Nexus.FiatTokenSymbol; break;

                //case 2: token = Nexus.FuelTokenSymbol; break;
                default: tokenSymbol = Nexus.StakingTokenSymbol; break;
                }

                switch (_rnd.Next() % 7)
                {
                // side-chain send
                case 1:
                {
                    var sourceChainList = Nexus.Chains.ToArray();
                    sourceChain = Nexus.FindChainByName(sourceChainList[_rnd.Next() % sourceChainList.Length]);

                    var targetChainList = Nexus.Chains.Select(x => Nexus.FindChainByName(x)).Where(x => Nexus.GetParentChainByName(x.Name) == sourceChain.Name || Nexus.GetParentChainByName(sourceChain.Name) == x.Name).ToArray();
                    var targetChain     = targetChainList[_rnd.Next() % targetChainList.Length];

                    var total = UnitConversion.ToBigInteger(1 + _rnd.Next() % 100, Nexus.FuelTokenDecimals);

                    var tokenBalance = sourceChain.GetTokenBalance(tokenSymbol, source.Address);
                    var fuelBalance  = sourceChain.GetTokenBalance(Nexus.FuelTokenSymbol, source.Address);

                    var expectedTotal = total;
                    if (tokenSymbol == Nexus.FuelTokenSymbol)
                    {
                        expectedTotal += fee;
                    }

                    var sideFee = 0;
                    if (tokenSymbol != Nexus.FuelTokenSymbol)
                    {
                        sideFee = fee;
                    }

                    if (tokenBalance > expectedTotal && fuelBalance > fee + sideFee)
                    {
                        Logger.Debug($"Rnd.SideChainSend: {total} {tokenSymbol} from {source.Address}");
                        GenerateSideChainSend(source, tokenSymbol, sourceChain, source.Address, targetChain, total, sideFee);
                    }
                    break;
                }

                // side-chain receive
                case 2:
                {
                    if (_pendingBlocks.Any())
                    {
                        var pendingBlock = _pendingBlocks.First();

                        if (mempool == null || Nexus.GetConfirmationsOfHash(pendingBlock.hash) > 0)
                        {
                            var balance = pendingBlock.destChain.GetTokenBalance(pendingBlock.tokenSymbol, source.Address);
                            if (balance > 0)
                            {
                                Logger.Message($"...Settling {pendingBlock.sourceChain.Name}=>{pendingBlock.destChain.Name}: {pendingBlock.hash}");
                                GenerateSideChainSettlement(source, pendingBlock.sourceChain, pendingBlock.destChain, pendingBlock.hash);
                            }
                        }
                    }

                    break;
                }

                /*
                 * // stable claim
                 * case 3:
                 * {
                 *  sourceChain = bankChain;
                 *  tokenSymbol = Nexus.FuelTokenSymbol;
                 *
                 *  var balance = sourceChain.GetTokenBalance(tokenSymbol, source.Address);
                 *
                 *  var total = UnitConversion.ToBigInteger(1 + _rnd.Next() % 100, Nexus.FuelTokenDecimals - 1);
                 *
                 *  if (balance > total + fee)
                 *  {
                 *      Logger.Debug($"Rnd.StableClaim: {total} {tokenSymbol} from {source.Address}");
                 *      GenerateStableClaim(source, sourceChain, total);
                 *  }
                 *
                 *  break;
                 * }
                 *
                 * // stable redeem
                 * case 4:
                 * {
                 *  sourceChain = bankChain;
                 *  tokenSymbol = Nexus.FiatTokenSymbol;
                 *
                 *  var tokenBalance = sourceChain.GetTokenBalance(tokenSymbol, source.Address);
                 *  var fuelBalance = sourceChain.GetTokenBalance(Nexus.FuelTokenSymbol, source.Address);
                 *
                 *  var rate = (BigInteger) bankChain.InvokeContract("bank", "GetRate", Nexus.FuelTokenSymbol);
                 *  var total = tokenBalance / 10;
                 *  if (total >= rate && fuelBalance > fee)
                 *  {
                 *      Logger.Debug($"Rnd.StableRedeem: {total} {tokenSymbol} from {source.Address}");
                 *      GenerateStableRedeem(source, sourceChain, total);
                 *  }
                 *
                 *  break;
                 * }*/

                // name register
                case 5:
                {
                    sourceChain = this.Nexus.RootChain;
                    tokenSymbol = Nexus.FuelTokenSymbol;

                    var balance = sourceChain.GetTokenBalance(tokenSymbol, source.Address);
                    if (balance > fee + AccountContract.RegistrationCost && !pendingNames.Contains(source.Address))
                    {
                        var randomName = accountNames[_rnd.Next() % accountNames.Length];

                        switch (_rnd.Next() % 10)
                        {
                        case 1:
                        case 2:
                            randomName += (_rnd.Next() % 10).ToString();
                            break;

                        case 3:
                        case 4:
                        case 5:
                            randomName += (10 + _rnd.Next() % 90).ToString();
                            break;

                        case 6:
                            randomName += (100 + _rnd.Next() % 900).ToString();
                            break;
                        }

                        var currentName = Nexus.LookUpAddressName(source.Address);
                        if (currentName == ValidationUtils.ANONYMOUS)
                        {
                            var lookup = Nexus.LookUpName(randomName);
                            if (lookup.IsNull)
                            {
                                Logger.Debug($"Rnd.GenerateAccount: {source.Address} => {randomName}");
                                GenerateAccountRegistration(source, randomName);
                            }
                        }
                    }

                    break;
                }

                // normal transfer
                default:
                {
                    var     temp = _rnd.Next() % 5;
                    Address targetAddress;

                    if ((_keys.Count < 2 || temp == 0) && _keys.Count < 2000)
                    {
                        var key = KeyPair.Generate();
                        _keys.Add(key);
                        targetAddress = key.Address;
                    }
                    else
                    {
                        targetAddress = _keys[_rnd.Next() % _keys.Count].Address;
                    }

                    if (source.Address != targetAddress)
                    {
                        var total = UnitConversion.ToBigInteger(1 + _rnd.Next() % 100, Nexus.FuelTokenDecimals - 1);

                        var tokenBalance = sourceChain.GetTokenBalance(tokenSymbol, source.Address);
                        var fuelBalance  = sourceChain.GetTokenBalance(Nexus.FuelTokenSymbol, source.Address);

                        var expectedTotal = total;
                        if (tokenSymbol == Nexus.FuelTokenSymbol)
                        {
                            expectedTotal += fee;
                        }

                        if (tokenBalance > expectedTotal && fuelBalance > fee)
                        {
                            Logger.Debug($"Rnd.Transfer: {total} {tokenSymbol} from {source.Address} to {targetAddress}");
                            GenerateTransfer(source, targetAddress, sourceChain, tokenSymbol, total);
                        }
                    }
                    break;
                }
                }
            }

            if (transactions.Count > 0)
            {
                EndBlock(mempool);
            }
            else
            {
                CancelBlock();
            }
        }
Exemplo n.º 31
0
        /// <summary>Samples a new projectile.</summary>
        /// <param name="manager">The manager.</param>
        /// <param name="emitter">The emitter that the projectile comes from.</param>
        /// <param name="offset">The offset.</param>
        /// <param name="angle">The angle.</param>
        /// <param name="weapon">The weapon.</param>
        /// <param name="faction">The faction the projectile belongs to.</param>
        /// <param name="random">The randomizer to use.</param>
        /// <returns>A new projectile.</returns>
        public int SampleProjectile(
            IManager manager,
            int emitter,
            Vector2 offset,
            float angle,
            Weapon weapon,
            Factions faction,
            IUniformRandom random)
        {
            var entity = manager.AddEntity();

            // Get position and velocity of the emitter, to set initial position
            // and additional velocity.
            var emitterTransform = (ITransform)manager.GetComponent(emitter, TransformTypeId);
            var emitterVelocity  = (IVelocity)manager.GetComponent(emitter, VelocityTypeId);

            // Rotate the offset.
            var emitterAngle = emitterTransform.Angle;
            var cosRadians   = (float)Math.Cos(emitterAngle);
            var sinRadians   = (float)Math.Sin(emitterAngle);

            FarPosition rotatedOffset;

            rotatedOffset.X = -offset.X * cosRadians - offset.Y * sinRadians;
            rotatedOffset.Y = -offset.X * sinRadians + offset.Y * cosRadians;

            // Set initial velocity.
            var velocity          = SampleInitialDirectedVelocity(emitterAngle + angle, random);
            var accelerationForce = SampleAccelerationForce(emitterAngle + angle, random);

            // Adjust rotation for projectile based on its own acceleration or speed.
            var emitAngle = emitterAngle;

            if (accelerationForce != Vector2.Zero)
            {
                emitAngle = (float)Math.Atan2(accelerationForce.Y, accelerationForce.X);
            }
            else if (velocity != Vector2.Zero)
            {
                emitAngle = (float)Math.Atan2(velocity.Y, velocity.X);
            }

            // See what we must not bump into.
            var collisionMask = ~faction.ToCollisionGroup();

            // Normally projectiles won't test against each other, but some may be
            // shot down, such as missiles. If that's the case, don't add us to the
            // common projectile group.
            if (!_canBeShot)
            {
                collisionMask &= ~Factions.Projectiles.ToCollisionGroup();
            }

            // Create physical body.
            var body = manager.AddBody(
                entity,
                emitterTransform.Position + rotatedOffset + velocity / Settings.TicksPerSecond,
                emitAngle,
                Body.BodyType.Dynamic,
                isBullet: true,
                allowSleep: false);

            manager.AttachCircle(
                body,
                UnitConversion.ToSimulationUnits(_collisionRadius),
                0,
                restitution: 0.1f,
                collisionCategory: faction.ToCollisionGroup() | Factions.Projectiles.ToCollisionGroup(),
                collisionMask: collisionMask);

            // Add to render system indexes. The padding these perform should be enough for any projectile.
            manager.AddComponent <Indexable>(entity).Initialize(CameraSystem.IndexId);
            manager.AddComponent <Indexable>(entity).Initialize(InterpolationSystem.IndexId);

            // If our emitter was moving, apply its velocity.
            if (emitterVelocity != null)
            {
                velocity += emitterVelocity.LinearVelocity;
            }

            // Then set the initial velocity of our bullet.
            body.LinearVelocity = velocity;

            // Sample an acceleration for this projectile. If there is any, create the
            // component for it, otherwise disregard.
            if (accelerationForce != Vector2.Zero)
            {
                // TODO add motor joint? else teach acceleration system to use ApplyForce
//                manager.AddComponent<Acceleration>(entity).Initialize(accelerationForce);
            }

            // Apply friction to this projectile if so desired.
            if (_friction > 0)
            {
                body.LinearDamping = 1f - _friction;
            }

            // If this projectile should vanish after some time, make it expire.
            if (_timeToLive > 0)
            {
                manager.AddComponent <Expiration>(entity).Initialize((int)(_timeToLive * Settings.TicksPerSecond));
            }

            // Mark as applying damage on collision.
            manager.AddComponent <CollisionDamage>(entity).Initialize(true);

            // Apply attributes of the weapon, modified with emitter attribute values,
            // and emitter attributes to the projectile to allow damage calculation if
            // it hits something.
            var emitterAttributes =
                (Attributes <AttributeType>)manager.GetComponent(emitter, Attributes <AttributeType> .TypeId);
            Attributes <AttributeType> projectileAttributes = null; // Only create if necessary.

            foreach (AttributeType attributeType in Enum.GetValues(typeof(AttributeType)))
            {
                if (attributeType == AttributeType.None)
                {
                    continue;
                }
                // Try to get weapon local attribute as base values.
                var value = 0f;
                if (weapon.Attributes.ContainsKey(attributeType))
                {
                    value = weapon.Attributes[attributeType];
                }
                // Try to modify it with emitter attributes.
                if (emitterAttributes != null)
                {
                    value = emitterAttributes.GetValue(attributeType, value);
                }
                // If we have something, copy it to the projectile.
// ReSharper disable CompareOfFloatsByEqualityOperator
                if (value != 0f)
// ReSharper restore CompareOfFloatsByEqualityOperator
                {
                    if (projectileAttributes == null)
                    {
                        projectileAttributes = manager.AddComponent <Attributes <AttributeType> >(entity);
                    }
                    projectileAttributes.SetBaseValue(attributeType, value);
                }
            }

            // Make us visible!
            if (!string.IsNullOrWhiteSpace(_model))
            {
                manager.AddComponent <SimpleTextureDrawable>(entity).Initialize(_model);
            }

            // And add some particle effects, if so desired.
            if (!string.IsNullOrWhiteSpace(_effect))
            {
                manager.AddComponent <ParticleEffects>(entity)
                .TryAdd(0, _effect, 1f, 0, _effectOffset, ParticleEffects.EffectGroup.None, true);
            }

            // Assign owner, to track original cause when they do something (e.g. kill something).
            manager.AddComponent <Owner>(entity).Initialize(emitter);

            return(entity);
        }