Пример #1
0
        public override void AddToken(IPEndPoint endPoint, uint token,
                                      TokenFlags tokenFlags)
        {
            if (token == TokenHelper.TokenNone)
            {
                return;
            }

            for (var i = 0; i < ConnlessPacketList.Count; i++)
            {
                var info = ConnlessPacketList[i];
                if (info.EndPoint.Compare(endPoint, true))
                {
                    info.SendCallback?.Invoke(info.TrackID, info.CallbackContext);
                    NetworkHelper.SendPacketConnless(Client,
                                                     info.EndPoint, token, TokenManager.GenerateToken(info.EndPoint),
                                                     info.Data, info.DataSize);

                    ConnlessPacketList.RemoveAt(i--);
                }
            }

            if (!tokenFlags.HasFlag(TokenFlags.ResponseOnly))
            {
                TokenCache.Add(new AddressInfo()
                {
                    EndPoint = endPoint,
                    Token    = token,
                    Expiry   = Time.Get() + Time.Freq() * TokenHelper.TokenCacheAddressExpiry
                });
            }
        }
Пример #2
0
 internal StringExpandableToken(InternalScriptExtent scriptExtent, TokenKind tokenKind, string value, string formatString, List<Token> nestedTokens, TokenFlags flags) : base(scriptExtent, tokenKind, flags, value)
 {
     if ((nestedTokens != null) && nestedTokens.Any<Token>())
     {
         this._nestedTokens = new ReadOnlyCollection<Token>(nestedTokens.ToArray());
     }
     this._formatString = formatString;
 }
Пример #3
0
 public void SetFlag(TokenFlags flag, bool on)
 {
     if (on)
     {
         _flags |= flag;
     }
     else
     {
         _flags &= ~flag;
     }
 }
Пример #4
0
        ///////////////////////////////////////////////////////////////////////

        public static bool HasFlags(
            TokenFlags flags,
            TokenFlags hasFlags,
            bool all
            )
        {
            if (all)
            {
                return((flags & hasFlags) == hasFlags);
            }
            else
            {
                return((flags & hasFlags) != TokenFlags.None);
            }
        }
Пример #5
0
        private void CreateTokens()
        {
            string[] tokenList = { maxDivTokenSymbol, nonDivisibleTokenSymbol };

            simulator.BeginBlock();

            foreach (var symbol in tokenList)
            {
                int        decimals = 0;
                BigInteger supply   = 0;
                TokenFlags flags    = TokenFlags.Divisible;

                switch (symbol)
                {
                case maxDivTokenSymbol:
                    decimals = NexusContract.MAX_TOKEN_DECIMALS;
                    supply   = UnitConversion.ToBigInteger(100000000, decimals);
                    flags    = TokenFlags.Transferable | TokenFlags.Fungible | TokenFlags.Finite | TokenFlags.Divisible;
                    break;

                case minDivTokenSymbol:
                    decimals = 1;
                    supply   = UnitConversion.ToBigInteger(100000000, 18);
                    flags    = TokenFlags.Transferable | TokenFlags.Fungible | TokenFlags.Finite | TokenFlags.Divisible;
                    break;

                case nonDivisibleTokenSymbol:
                    decimals = 0;
                    supply   = UnitConversion.ToBigInteger(100000000, 18);
                    flags    = TokenFlags.Transferable | TokenFlags.Fungible | TokenFlags.Finite;
                    break;
                }

                simulator.GenerateToken(simulatorOwner, symbol, $"{symbol}Token", DomainSettings.PlatformName, Hash.FromString(symbol), supply, decimals, flags);
                simulator.MintTokens(simulatorOwner, simulatorOwner.Address, symbol, supply);
            }

            simulator.EndBlock();
        }
Пример #6
0
 public bool IsSet(TokenFlags flag)
 {
     return((Flags & flag) != 0);
 }
Пример #7
0
 internal TokenInfo(string symbol, string name, BigInteger maxSupply, int decimals, TokenFlags flags, byte[] script)
 {
     this.Symbol    = symbol;
     this.Name      = name;
     this.Flags     = flags;
     this.Decimals  = decimals;
     this.MaxSupply = maxSupply;
     this.Script    = script;
 }
Пример #8
0
        public TokenInfo(string symbol, string name, Address owner, BigInteger maxSupply, int decimals, TokenFlags flags, byte[] script, ContractInterface ABI)
        {
            Throw.IfNullOrEmpty(symbol, nameof(symbol));
            Throw.IfNullOrEmpty(name, nameof(name));
            Throw.If(owner.IsNull, "token owner can't be null address");
            Throw.If(decimals < 0, "decimals can't be negative");
            Throw.If(flags == TokenFlags.None, "token must have flags set");
            Throw.If(script == null || script.Length == 0, "token script can't be empty");

            Throw.If(flags.HasFlag(TokenFlags.Swappable), "swappable swap can't be set in token creation");

            Throw.If(maxSupply < 0, "negative supply");
            Throw.If(maxSupply == 0 && flags.HasFlag(TokenFlags.Finite), "finite requires a supply");
            Throw.If(maxSupply > 0 && !flags.HasFlag(TokenFlags.Finite), "infinite requires no supply");

            if (!flags.HasFlag(TokenFlags.Fungible))
            {
                Throw.If(flags.HasFlag(TokenFlags.Divisible), "non-fungible token must be indivisible");
            }

            if (flags.HasFlag(TokenFlags.Divisible))
            {
                Throw.If(decimals <= 0, "divisible token must have decimals");
            }
            else
            {
                Throw.If(decimals > 0, "indivisible token can't have decimals");
            }

            this.Symbol    = symbol;
            this.Name      = name;
            this.Owner     = owner;
            this.Flags     = flags;
            this.Decimals  = decimals;
            this.MaxSupply = maxSupply;
            this.Script    = script;
            this.ABI       = ABI;
        }
Пример #9
0
 internal TokenInfo(string tokenString, TokenFlags flags, int precedence)
     : this(tokenString, flags) {
     _precedence = precedence;
 }
Пример #10
0
 /// <summary>
 /// Return true if the <ref>TokenKind</ref> has the given trait.
 /// </summary>
 public static bool HasTrait(this TokenKind kind, TokenFlags flag)
 {
     return (GetTraits(kind) & flag) != TokenFlags.None;
 }
Пример #11
0
 static TokenTraits()
 {
     TokenFlags[] flagsArray = new TokenFlags[0x9b];
     flagsArray[8] = TokenFlags.ParseModeInvariant;
     flagsArray[9] = TokenFlags.ParseModeInvariant;
     flagsArray[10] = TokenFlags.ParseModeInvariant;
     flagsArray[11] = TokenFlags.ParseModeInvariant;
     flagsArray[12] = TokenFlags.ParseModeInvariant;
     flagsArray[13] = TokenFlags.ParseModeInvariant;
     flagsArray[14] = TokenFlags.ParseModeInvariant;
     flagsArray[15] = TokenFlags.ParseModeInvariant;
     flagsArray[0x10] = TokenFlags.ParseModeInvariant;
     flagsArray[0x11] = TokenFlags.ParseModeInvariant;
     flagsArray[0x12] = TokenFlags.ParseModeInvariant;
     flagsArray[0x13] = TokenFlags.ParseModeInvariant;
     flagsArray[0x15] = TokenFlags.ParseModeInvariant;
     flagsArray[0x16] = TokenFlags.ParseModeInvariant;
     flagsArray[0x17] = TokenFlags.ParseModeInvariant;
     flagsArray[0x18] = TokenFlags.ParseModeInvariant;
     flagsArray[0x19] = TokenFlags.ParseModeInvariant;
     flagsArray[0x1a] = TokenFlags.ParseModeInvariant | TokenFlags.BinaryOperator;
     flagsArray[0x1b] = TokenFlags.ParseModeInvariant | TokenFlags.BinaryOperator;
     flagsArray[0x1c] = TokenFlags.ParseModeInvariant | TokenFlags.SpecialOperator;
     flagsArray[0x1d] = TokenFlags.ParseModeInvariant | TokenFlags.SpecialOperator;
     flagsArray[30] = TokenFlags.ParseModeInvariant | TokenFlags.UnaryOperator;
     flagsArray[0x1f] = TokenFlags.PrefixOrPostfixOperator | TokenFlags.DisallowedInRestrictedMode | TokenFlags.UnaryOperator;
     flagsArray[0x20] = TokenFlags.PrefixOrPostfixOperator | TokenFlags.DisallowedInRestrictedMode | TokenFlags.UnaryOperator;
     flagsArray[0x21] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceMask;
     flagsArray[0x22] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.SpecialOperator;
     flagsArray[0x23] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.SpecialOperator;
     flagsArray[0x24] = TokenFlags.CanConstantFold | TokenFlags.UnaryOperator;
     flagsArray[0x25] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceMultiply;
     flagsArray[0x26] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceMultiply;
     flagsArray[0x27] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceMultiply;
     flagsArray[40] = TokenFlags.CanConstantFold | TokenFlags.UnaryOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceAdd;
     flagsArray[0x29] = TokenFlags.CanConstantFold | TokenFlags.UnaryOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceAdd;
     flagsArray[0x2a] = TokenFlags.AssignmentOperator;
     flagsArray[0x2b] = TokenFlags.AssignmentOperator;
     flagsArray[0x2c] = TokenFlags.AssignmentOperator;
     flagsArray[0x2d] = TokenFlags.AssignmentOperator;
     flagsArray[0x2e] = TokenFlags.AssignmentOperator;
     flagsArray[0x2f] = TokenFlags.AssignmentOperator;
     flagsArray[0x30] = TokenFlags.DisallowedInRestrictedMode;
     flagsArray[0x31] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.ParseModeInvariant;
     flagsArray[50] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceFormat;
     flagsArray[0x33] = TokenFlags.CanConstantFold | TokenFlags.UnaryOperator;
     flagsArray[0x34] = TokenFlags.CanConstantFold | TokenFlags.UnaryOperator;
     flagsArray[0x35] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceLogical;
     flagsArray[0x36] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceLogical;
     flagsArray[0x37] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceLogical;
     flagsArray[0x38] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceBitwise;
     flagsArray[0x39] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceBitwise;
     flagsArray[0x3a] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceBitwise;
     flagsArray[0x3b] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.UnaryOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[60] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x3d] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x3e] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x3f] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x40] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x41] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x42] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x43] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x44] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x45] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[70] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x47] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x48] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x49] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x4a] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x4b] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.UnaryOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x4c] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x4d] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x4e] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x4f] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[80] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x51] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x52] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x53] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x54] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x55] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x56] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x57] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x58] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x59] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[90] = TokenFlags.CaseSensitiveOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x5b] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.CaseSensitiveOperator | TokenFlags.UnaryOperator | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x5c] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x5d] = TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x5e] = TokenFlags.DisallowedInRestrictedMode | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x5f] = TokenFlags.PrefixOrPostfixOperator | TokenFlags.DisallowedInRestrictedMode | TokenFlags.UnaryOperator;
     flagsArray[0x60] = TokenFlags.PrefixOrPostfixOperator | TokenFlags.DisallowedInRestrictedMode | TokenFlags.UnaryOperator;
     flagsArray[0x61] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x62] = TokenFlags.CanConstantFold | TokenFlags.BinaryOperator | TokenFlags.BinaryPrecedenceComparison;
     flagsArray[0x77] = TokenFlags.ScriptBlockBlockName | TokenFlags.Keyword;
     flagsArray[120] = TokenFlags.Keyword;
     flagsArray[0x79] = TokenFlags.Keyword;
     flagsArray[0x7a] = TokenFlags.Keyword;
     flagsArray[0x7b] = TokenFlags.Keyword;
     flagsArray[0x7c] = TokenFlags.Keyword;
     flagsArray[0x7d] = TokenFlags.Keyword;
     flagsArray[0x7e] = TokenFlags.Keyword;
     flagsArray[0x7f] = TokenFlags.ScriptBlockBlockName | TokenFlags.Keyword;
     flagsArray[0x80] = TokenFlags.Keyword;
     flagsArray[0x81] = TokenFlags.Keyword;
     flagsArray[130] = TokenFlags.ScriptBlockBlockName | TokenFlags.Keyword;
     flagsArray[0x83] = TokenFlags.Keyword;
     flagsArray[0x84] = TokenFlags.Keyword;
     flagsArray[0x85] = TokenFlags.Keyword;
     flagsArray[0x86] = TokenFlags.Keyword;
     flagsArray[0x87] = TokenFlags.Keyword;
     flagsArray[0x88] = TokenFlags.Keyword;
     flagsArray[0x89] = TokenFlags.Keyword;
     flagsArray[0x8a] = TokenFlags.Keyword;
     flagsArray[0x8b] = TokenFlags.Keyword;
     flagsArray[140] = TokenFlags.Keyword;
     flagsArray[0x8d] = TokenFlags.ScriptBlockBlockName | TokenFlags.Keyword;
     flagsArray[0x8e] = TokenFlags.Keyword;
     flagsArray[0x8f] = TokenFlags.Keyword;
     flagsArray[0x90] = TokenFlags.Keyword;
     flagsArray[0x91] = TokenFlags.Keyword;
     flagsArray[0x92] = TokenFlags.Keyword;
     flagsArray[0x93] = TokenFlags.Keyword;
     flagsArray[0x94] = TokenFlags.Keyword;
     flagsArray[0x95] = TokenFlags.Keyword;
     flagsArray[150] = TokenFlags.Keyword;
     flagsArray[0x97] = TokenFlags.Keyword;
     flagsArray[0x98] = TokenFlags.Keyword;
     flagsArray[0x99] = TokenFlags.Keyword;
     flagsArray[0x9a] = TokenFlags.Keyword;
     _staticTokenFlags = flagsArray;
     _tokenText = new string[] { 
         "unknown", "var", "@var", "param", "number", "label", "ident", "generic", "newline", "line continuation", "comment", "eof", "sqstr", "dqstr", "sq here string", "dq here string", 
         "(", ")", "{", "}", "[", "]", "@(", "@{", "$(", ";", "&&", "||", "&", "|", ",", "--", 
         "++", "..", "::", ".", "!", "*", "/", "%", "+", "-", "=", "+=", "-=", "*=", "/=", "%=", 
         "redirection", "<", "-f", "-not", "-bnot", "-and", "-or", "-xor", "-band", "-bor", "-bxor", "-join", "-eq", "-ne", "-ge", "-gt", 
         "-lt", "-le", "-ilike", "-inotlike", "-imatch", "-inotmatch", "-ireplace", "-icontains", "-inotcontains", "-iin", "-inotin", "-isplit", "-ceq", "-cne", "-cge", "-cgt", 
         "-clt", "-cle", "-clike", "-cnotlike", "-cmatch", "-cnotmatch", "-creplace", "-ccontains", "-cnotcontains", "-cin", "-cnotin", "-csplit", "-is", "-isnot", "-as", "++", 
         "--", "-shl", "-shr", "", "", "", "", "", "", "", "", "", "", "", "", "", 
         "", "", "", "", "", "", "", "begin", "break", "catch", "class", "continue", "data", "define", "do", "dynamicparam", 
         "else", "elseif", "end", "exit", "filter", "finally", "for", "foreach", "from", "function", "if", "in", "param", "process", "return", "switch", 
         "throw", "trap", "try", "until", "using", "var", "while", "workflow", "parallel", "sequence", "inlinescript"
      };
 }
Пример #12
0
 public abstract void AddToken(IPEndPoint endPoint,
                               uint token, TokenFlags tokenFlags);
Пример #13
0
        public Transaction GenerateToken(KeyPair owner, string symbol, string name, BigInteger totalSupply, int decimals, TokenFlags flags)
        {
            var chain = Nexus.RootChain;

            var script = ScriptUtils.
                         BeginScript().
                         AllowGas(owner.Address, Address.Null, 1, 9999).
                         CallContract("nexus", "CreateToken", owner.Address, symbol, name, totalSupply, decimals, flags).
                         SpendGas(owner.Address).
                         EndScript();

            var tx = MakeTransaction(owner, chain, script);

            tx.Sign(owner);

            return(tx);
        }
Пример #14
0
 internal StringLiteralToken(InternalScriptExtent scriptExtent, TokenFlags flags, TokenKind tokenKind, string value) : base(scriptExtent, tokenKind, flags, value)
 {
 }
Пример #15
0
        private static void DeployOrUpgrade(string[] args, SpookSettings settings, NexusAPI api, BigInteger minFee, bool isUpgrade)
        {
            if (args.Length != 1)
            {
                throw new CommandException("Invalid number of arguments, expected file name");
            }

            DoChecks(api);

            var fileName = args[0];

            if (!File.Exists(fileName))
            {
                throw new CommandException("Provided file does not exist");
            }

            if (!FileExistsCaseSensitive(fileName))
            {
                throw new CommandException("Provided file case does not match real file name case");
            }

            var extension = ScriptModule.ScriptExtension;

            if (!fileName.EndsWith(extension))
            {
                throw new CommandException($"Provided file is not a compiled {extension} script");
            }

            var abiFile = fileName.Replace(extension, ".abi");

            if (!File.Exists(abiFile))
            {
                throw new CommandException($"No ABI file {abiFile} that matches provided script file");
            }

            var contractName = Path.GetFileNameWithoutExtension(fileName);

            var contractScript = File.ReadAllBytes(fileName);
            var abiBytes       = File.ReadAllBytes(abiFile);

            var abi = ContractInterface.FromBytes(abiBytes);

            var sb = new ScriptBuilder();

            int nexusVersion = 0;

            try
            {
                var nexusDetails = api.Execute("getNexus", new object[] { false });
                var root         = LunarLabs.Parser.JSON.JSONReader.ReadFromString(nexusDetails);

                var governance = root["governance"];

                var entry = governance.Children.Where(x => x.GetNode("name").Value == "nexus.protocol.version").FirstOrDefault();
                entry = entry.GetNodeByIndex(1);

                nexusVersion = Int32.Parse(entry.Value);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                nexusVersion = -1;
            }

            if (nexusVersion <= 1)
            {
                throw new CommandException("Failed to obtain nexus version via API");
            }


            bool isToken        = ValidationUtils.IsValidTicker(contractName);
            var  availableFlags = Enum.GetValues(typeof(TokenFlags)).Cast <TokenFlags>().ToArray();

            sb.AllowGas(Keys.Address, Address.Null, minFee, 9999);

            if (isUpgrade)
            {
                // check for modification in flags
                if (isToken)
                {
                    var symbol    = contractName;
                    var resultStr = api.Execute("getToken", new[] { symbol, "false" });

                    logger.Debug($"{resultStr}");

                    //2021.08.27 sfichera: Fixed api obj deserialization.
                    //dynamic apiResult = System.Text.Json.JsonSerializer.Deserialize<TokenResult>(resultStr);
                    dynamic apiResult = JsonConvert.DeserializeObject <TokenResult>(resultStr);

                    if (apiResult is TokenResult)
                    {
                        var oldToken   = (TokenResult)apiResult;
                        var oldFlags   = TokenFlags.None;
                        var splitFlags = oldToken.flags.Split(',');
                        foreach (var entry in splitFlags)
                        {
                            TokenFlags flag;

                            if (Enum.TryParse <TokenFlags>(entry, true, out flag))
                            {
                                oldFlags |= flag;
                            }
                        }

                        foreach (var flag in availableFlags)
                        {
                            var propName = "is" + flag;
                            if (abi.HasMethod(propName))
                            {
                                var isSet  = ExecuteScript(contractScript, abi, propName).AsBool();
                                var wasSet = oldFlags.HasFlag(flag);
                                if (isSet != wasSet)
                                {
                                    throw new CommandException($"Detected '{flag}' flag change: {wasSet} => {isSet}");
                                }
                            }
                        }
                    }
                    else
                    {
                        throw new CommandException("could not find any deployed token contract for " + symbol);
                    }
                }

                sb.CallInterop("Runtime.UpgradeContract", Keys.Address, contractName, contractScript, abiBytes);
            }
            else
            if (isToken)
            {
                if (!abi.HasMethod("getName"))
                {
                    throw new CommandException("token contract is missing required 'name' property");
                }

                string symbol = null;


                if (nexusVersion < 6)
                {
                    symbol = contractName;
                }
                else
                {
                    if (abi.HasMethod("getSymbol"))
                    {
                        symbol = ExecuteScript(contractScript, abi, "getSymbol").AsString();
                    }

                    if (string.IsNullOrEmpty(symbol))
                    {
                        throw new CommandException("token contract 'symbol' property is either missing or returning an empty value");
                    }
                }

                var name = ExecuteScript(contractScript, abi, "getName").AsString();

                if (string.IsNullOrEmpty(name))
                {
                    throw new CommandException("token contract 'name' property is either missing or returning an empty value");
                }

                BigInteger maxSupply = abi.HasMethod("getMaxSupply") ? ExecuteScript(contractScript, abi, "getMaxSupply").AsNumber() : 0;
                BigInteger decimals  = abi.HasMethod("getDecimals") ? ExecuteScript(contractScript, abi, "getDecimals").AsNumber() : 0;

                TokenFlags flags = TokenFlags.None;

                foreach (var flag in availableFlags)
                {
                    var propName = "is" + flag;
                    if (abi.HasMethod(propName) && ExecuteScript(contractScript, abi, propName).AsBool())
                    {
                        flags |= flag;
                    }
                }

                if (nexusVersion < 6)
                {
                    sb.CallInterop("Nexus.CreateToken", Keys.Address, symbol, name, maxSupply, decimals, flags, contractScript, abiBytes);
                }
                else
                {
                    sb.CallInterop("Nexus.CreateToken", Keys.Address, contractScript, abiBytes);
                }

                contractName = symbol;
            }
            else
            {
                sb.CallInterop("Runtime.DeployContract", Keys.Address, contractName, contractScript, abiBytes);
            }

            sb.SpendGas(Keys.Address);
            var script = sb.EndScript();

            if (!isUpgrade)
            {
                var upgradeTrigger = AccountContract.GetTriggerForABI(AccountTrigger.OnUpgrade);
                if (abi.Implements(upgradeTrigger))
                {
                    logger.Message($"{contractName} implements proper triggers, and can be upgraded later.");
                }
                else
                {
                    logger.Warning($"{contractName} does not implements proper triggers, can't be upgraded later.");
                }
            }

            var hash = ExecuteTransaction(settings, api, script, ProofOfWork.Minimal, Keys);

            if (hash != Hash.Null)
            {
                var expectedEvent    = isUpgrade ? EventKind.ContractUpgrade : (isToken ? EventKind.TokenCreate : EventKind.ContractDeploy);
                var expectedEventStr = expectedEvent.ToString();

                var events = GetTransactionEvents(hash);
                if (events.Any(x => x.kind == expectedEventStr))
                {
                    var contractAddress = SmartContract.GetAddressForName(contractName);

                    string action = isUpgrade ? "Upgraded" : "Deployed";

                    logger.Message($"{action} {contractName} at {contractAddress}");
                }
                else
                {
                    throw new CommandException("Transaction was confirmed but deployment event is missing!");
                }
            }
        }
Пример #16
0
 internal UnscannedSubExprToken(InternalScriptExtent scriptExtent, TokenFlags tokenFlags, string value, BitArray skippedCharOffsets)
     : base(scriptExtent, tokenFlags, TokenKind.StringLiteral, value)
 {
     this.SkippedCharOffsets = skippedCharOffsets;
 }
Пример #17
0
 internal LabelToken(InternalScriptExtent scriptExtent, TokenFlags tokenFlags, string labelText)
     : base(scriptExtent, TokenKind.Label, tokenFlags)
 {
     LabelText = labelText;
 }
Пример #18
0
 internal VariableToken(InternalScriptExtent scriptExtent, VariablePath path, TokenFlags tokenFlags, bool splatted)
     : base(scriptExtent, splatted ? TokenKind.SplattedVariable : TokenKind.Variable, tokenFlags)
 {
     VariablePath = path;
 }
Пример #19
0
 /// <summary>
 /// Constructor
 /// </summary>
 public Token(string InText, TokenType InType, TokenFlags InFlags)
 {
     Text  = InText;
     Type  = InType;
     Flags = InFlags;
 }
Пример #20
0
        public void CreateToken(Address from, string symbol, string name, string platform, Hash hash, BigInteger maxSupply, BigInteger decimals, TokenFlags flags, byte[] script)
        {
            var pow = Runtime.Transaction.Hash.GetDifficulty();

            Runtime.Expect(pow >= (int)ProofOfWork.Minimal, "expected proof of work");

            Runtime.Expect(!string.IsNullOrEmpty(symbol), "token symbol required");
            Runtime.Expect(!string.IsNullOrEmpty(name), "token name required");
            Runtime.Expect(maxSupply >= 0, "token supply cant be negative");
            Runtime.Expect(decimals >= 0, "token decimals cant be negative");
            Runtime.Expect(decimals <= MAX_TOKEN_DECIMALS, $"token decimals cant exceed {MAX_TOKEN_DECIMALS}");

            Runtime.Expect(!Runtime.Nexus.TokenExists(symbol), "token already exists");

            if (symbol == Nexus.FuelTokenSymbol)
            {
                Runtime.Expect(flags.HasFlag(TokenFlags.Fuel), "token should be native");
            }
            else
            {
                Runtime.Expect(!flags.HasFlag(TokenFlags.Fuel), "token can't be native");
            }

            if (symbol == Nexus.StakingTokenSymbol)
            {
                Runtime.Expect(flags.HasFlag(TokenFlags.Stakable), "token should be stakable");
            }

            if (symbol == Nexus.FiatTokenSymbol)
            {
                Runtime.Expect(flags.HasFlag(TokenFlags.Fiat), "token should be fiat");
            }

            Runtime.Expect(!string.IsNullOrEmpty(platform), "chain name required");

            if (flags.HasFlag(TokenFlags.External))
            {
                Runtime.Expect(from == Runtime.Nexus.GenesisAddress, "genesis address only");
                Runtime.Expect(platform != Nexus.PlatformName, "external token chain required");
                Runtime.Expect(Runtime.Nexus.PlatformExists(platform), "platform not found");
            }
            else
            {
                Runtime.Expect(platform == Nexus.PlatformName, "chain name is invalid");
            }

            Runtime.Expect(IsWitness(from), "invalid witness");
            Runtime.Expect(from.IsUser, "owner address must be user address");

            Runtime.Expect(this.Runtime.Nexus.CreateToken(symbol, name, platform, hash, maxSupply, (int)decimals, flags, script), "token creation failed");
            Runtime.Notify(EventKind.TokenCreate, from, symbol);
        }
Пример #21
0
 internal StringToken(InternalScriptExtent scriptExtent, TokenKind kind, TokenFlags tokenFlags, string value) : base(scriptExtent, kind, tokenFlags)
 {
     this._value = value;
 }
Пример #22
0
 internal TokenInfo(string tokenString, TokenFlags flags, int precedence)
     : this(tokenString, flags)
 {
     _precedence = precedence;
 }
Пример #23
0
 internal NumberToken(InternalScriptExtent scriptExtent, object value, TokenFlags tokenFlags)
     : base(scriptExtent, TokenKind.Number, tokenFlags)
 {
     _value = value;
 }
Пример #24
0
 internal TokenInfo(string tokenString, TokenFlags flags)
 {
     _tokenString = tokenString;
     _flags       = flags;
     _precedence  = TokenInfo.InvalidPrecedence;
 }
Пример #25
0
 internal UnscannedSubExprToken(InternalScriptExtent scriptExtent, TokenFlags tokenFlags, string value, BitArray skippedCharOffsets) : base(scriptExtent, tokenFlags, TokenKind.StringLiteral, value)
 {
     this.SkippedCharOffsets = skippedCharOffsets;
 }
Пример #26
0
 internal StringExpandableToken(InternalScriptExtent scriptExtent, TokenKind tokenKind, string value, string formatString, List <Token> nestedTokens, TokenFlags flags) : base(scriptExtent, tokenKind, flags, value)
 {
     if ((nestedTokens != null) && nestedTokens.Any <Token>())
     {
         this._nestedTokens = new ReadOnlyCollection <Token>(nestedTokens.ToArray());
     }
     this._formatString = formatString;
 }
Пример #27
0
        private Transaction TokenCreateTx(Chain chain, KeyPair owner, string symbol, string name, BigInteger totalSupply, int decimals, TokenFlags flags, bool useGas)
        {
            var sb = ScriptUtils.BeginScript();

            if (useGas)
            {
                sb.AllowGas(owner.Address, Address.Null, 1, 9999);
            }

            sb.CallContract(ScriptBuilderExtensions.NexusContract, "CreateToken", owner.Address, symbol, name, totalSupply, decimals, flags);

            if (symbol == StakingTokenSymbol)
            {
                sb.CallContract(ScriptBuilderExtensions.TokenContract, "MintTokens", owner.Address, symbol, UnitConversion.ToBigInteger(8863626, StakingTokenDecimals));
            }
            else
            if (symbol == FuelTokenSymbol)
            {
                // requires staking token to be created previously
                // note this is a completly arbitrary number just to be able to generate energy in the genesis, better change it later
                sb.CallContract(ScriptBuilderExtensions.EnergyContract, "Stake", owner.Address, UnitConversion.ToBigInteger(100000, StakingTokenDecimals));
                sb.CallContract(ScriptBuilderExtensions.EnergyContract, "Claim", owner.Address, owner.Address);
            }

            if (useGas)
            {
                sb.SpendGas(owner.Address);
            }

            var script = sb.EndScript();

            var tx = new Transaction(Name, chain.Name, script, Timestamp.Now + TimeSpan.FromDays(300));

            tx.Sign(owner);

            return(tx);
        }
Пример #28
0
 public bool CreateToken(string symbol, string name, string platform, Hash hash, BigInteger maxSupply, int decimals, TokenFlags flags, byte[] script)
 {
     return(Nexus.CreateToken(symbol, name, platform, hash, maxSupply, decimals, flags, script));
 }
Пример #29
0
        internal Token(Address owner, string symbol, string name, BigInteger maxSupply, int decimals, TokenFlags flags)
        {
            Throw.If(maxSupply < 0, "negative supply");
            Throw.If(maxSupply == 0 && flags.HasFlag(TokenFlags.Finite), "finite requires a supply");
            Throw.If(maxSupply > 0 && !flags.HasFlag(TokenFlags.Finite), "infinite requires no supply");

            if (!flags.HasFlag(TokenFlags.Fungible))
            {
                Throw.If(flags.HasFlag(TokenFlags.Divisible), "non-fungible token must be indivisible");
            }

            if (flags.HasFlag(TokenFlags.Divisible))
            {
                Throw.If(decimals <= 0, "divisible token must have decimals");
            }
            else
            {
                Throw.If(decimals > 0, "indivisible token can't have decimals");
            }

            this.Owner     = owner;
            this.Symbol    = symbol;
            this.Name      = name;
            this.MaxSupply = maxSupply;
            this.Decimals  = decimals;
            this.Flags     = flags;

            _supply = 0;
        }
Пример #30
0
        private Transaction TokenCreateTx(Chain chain, KeyPair owner, string symbol, string name, BigInteger totalSupply, int decimals, TokenFlags flags)
        {
            var sb = ScriptUtils.BeginScript();

            if (symbol != FuelTokenSymbol)
            {
                sb.AllowGas(owner.Address, Address.Null, 1, 9999);
            }

            sb.CallContract(ScriptBuilderExtensions.NexusContract, "CreateToken", owner.Address, symbol, name, totalSupply, decimals, flags);

            if (symbol == FuelTokenSymbol)
            {
                sb.CallContract(ScriptBuilderExtensions.TokenContract, "MintTokens", owner.Address, symbol, totalSupply);
                sb.AllowGas(owner.Address, Address.Null, 1, 9999); // done here only because before fuel token does not exist yet!
            }
            else
            if (symbol == StakingTokenSymbol)
            {
                sb.CallContract(ScriptBuilderExtensions.TokenContract, "MintTokens", owner.Address, symbol, UnitConversion.ToBigInteger(8863626, StakingTokenDecimals));
            }

            var script = sb.SpendGas(owner.Address).EndScript();

            var tx = new Transaction(Name, chain.Name, script, Timestamp.Now + TimeSpan.FromDays(300));

            tx.Sign(owner);

            return(tx);
        }
Пример #31
0
 internal TokenInfo(string tokenString, TokenFlags flags) {
     _tokenString = tokenString;
     _flags = flags;
     _precedence = TokenInfo.InvalidPrecedence;
 }
Пример #32
0
 internal LabelToken(InternalScriptExtent scriptExtent, TokenFlags tokenFlags, string labelText) : base(scriptExtent, TokenKind.Label, tokenFlags)
 {
     this._labelText = labelText;
 }
Пример #33
0
        internal bool CreateToken(Address owner, string symbol, string name, BigInteger maxSupply, int decimals, TokenFlags flags, byte[] script)
        {
            if (symbol == null || name == null || maxSupply < 0)
            {
                return(false);
            }

            symbol = symbol.ToUpper();

            // check if already exists something with that name
            if (TokenExists(symbol))
            {
                return(false);
            }

            Throw.If(maxSupply < 0, "negative supply");
            Throw.If(maxSupply == 0 && flags.HasFlag(TokenFlags.Finite), "finite requires a supply");
            Throw.If(maxSupply > 0 && !flags.HasFlag(TokenFlags.Finite), "infinite requires no supply");

            if (!flags.HasFlag(TokenFlags.Fungible))
            {
                Throw.If(flags.HasFlag(TokenFlags.Divisible), "non-fungible token must be indivisible");
            }

            if (flags.HasFlag(TokenFlags.Divisible))
            {
                Throw.If(decimals <= 0, "divisible token must have decimals");
            }
            else
            {
                Throw.If(decimals > 0, "indivisible token can't have decimals");
            }

            var tokenInfo = new TokenInfo(owner, symbol, name, maxSupply, decimals, flags, script);

            EditToken(symbol, tokenInfo);

            // add to persistent list of tokens
            var tokenList = this.Tokens.ToList();

            tokenList.Add(symbol);
            this.Tokens = tokenList;

            return(true);
        }
Пример #34
0
        internal Token CreateToken(Address owner, string symbol, string name, BigInteger maxSupply, int decimals, TokenFlags flags)
        {
            if (symbol == null || name == null || maxSupply < 0)
            {
                return(null);
            }

            // check if already exists something with that name
            var temp = FindTokenBySymbol(symbol);

            if (temp != null)
            {
                return(null);
            }

            var token = new Token(owner, symbol, name, maxSupply, decimals, flags);

            if (symbol == FuelTokenSymbol)
            {
                FuelToken = token;
            }
            else
            if (symbol == StakingTokenSymbol)
            {
                StakingToken = token;
            }
            else
            if (symbol == StableTokenSymbol)
            {
                StableToken = token;
            }

            _tokens[symbol] = token;

            return(token);
        }
Пример #35
0
        public void CreateToken(Address owner, string symbol, string name, BigInteger maxSupply, BigInteger decimals, TokenFlags flags, byte[] script)
        {
            Runtime.Expect(!string.IsNullOrEmpty(symbol), "token symbol required");
            Runtime.Expect(!string.IsNullOrEmpty(name), "token name required");
            Runtime.Expect(maxSupply >= 0, "token supply cant be negative");
            Runtime.Expect(decimals >= 0, "token decimals cant be negative");
            Runtime.Expect(decimals <= MAX_TOKEN_DECIMALS, $"token decimals cant exceed {MAX_TOKEN_DECIMALS}");

            if (symbol == Nexus.FuelTokenSymbol)
            {
                Runtime.Expect(flags.HasFlag(TokenFlags.Fuel), "token should be native");
            }
            else
            {
                Runtime.Expect(!flags.HasFlag(TokenFlags.Fuel), "token can't be native");
            }

            if (symbol == Nexus.StakingTokenSymbol)
            {
                Runtime.Expect(flags.HasFlag(TokenFlags.Stakable), "token should be stakable");
            }

            if (symbol == Nexus.StableTokenSymbol)
            {
                Runtime.Expect(flags.HasFlag(TokenFlags.Stable), "token should be stable");
            }

            if (flags.HasFlag(TokenFlags.External))
            {
                Runtime.Expect(owner == Runtime.Nexus.GenesisAddress, "external token not permitted");
            }

            Runtime.Expect(IsWitness(owner), "invalid witness");

            symbol = symbol.ToUpperInvariant();

            Runtime.Expect(this.Runtime.Nexus.CreateToken(owner, symbol, name, maxSupply, (int)decimals, flags, script), "token creation failed");
            Runtime.Notify(EventKind.TokenCreate, owner, symbol);
        }
Пример #36
0
        public Transaction GenerateToken(PhantasmaKeys owner, string symbol, string name, BigInteger totalSupply, int decimals, TokenFlags flags, byte[] tokenScript = null)
        {
            if (tokenScript == null)
            {
                // small script that restricts minting of tokens to transactions where the owner is a witness
                var addressStr = Base16.Encode(owner.Address.ToByteArray());
                var scriptString = new string[] {
                $"alias r1, $triggerMint",
                $"alias r2, $currentTrigger",
                $"alias r3, $result",
                $"alias r4, $owner",

                $@"load $triggerMint, ""{AccountTrigger.OnMint}""",
                $"pop $currentTrigger",

                $"equal $triggerMint, $currentTrigger, $result",
                $"jmpif $result, @mintHandler",
                $"jmp @end",

                $"@mintHandler: nop",
                $"load $owner 0x{addressStr}",
                "push $owner",
                "extcall \"Address()\"",
                "extcall \"Runtime.IsWitness\"",
                "pop $result",
                $"jmpif $result, @end",
                $"throw",

                $"@end: ret"
                };
                tokenScript = AssemblerUtils.BuildScript(scriptString);
            }

            var script = ScriptUtils.
                BeginScript().
                AllowGas(owner.Address, Address.Null, MinimumFee, 9999).
                CallInterop("Nexus.CreateToken", owner.Address, symbol, name, totalSupply, decimals, flags, tokenScript).
                SpendGas(owner.Address).
                EndScript();

            var tx = MakeTransaction(owner, ProofOfWork.Minimal, Nexus.RootChain, script);

            return tx;
        }
Пример #37
0
        public void CreateToken(Address from, string symbol, string name, BigInteger maxSupply, int decimals, TokenFlags flags, byte[] script)
        {
            var Runtime = this;

            Runtime.Expect(Runtime.IsRootChain(), "must be root chain");

            var pow = Runtime.Transaction.Hash.GetDifficulty();

            Runtime.Expect(pow >= (int)ProofOfWork.Minimal, "expected proof of work");

            Runtime.Expect(!string.IsNullOrEmpty(symbol), "token symbol required");
            Runtime.Expect(!string.IsNullOrEmpty(name), "token name required");

            Runtime.Expect(ValidationUtils.IsValidTicker(symbol), "invalid symbol");
            Runtime.Expect(!Runtime.TokenExists(symbol), "token already exists");

            Runtime.Expect(maxSupply >= 0, "token supply cant be negative");
            Runtime.Expect(decimals >= 0, "token decimals cant be negative");
            Runtime.Expect(decimals <= DomainSettings.MAX_TOKEN_DECIMALS, $"token decimals cant exceed {DomainSettings.MAX_TOKEN_DECIMALS}");

            if (symbol == DomainSettings.FuelTokenSymbol)
            {
                Runtime.Expect(flags.HasFlag(TokenFlags.Fuel), "token should be native");
            }
            else
            {
                Runtime.Expect(!flags.HasFlag(TokenFlags.Fuel), "token can't be native");
            }

            if (symbol == DomainSettings.StakingTokenSymbol)
            {
                Runtime.Expect(flags.HasFlag(TokenFlags.Stakable), "token should be stakable");
            }

            if (symbol == DomainSettings.FiatTokenSymbol)
            {
                Runtime.Expect(flags.HasFlag(TokenFlags.Fiat), "token should be fiat");
            }

            if (!flags.HasFlag(TokenFlags.Fungible))
            {
                Runtime.Expect(!flags.HasFlag(TokenFlags.Divisible), "non-fungible token must be indivisible");
            }

            if (flags.HasFlag(TokenFlags.Divisible))
            {
                Runtime.Expect(decimals > 0, "divisible token must have decimals");
            }
            else
            {
                Runtime.Expect(decimals == 0, "indivisible token can't have decimals");
            }

            Runtime.Expect(from.IsUser, "owner address must be user address");
            Runtime.Expect(Runtime.IsStakeMaster(from), "needs to be master");
            Runtime.Expect(Runtime.IsWitness(from), "invalid witness");

            Nexus.CreateToken(RootStorage, symbol, name, maxSupply, decimals, flags, script);
            Runtime.Notify(EventKind.TokenCreate, from, symbol);
        }
Пример #38
0
 public void SetFlag(TokenFlags flag, bool on)
 {
     if (on) { _flags |= flag; }
     else { _flags &= ~flag; }
 }
        /// <summary>
        /// Reads a single token from a text buffer
        /// </summary>
        /// <param name="Text">The text buffer to read from</param>
        /// <param name="LineIdx">The current line index</param>
        /// <param name="ColumnIdx">The current column index</param>
        /// <param name="Flags">Flags for the new token</param>
        /// <returns>The next token, or null at the end of the file</returns>
        static bool ReadToken(TextBuffer Text, ref int LineIdx, ref int ColumnIdx, TokenFlags Flags, TokenReaderContext Context, out Token Result)
        {
            int StartLineIdx   = LineIdx;
            int StartColumnIdx = ColumnIdx;

            char Character = Text.ReadCharacter(ref LineIdx, ref ColumnIdx);

            if (Character == '\0')
            {
                Result = new Token("", TokenType.Placemarker, Flags);
                return(false);
            }
            else if (Context.HasFlag(TokenReaderContext.TokenString))
            {
                // Raw token string until the end of the current line
                StringBuilder Builder = new StringBuilder();
                if (Character == '\n')
                {
                    LineIdx   = StartLineIdx;
                    ColumnIdx = StartColumnIdx;
                }
                else
                {
                    Builder.Append(Character);
                    for (;;)
                    {
                        Character = Text[LineIdx, ColumnIdx];
                        if (Character == '\n')
                        {
                            break;
                        }
                        Builder.Append(Character);
                        if (!Text.MoveNext(ref LineIdx, ref ColumnIdx))
                        {
                            break;
                        }
                    }
                }
                Result = new Token(Builder.ToString().TrimEnd(), TokenType.StringOfTokens, Flags);
                return(true);
            }
            else if (Character == '\'')
            {
                // Character literal
                SkipTextLiteral(Text, ref LineIdx, ref ColumnIdx, '\'');
                Result = new Token(Text.ExtractString(StartLineIdx, StartColumnIdx, LineIdx, ColumnIdx), TokenType.CharacterLiteral, Flags);
                return(true);
            }
            else if (Character == '\"')
            {
                // String literal
                SkipTextLiteral(Text, ref LineIdx, ref ColumnIdx, '\"');
                Result = new Token(Text.ExtractString(StartLineIdx, StartColumnIdx, LineIdx, ColumnIdx), TokenType.StringLiteral, Flags);
                return(true);
            }
            else if ((Character >= 'a' && Character <= 'z') || (Character >= 'A' && Character <= 'Z') || Character == '_')
            {
                // Identifier (or text literal with prefix)
                for (;;)
                {
                    Character = Text[LineIdx, ColumnIdx];
                    if ((Character < 'a' || Character > 'z') && (Character < 'A' || Character > 'Z') && (Character < '0' || Character > '9') && Character != '_' && Character != '$')
                    {
                        break;
                    }
                    Text.MoveNext(ref LineIdx, ref ColumnIdx);
                }

                // Check if it's a prefixed text literal
                if (Character == '\'')
                {
                    Text.MoveNext(ref LineIdx, ref ColumnIdx);
                    SkipTextLiteral(Text, ref LineIdx, ref ColumnIdx, '\'');
                    Result = new Token(Text.ExtractString(StartLineIdx, StartColumnIdx, LineIdx, ColumnIdx), TokenType.CharacterLiteral, Flags);
                    return(true);
                }
                else if (Character == '\"')
                {
                    Text.MoveNext(ref LineIdx, ref ColumnIdx);
                    SkipTextLiteral(Text, ref LineIdx, ref ColumnIdx, '\"');
                    Result = new Token(Text.ExtractString(StartLineIdx, StartColumnIdx, LineIdx, ColumnIdx), TokenType.StringLiteral, Flags);
                    return(true);
                }
                else
                {
                    Result = new Token(Text.ExtractString(StartLineIdx, StartColumnIdx, LineIdx, ColumnIdx), TokenType.Identifier, Flags);
                    return(true);
                }
            }
            else if ((Character >= '0' && Character <= '9') || (Character == '.' && (Text[LineIdx, ColumnIdx] >= '0' && Text[LineIdx, ColumnIdx] <= '9')))
            {
                // pp-number token
                char LastCharacter = Character;
                for (;;)
                {
                    Character = Text[LineIdx, ColumnIdx];
                    if ((Character < 'a' || Character > 'z') && (Character < 'A' || Character > 'Z') && (Character < '0' || Character > '9') && Character != '_' && Character != '$' && Character != '\'')
                    {
                        if ((Character != '+' && Character != '-') || (LastCharacter != 'e' && LastCharacter != 'E'))
                        {
                            break;
                        }
                    }
                    LastCharacter = Text.ReadCharacter(ref LineIdx, ref ColumnIdx);
                }
                Result = new Token(Text.ExtractString(StartLineIdx, StartColumnIdx, LineIdx, ColumnIdx), TokenType.NumericLiteral, Flags);
                return(true);
            }
            else if (Character == '<' && Context.HasFlag(TokenReaderContext.IncludeDirective))
            {
                StringBuilder Builder = new StringBuilder("<");
                while (Builder[Builder.Length - 1] != '>')
                {
                    Builder.Append(Text[LineIdx, ColumnIdx]);
                    ColumnIdx++;
                }
                Result = new Token(Builder.ToString(), TokenType.SystemInclude, Flags);
                return(true);
            }
            else
            {
                // Try to read a symbol
                if (ColumnIdx > 0)
                {
                    for (int Idx = 0; Idx < SymbolicTokens.Length; Idx++)
                    {
                        string SymbolicToken = SymbolicTokens[Idx];
                        for (int Length = 0; Text[LineIdx, ColumnIdx + Length - 1] == SymbolicToken[Length]; Length++)
                        {
                            if (Length + 1 == SymbolicToken.Length)
                            {
                                ColumnIdx += Length;
                                Result     = new Token(SymbolicToken, TokenType.Symbol, Flags);
                                return(true);
                            }
                        }
                    }
                }

                // Otherwise just return a single character
                TokenType Type;
                switch (Character)
                {
                case '(':
                    Type = TokenType.LeftParen;
                    break;

                case ')':
                    Type = TokenType.RightParen;
                    break;

                case ',':
                    Type = TokenType.Comma;
                    break;

                default:
                    Type = TokenType.Symbol;
                    break;
                }
                Result = new Token(Character.ToString(), Type, Flags);
                return(true);
            }
        }
Пример #40
0
 internal TokenInfo(Address owner, string symbol, string name, BigInteger maxSupply, int decimals, TokenFlags flags)
 {
     this.Owner     = owner;
     this.Symbol    = symbol;
     this.Name      = name;
     this.Flags     = flags;
     this.Decimals  = decimals;
     this.MaxSupply = maxSupply;
 }
Пример #41
0
        public Transaction GenerateToken(PhantasmaKeys owner, string symbol, string name, BigInteger totalSupply,
                                         int decimals, TokenFlags flags, byte[] tokenScript = null, Dictionary <string, int> labels = null,
                                         IEnumerable <ContractMethod> customMethods         = null, uint seriesID = 0)
        {
            var version = _cli.Nexus.GetGovernanceValue(_cli.Nexus.RootStorage, Nexus.NexusProtocolVersionTag);

            labels ??= new Dictionary <string, int>();

            if (tokenScript == null)
            {
                // small script that restricts minting of tokens to transactions where the owner is a witness
                var      addressStr = Base16.Encode(owner.Address.ToByteArray());
                string[] scriptString;

                if (version >= 4)
                {
                    scriptString = new[] {
                        $"alias r3, $result",
                        $"alias r4, $owner",
                        $"@{AccountTrigger.OnMint}: nop",
                        $"load $owner 0x{addressStr}",
                        "push $owner",
                        "extcall \"Address()\"",
                        "extcall \"Runtime.IsWitness\"",
                        "pop $result",
                        $"jmpif $result, @end",
                        $"load r0 \"invalid witness\"",
                        $"throw r0",

                        $"@getOwner: nop",
                        $"load $owner 0x{addressStr}",
                        "push $owner",
                        $"jmp @end",

                        $"@getSymbol: nop",
                        $"load r0 \"" + symbol + "\"",
                        "push r0",
                        $"jmp @end",

                        $"@getName: nop",
                        $"load r0 \"" + name + "\"",
                        "push r0",
                        $"jmp @end",

                        $"@getMaxSupply: nop",
                        $"load r0 " + totalSupply + "",
                        "push r0",
                        $"jmp @end",

                        $"@getDecimals: nop",
                        $"load r0 " + decimals + "",
                        "push r0",
                        $"jmp @end",

                        $"@getTokenFlags: nop",
                        $"load r0 " + (int)flags + "",
                        "push r0",
                        $"jmp @end",

                        $"@end: ret"
                    };
                }
                else
                {
                    scriptString = new string[] {
                        $"alias r1, $triggerMint",
                        $"alias r2, $currentTrigger",
                        $"alias r3, $result",
                        $"alias r4, $owner",

                        $@"load $triggerMint, ""{AccountTrigger.OnMint}""",
                        $"pop $currentTrigger",

                        $"equal $triggerMint, $currentTrigger, $result",
                        $"jmpif $result, @mintHandler",
                        $"jmp @end",

                        $"@mintHandler: nop",
                        $"load $owner 0x{addressStr}",
                        "push $owner",
                        "extcall \"Address()\"",
                        "extcall \"Runtime.IsWitness\"",
                        "pop $result",
                        $"jmpif $result, @end",
                        $"load r0 \"invalid witness\"",
                        $"throw r0",

                        $"@end: ret"
                    };
                }
                DebugInfo debugInfo;
                tokenScript = AssemblerUtils.BuildScript(scriptString, "GenerateToken", out debugInfo, out labels);
            }

            var sb = ScriptUtils.
                     BeginScript().
                     AllowGas(owner.Address, Address.Null, 100000, 9999);

            if (version >= 4)
            {
                var triggerMap = new Dictionary <AccountTrigger, int>();

                var onMintLabel = AccountTrigger.OnMint.ToString();
                if (labels.ContainsKey(onMintLabel))
                {
                    triggerMap[AccountTrigger.OnMint] = labels[onMintLabel];
                }

                var methods = AccountContract.GetTriggersForABI(triggerMap);

                if (version >= 6)
                {
                    methods = methods.Concat(new ContractMethod[] {
                        new ("getOwner", VMType.Object, labels, new ContractParameter[0]),
                        new ("getSymbol", VMType.String, labels, new ContractParameter[0]),
                        new ("getName", VMType.String, labels, new ContractParameter[0]),
                        new ("getDecimals", VMType.Number, labels, new ContractParameter[0]),
                        new ("getMaxSupply", VMType.Number, labels, new ContractParameter[0]),
                        new ("getTokenFlags", VMType.Enum, labels, new ContractParameter[0]),
                    });
Пример #42
0
 internal Token(InternalScriptExtent scriptExtent, TokenKind kind, TokenFlags tokenFlags)
 {
     _scriptExtent = scriptExtent;
     _kind = kind;
     _tokenFlags = tokenFlags | kind.GetTraits();
 }
Пример #43
0
        public Transaction GenerateToken(PhantasmaKeys owner, string symbol, string name, BigInteger totalSupply,
                                         int decimals, TokenFlags flags, byte[] tokenScript = null, Dictionary <string, int> labels = null, IEnumerable <ContractMethod> customMethods = null)
        {
            var version = Nexus.GetGovernanceValue(Nexus.RootStorage, Nexus.NexusProtocolVersionTag);

            if (labels == null)
            {
                labels = new Dictionary <string, int>();
            }

            if (tokenScript == null)
            {
                // small script that restricts minting of tokens to transactions where the owner is a witness
                var      addressStr = Base16.Encode(owner.Address.ToByteArray());
                string[] scriptString;

                if (version >= 4)
                {
                    scriptString = new string[] {
                        $"alias r3, $result",
                        $"alias r4, $owner",
                        $"@{AccountTrigger.OnMint}: nop",
                        $"load $owner 0x{addressStr}",
                        "push $owner",
                        "extcall \"Address()\"",
                        "extcall \"Runtime.IsWitness\"",
                        "pop $result",
                        $"jmpif $result, @end",
                        $"load r0 \"invalid witness\"",
                        $"throw r0",

                        $"@end: ret"
                    };
                }
                else
                {
                    scriptString = new string[] {
                        $"alias r1, $triggerMint",
                        $"alias r2, $currentTrigger",
                        $"alias r3, $result",
                        $"alias r4, $owner",

                        $@"load $triggerMint, ""{AccountTrigger.OnMint}""",
                        $"pop $currentTrigger",

                        $"equal $triggerMint, $currentTrigger, $result",
                        $"jmpif $result, @mintHandler",
                        $"jmp @end",

                        $"@mintHandler: nop",
                        $"load $owner 0x{addressStr}",
                        "push $owner",
                        "extcall \"Address()\"",
                        "extcall \"Runtime.IsWitness\"",
                        "pop $result",
                        $"jmpif $result, @end",
                        $"load r0 \"invalid witness\"",
                        $"throw r0",

                        $"@end: ret"
                    };
                }
                DebugInfo debugInfo;
                tokenScript = AssemblerUtils.BuildScript(scriptString, "GenerateToken", out debugInfo, out labels);
            }

            var sb = ScriptUtils.
                     BeginScript().
                     AllowGas(owner.Address, Address.Null, MinimumFee, 9999);

            if (version >= 4)
            {
                var triggerMap = new Dictionary <AccountTrigger, int>();

                var onMintLabel = AccountTrigger.OnMint.ToString();
                if (labels.ContainsKey(onMintLabel))
                {
                    triggerMap[AccountTrigger.OnMint] = labels[onMintLabel];
                }

                var methods = AccountContract.GetTriggersForABI(triggerMap);

                if (customMethods != null)
                {
                    methods = methods.Concat(customMethods);
                }

                var abi      = new ContractInterface(methods, Enumerable.Empty <ContractEvent>());
                var abiBytes = abi.ToByteArray();

                sb.CallInterop("Nexus.CreateToken", owner.Address, symbol, name, totalSupply, decimals, flags, tokenScript, abiBytes);
            }
            else
            {
                sb.CallInterop("Nexus.CreateToken", owner.Address, symbol, name, totalSupply, decimals, flags, tokenScript);
            }

            if (!flags.HasFlag(TokenFlags.Fungible))
            {
                ContractInterface nftABI;
                byte[]            nftScript;
                NFTUtils.GenerateNFTDummyScript(symbol, name, name, "http://simulator/nft/*", "http://simulator/img/*", out nftScript, out nftABI);
                sb.CallInterop("Nexus.CreateTokenSeries", owner.Address, symbol, new BigInteger(0), totalSupply, TokenSeriesMode.Unique, nftScript, nftABI.ToByteArray());
            }

            sb.SpendGas(owner.Address);

            var script = sb.EndScript();

            var tx = MakeTransaction(owner, ProofOfWork.Minimal, Nexus.RootChain, script);

            return(tx);
        }
Пример #44
0
 internal VariableToken(InternalScriptExtent scriptExtent, System.Management.Automation.VariablePath path, TokenFlags tokenFlags, bool splatted) : base(scriptExtent, splatted ? TokenKind.SplattedVariable : TokenKind.Variable, tokenFlags)
 {
     this.VariablePath = path;
 }