Ejemplo n.º 1
0
        public static string CallContractFunction(string senderPrivateKey, string operation, params object[] param)
        {
            try
            {
                // Create a new RPC client that is connected to a private test network
                RpcClient client = new RpcClient("http://localhost:10332");

                // Initialize the script that will be executed by the neo VM
                UInt160 contractHash = UInt160.Parse(SmartContractHash);
                byte[]  script       = contractHash.MakeScript(operation, param);

                // Generate a keypair from the sender's private key
                KeyPair senderKeyPair = Neo.Network.RPC.Utility.GetKeyPair(senderPrivateKey);
                UInt160 sender        = Contract.CreateSignatureContract(senderKeyPair.PublicKey).ScriptHash;
                Signer  signer        = new Signer()
                {
                    Scopes  = WitnessScope.CalledByEntry,
                    Account = sender
                };

                var result = client.InvokeScript(script, signer);
                return(result.Stack.Single().GetString());
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Get token information in one rpc call
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <returns></returns>
        public RpcNep5TokenInfo GetTokenInfo(UInt160 scriptHash)
        {
            byte[] script = Concat(scriptHash.MakeScript("name"),
                                   scriptHash.MakeScript("symbol"),
                                   scriptHash.MakeScript("decimals"),
                                   scriptHash.MakeScript("totalSupply"));

            var result = rpcClient.InvokeScript(script).Stack;

            return(new RpcNep5TokenInfo
            {
                Name = result[0].GetString(),
                Symbol = result[1].GetString(),
                Decimals = (byte)result[2].GetInteger(),
                TotalSupply = result[3].GetInteger()
            });
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");


            /// Instruction: https://docs.neo.org/v3/docs/en-us/tooldev/sdk/transaction.html#transaction-construction-process
            // choose a neo node with rpc opened
            RpcClient client = new RpcClient("http://seed1t.neo.org:20332");



            // construct the script
            ReadOnlySpan <byte> myContractSpan = Encoding.Default.GetBytes(myContractScriptHash);
            UInt160             scriptHash     = new UInt160(myContractSpan);

            byte[] script = scriptHash.MakeScript("addAgText", "String for test");


            // get ScriptHash of KeyPair account
            KeyPair sendKey = Neo.Network.RPC.Utility.GetKeyPair(privateKey);
            UInt160 sender  = Contract.CreateSignatureContract(sendKey.PublicKey).ScriptHash;


            // add Cosigners, which is a collection of scripthashs that need to be signed
            Cosigner[] cosigners = new[] { new Cosigner {
                                               Scopes = WitnessScope.CalledByEntry, Account = sender
                                           } };

            // initialize the TransactionManager with rpc client and sender scripthash
            TransactionManager txManager = new TransactionManager(client, sender);

            // fill the script, attributes and cosigners
            txManager.MakeTransaction(script, null, cosigners);

            // add signature for the transaction with sendKey
            txManager.AddSignature(sendKey);

            // sign transaction with the added signature
            txManager.Sign();

            Transaction tx = txManager.Tx;


            // broadcasts the transaction over the Neo network
            client.SendRawTransaction(tx);

            Console.WriteLine("Done");

            // print a message after the transaction is on chain
            WalletAPI neoAPI = new WalletAPI(client);

            neoAPI.WaitTransaction(tx)
            .ContinueWith(async(p) => Console.WriteLine($"Transaction vm state is  {(await p).VMState}"));

            Console.ReadKey();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Get token information in one rpc call
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <returns></returns>
        public async Task <RpcNep5TokenInfo> GetTokenInfoAsync(UInt160 scriptHash)
        {
            byte[] script = Concat(
                scriptHash.MakeScript("name"),
                scriptHash.MakeScript("symbol"),
                scriptHash.MakeScript("decimals"),
                scriptHash.MakeScript("totalSupply"));

            var result = await rpcClient.InvokeScriptAsync(script).ConfigureAwait(false);

            var stack = result.Stack;

            return(new RpcNep5TokenInfo
            {
                Name = stack[0].GetString(),
                Symbol = stack[1].GetString(),
                Decimals = (byte)stack[2].GetInteger(),
                TotalSupply = stack[3].GetInteger()
            });
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Get token information in one rpc call
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <returns></returns>
        public async Task <RpcNep17TokenInfo> GetTokenInfoAsync(UInt160 scriptHash)
        {
            var contractState = await rpcClient.GetContractStateAsync(scriptHash.ToString()).ConfigureAwait(false);

            byte[] script = Concat(
                scriptHash.MakeScript("symbol", true),
                scriptHash.MakeScript("decimals", true),
                scriptHash.MakeScript("totalSupply", true));
            var name   = contractState.Manifest.Name;
            var result = await rpcClient.InvokeScriptAsync(script).ConfigureAwait(false);

            var stack = result.Stack;

            return(new RpcNep17TokenInfo
            {
                Name = name,
                Symbol = stack[0].GetString(),
                Decimals = (byte)stack[1].GetInteger(),
                TotalSupply = stack[2].GetInteger()
            });
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Create NEP17 token transfer transaction
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <param name="fromKey">from KeyPair</param>
        /// <param name="to">to account script hash</param>
        /// <param name="amount">transfer amount</param>
        /// <param name="data">onPayment data</param>
        /// <returns></returns>
        public async Task <Transaction> CreateTransferTxAsync(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount, object data = null)
        {
            var sender = Contract.CreateSignatureRedeemScript(fromKey.PublicKey).ToScriptHash();

            Signer[] signers = new[] { new Signer {
                                           Scopes = WitnessScope.CalledByEntry, Account = sender
                                       } };
            byte[] script = scriptHash.MakeScript("transfer", true, sender, to, amount, data);

            TransactionManagerFactory factory = new TransactionManagerFactory(rpcClient, magic);
            TransactionManager        manager = await factory.MakeTransactionAsync(script, signers).ConfigureAwait(false);

            return(await manager
                   .AddSignature(fromKey)
                   .SignAsync().ConfigureAwait(false));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Create NEP5 token transfer transaction
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <param name="fromKey">from KeyPair</param>
        /// <param name="to">to account script hash</param>
        /// <param name="amount">transfer amount</param>
        /// <returns></returns>
        public Transaction CreateTransferTx(UInt160 scriptHash, KeyPair fromKey, UInt160 to, BigInteger amount)
        {
            var sender = Contract.CreateSignatureRedeemScript(fromKey.PublicKey).ToScriptHash();

            Signer[] signers = new[] { new Signer {
                                           Scopes = WitnessScope.CalledByEntry, Account = sender
                                       } };

            byte[]      script = scriptHash.MakeScript("transfer", sender, to, amount);
            Transaction tx     = new TransactionManager(rpcClient)
                                 .MakeTransaction(script, signers)
                                 .AddSignature(fromKey)
                                 .Sign()
                                 .Tx;

            return(tx);
        }
Ejemplo n.º 8
0
        public static async Task BroadcastTransaction(string senderPrivateKey, string operation, params object[] param)
        {
            try
            {
                // Create a new RPC client that is connected to a private test network
                RpcClient client = new RpcClient("http://localhost:10332");

                // Initialize the script that will be executed by the neo VM
                UInt160 contractHash = UInt160.Parse(SmartContractHash);
                byte[]  script       = contractHash.MakeScript(operation, param);

                // Generate a keypair from the sender's private key
                KeyPair  senderKeyPair = Neo.Network.RPC.Utility.GetKeyPair(senderPrivateKey);
                UInt160  sender        = Contract.CreateSignatureContract(senderKeyPair.PublicKey).ScriptHash;
                Signer[] signers       = new[]
                {
                    new Signer()
                    {
                        Scopes  = WitnessScope.CalledByEntry,
                        Account = sender
                    }
                };

                // Create and broadcast the transaction
                Transaction transaction = new TransactionManager(client)
                                          .MakeTransaction(script, signers, null)
                                          .AddSignature(senderKeyPair)
                                          .Sign()
                                          .Tx;
                client.SendRawTransaction(transaction);

                // Wait until transaction is confirmed on the chain
                WalletAPI wallet = new WalletAPI(client);
                await wallet.WaitTransaction(transaction).ContinueWith(async(p) =>
                {
                    Console.WriteLine($"Transaction vm state is  {(await p).VMState}");
                });
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Create NEP17 token transfer transaction from multi-sig account
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <param name="m">multi-sig min signature count</param>
        /// <param name="pubKeys">multi-sig pubKeys</param>
        /// <param name="fromKeys">sign keys</param>
        /// <param name="to">to account</param>
        /// <param name="amount">transfer amount</param>
        /// <param name="data">onPayment data</param>
        /// <returns></returns>
        public async Task <Transaction> CreateTransferTxAsync(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] fromKeys, UInt160 to, BigInteger amount, object data = null)
        {
            if (m > fromKeys.Length)
            {
                throw new ArgumentException($"Need at least {m} KeyPairs for signing!");
            }
            var sender = Contract.CreateMultiSigContract(m, pubKeys).ScriptHash;

            Signer[] signers = new[] { new Signer {
                                           Scopes = WitnessScope.CalledByEntry, Account = sender
                                       } };
            byte[] script = scriptHash.MakeScript("transfer", true, sender, to, amount, data);

            TransactionManagerFactory factory = new TransactionManagerFactory(rpcClient, magic);
            TransactionManager        manager = await factory.MakeTransactionAsync(script, signers).ConfigureAwait(false);

            return(await manager
                   .AddMultiSig(fromKeys, m, pubKeys)
                   .SignAsync().ConfigureAwait(false));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Create NEP5 token transfer transaction from multi-sig account
        /// </summary>
        /// <param name="scriptHash">contract script hash</param>
        /// <param name="m">multi-sig min signature count</param>
        /// <param name="pubKeys">multi-sig pubKeys</param>
        /// <param name="fromKeys">sign keys</param>
        /// <param name="to">to account</param>
        /// <param name="amount">transfer amount</param>
        /// <returns></returns>
        public Transaction CreateTransferTx(UInt160 scriptHash, int m, ECPoint[] pubKeys, KeyPair[] fromKeys, UInt160 to, BigInteger amount)
        {
            if (m > fromKeys.Length)
            {
                throw new ArgumentException($"Need at least {m} KeyPairs for signing!");
            }
            var sender = Contract.CreateMultiSigContract(m, pubKeys).ScriptHash;

            Signer[] signers = new[] { new Signer {
                                           Scopes = WitnessScope.CalledByEntry, Account = sender
                                       } };

            byte[]      script = scriptHash.MakeScript("transfer", sender, to, amount);
            Transaction tx     = new TransactionManager(rpcClient)
                                 .MakeTransaction(script, signers)
                                 .AddMultiSig(fromKeys, m, pubKeys)
                                 .Sign()
                                 .Tx;

            return(tx);
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Use RPC method to test invoke operation.
 /// </summary>
 /// <param name="scriptHash">contract script hash</param>
 /// <param name="operation">contract operation</param>
 /// <param name="args">operation arguments</param>
 /// <returns></returns>
 public Task <RpcInvokeResult> TestInvokeAsync(UInt160 scriptHash, string operation, params object[] args)
 {
     byte[] script = scriptHash.MakeScript(operation, true, args);
     return(rpcClient.InvokeScriptAsync(script));
 }
Ejemplo n.º 12
0
 /// <summary>
 /// Use RPC method to test invoke operation.
 /// </summary>
 /// <param name="scriptHash">contract script hash</param>
 /// <param name="operation">contract operation</param>
 /// <param name="args">operation arguments</param>
 /// <returns></returns>
 public RpcInvokeResult TestInvoke(UInt160 scriptHash, string operation, params object[] args)
 {
     byte[] script = scriptHash.MakeScript(operation, args);
     return(rpcClient.InvokeScript(script));
 }