Ejemplo n.º 1
0
        public async Task <IActionResult> PutStdFee([FromRoute] int id, [FromBody] StdFee stdFee)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != stdFee.AutoId)
            {
                return(BadRequest());
            }

            _context.Entry(stdFee).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StdFeeExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
        // 'Function "calculateDefaultFee" returns expected values;'
        public void CorrectCalculateFee()
        {
            const int    defaultAmount = 100;
            const String defaultDenom  = "commercio";
            const int    defaultGas    = 200;
            int          msgsNumber    = 2;

            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            StdFee expectedFee = new StdFee(
                amount: new List <StdCoin>
            {
                new StdCoin(
                    denom: defaultDenom,
                    amount: (defaultAmount * msgsNumber).ToString()
                    )
            },
                gas: (defaultGas * msgsNumber).ToString()
                );

            StdFee fee = GenericUtils.calculateDefaultFee(
                msgsNumber: msgsNumber,
                fee: defaultAmount,
                denom: defaultDenom,
                gas: defaultGas
                );

            Assert.AreEqual(compareLogic.Compare(fee.toJson(), expectedFee.toJson()).AreEqual, true);
        }
        /// Creates a new transaction which tells the [recipient] that the document
        /// having the specified [documentId] and present inside the transaction with
        /// hash [txHash] has been properly seen.
        /// [proof] optional proof of reading.
        public static async Task <TransactionResult> sendDocumentReceipt(
            String recipient,
            String txHash,
            String documentId,
            Wallet wallet,
            String proof          = "",
            StdFee fee            = null,
            BroadcastingMode mode = BroadcastingMode.SYNC
            )
        {
            CommercioDocReceipt commercioDocReceipt = CommercioDocReceiptHelper.fromWallet(
                wallet: wallet,
                recipient: recipient,
                txHash: txHash,
                documentId: documentId,
                proof: proof
                );

            MsgSendDocumentReceipt msg = new MsgSendDocumentReceipt(receipt: commercioDocReceipt);

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(await TxHelper.createSignAndSendTx(new List <StdMsg> {
                msg
            }, wallet, fee : fee, mode : mode));
        }
Ejemplo n.º 4
0
        public void TestTxSigner()
        {
            List <String> mnemonic = new List <String>(singleVector.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            // Create the network info
            NetworkInfo networkInfo = new NetworkInfo(bech32Hrp: localbech32Hrp, lcdUrl: localTestUrl);

            // Build a transaction
            MsgSend msg = new MsgSend(
                fromAddress: "cosmos1hafptm4zxy5nw8rd2pxyg83c5ls2v62tstzuv2",
                toAddress: "cosmos12lla7fg3hjd2zj6uvf4pqj7atx273klc487c5k",
                amount: new List <StdCoin> {
                new StdCoin(denom: "uatom", amount: "100")
            }
                );
            // Fee
            StdFee fee = new StdFee(
                gas: "200000",
                amount: new List <StdCoin> {
                new StdCoin(denom: "uatom", amount: "250")
            }
                );
            StdTx tx = TxBuilder.buildStdTx(stdMsgs: new List <StdMsg> {
                msg
            }, fee: fee);
            // Create a wallet
            Wallet wallet = Wallet.derive(mnemonic, networkInfo);

            // Verify Wallet
            Assert.AreEqual(wallet.networkInfo.bech32Hrp, networkInfo.bech32Hrp);
            Assert.AreEqual(wallet.networkInfo.lcdUrl, networkInfo.lcdUrl);

            // Build the mockup server
            var _server = new MockHttpServer();
            //  I need this in order to get the correct data out of the mock server
            Dictionary <String, Object> accResponse  = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.AccountDataResponse);
            Dictionary <String, Object> NodeResponse = JsonConvert.DeserializeObject <Dictionary <String, Object> >(TestResources.NodeInfoResponse);

            // Initialize Server Response
            _server
            .WithService(localTestUrl)
            .Api("auth/accounts/{wallettAddress}", accResponse)
            .Api("node_info", NodeResponse);

            // Link the client to the retrieval classes
            HttpClient client = new HttpClient(_server);

            AccountDataRetrieval.client = client;
            NodeInfoRetrieval.client    = client;

            // Call without await to avoid marking test class as async
            StdTx signedTx = TxSigner.signStdTx(wallet: wallet, stdTx: tx).Result;

            Assert.AreEqual(signedTx.signatures.Count, 1);

            StdSignature signature = (signedTx.signatures.ToArray())[0];

            Assert.AreEqual(signature.publicKey.type, "tendermint/PubKeySecp256k1");
            Assert.AreEqual(signature.publicKey.value, "ArMO2T5FNKkeF2aAZY012p/cpa9+PqKqw2GcQRPhAn3w");
            Assert.AreEqual(signature.value, "m2op4CCBa39fRZD91WiqtBLKbUQI+1OWsc1tJkpDg+8FYB4y51KahGn26MskVMpTJl5gToIC1pX26hLbW1Kxrg==");
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> PostStdFee([FromBody] StdFee stdFee)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.StdFee.Add(stdFee);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetStdFee", new { id = stdFee.AutoId }, stdFee));
        }
Ejemplo n.º 6
0
        /// Sends a new transaction from the sender [wallet]
        /// to request a list of Did PowerUp [requestDidPowerUpsList].
        /// Optionally [fee] and broadcasting [mode] parameters can be specified.
        public static async Task <TransactionResult> requestDidPowerUpList(
            List <RequestDidPowerUp> requestDidPowerUpsList,
            Wallet wallet,
            StdFee fee            = null,
            BroadcastingMode mode = BroadcastingMode.SYNC
            )
        {
            List <MsgRequestDidPowerUp> msgs = requestDidPowerUpsList
                                               .Select(x => new MsgRequestDidPowerUp(x))
                                               .ToList();

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(await TxHelper.createSignAndSendTx(msgs.ToList <StdMsg>(), wallet, fee : fee, mode : mode));
        }
Ejemplo n.º 7
0
        public async Task AsyncCreateTransactionTransferCoins()
        {
            using var client = CreateClient(Configuration.LocalBaseUrl);

            var account1BeforeTransaction = ((await client.Auth.GetAuthAccountByAddressAsync(Configuration.LocalAccount1Address)).Result as BaseAccount) !;

            Assert.NotNull(account1BeforeTransaction);
            var account2BeforeTransaction = ((await client.Auth.GetAuthAccountByAddressAsync(Configuration.LocalAccount2Address)).Result as BaseAccount) !;

            Assert.NotNull(account2BeforeTransaction);

            var denom       = account1BeforeTransaction.Coins[0].Denom;
            var amount      = 10;
            var coinsToSend = new List <Coin>()
            {
                new Coin(denom, amount)
            };
            var memo = Guid.NewGuid().ToString("D");
            var fee  = new StdFee()
            {
                Amount = new List <Coin>(),
                Gas    = 300000,
            };
            var result = await((ICosmosApiClient)client).SendAsync(Configuration.LocalAccount1Address, Configuration.LocalAccount2Address, coinsToSend, BroadcastTxMode.Block, fee, Configuration.LocalAccount1PrivateKey, Configuration.LocalAccount1Passphrase, memo);

            OutputHelper.WriteLine("Deserialized broadcast result");
            Dump(result);
            OutputHelper.WriteLine("");
            Assert.NotNull(result.TxHash);
            Assert.True(result.TxHash.Length > 0);
            Assert.True(result.Logs.All(l => l.Success));
            var account1AfterTransaction =
                ((await client.Auth.GetAuthAccountByAddressAsync(Configuration.LocalAccount1Address)).Result as BaseAccount) !;
            var account1CoinsBefore = GetAmount(account1BeforeTransaction, denom);
            var account1CoinsAfter  = GetAmount(account1AfterTransaction, denom);

            Assert.Equal(account1CoinsBefore - amount, account1CoinsAfter);
            var account2AfterTransaction =
                ((await client.Auth.GetAuthAccountByAddressAsync(Configuration.LocalAccount2Address)).Result as BaseAccount) !;
            var account2CoinsBefore = GetAmount(account2BeforeTransaction, denom);
            var account2CoinsAfter  = GetAmount(account2AfterTransaction, denom);

            Assert.Equal(account2CoinsBefore + amount, account2CoinsAfter);
        }
Ejemplo n.º 8
0
        public void TestJson()
        {
            StdFee         origFee;
            StdCoin        coin1, coin2;
            List <StdCoin> coinList, recoveredList;
            Dictionary <String, Object> origJson;


            coin1    = new StdCoin(denom: "PizzaDiFango", amount: "100");
            coin2    = new StdCoin(denom: "LifeUniverse", amount: "42");
            coinList = new List <StdCoin>();
            coinList.Add(coin1);
            coinList.Add(coin2);

            origFee = new StdFee(amount: coinList, gas: "0.1");

            origJson = origFee.toJson();

            recoveredList = origFee.amount;

            // Verify if the object is correct
            Assert.AreEqual(coinList, recoveredList);
        }
Ejemplo n.º 9
0
        /// Creates a new Did power up request for the given [pairwiseDid] and of the given [amount].
        /// Signs everything that needs to be signed (i.e. the signature JSON inside the payload) with the
        /// private key contained inside the given  [senderWallet] and the [privateKey].
        public static async Task <TransactionResult> requestDidPowerUp(
            Wallet senderWallet,
            String pairwiseDid,
            List <StdCoin> amount,
            RSAPrivateKey privateKey,
            StdFee fee            = null,
            BroadcastingMode mode = BroadcastingMode.SYNC
            )
        {
            RequestDidPowerUp requestDidPowerUp = await RequestDidPowerUpHelper.fromWallet(
                senderWallet,
                pairwiseDid,
                amount,
                privateKey
                );

            MsgRequestDidPowerUp msg = new MsgRequestDidPowerUp(requestDidPowerUp: requestDidPowerUp);

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(await TxHelper.createSignAndSendTx(new List <StdMsg> {
                msg
            }, senderWallet, fee : fee, mode : mode));
        }
Ejemplo n.º 10
0
        public void TestJson()
        {
            StdTx                       origTx;
            StdSignature                origSignature;
            StdMsg                      origMsg;
            List <StdSignature>         tSignatures;
            List <StdMsg>               tMessages;
            StdMsg_test                 t;
            StdFee                      tFee;
            Dictionary <String, Object> origJson;
            String                      outString;

            origSignature = new StdSignature(publicKey: new StdPublicKey("PublicKeyType", "PublicKeyValue"), value: "PublicKeySample");
            tSignatures   = new List <StdSignature> {
                origSignature, origSignature
            };

            t         = new StdMsg_test();
            origMsg   = t.createMsg();
            tMessages = new List <StdMsg> {
                origMsg, origMsg
            };

            tFee = new StdFee(amount: new List <StdCoin> {
                new StdCoin(denom: "Coin1Denom", amount: "Coin1Amount"), new StdCoin(denom: "Coin2Denom", amount: "Coin2Amount")
            }, gas: "GasValue");

            origTx   = new StdTx(messages: tMessages, signatures: tSignatures, fee: tFee, memo: "StdMemoValue");
            origJson = origTx.toJson();

            // Here just for debugging
            outString = origTx.ToString();

            // USeless - the test just create the object...
            Assert.AreEqual(origTx, origTx);
        }
Ejemplo n.º 11
0
        // This doesn't seem to be used, although it is there in Dart code... I will keep it as a placeholder
        // Use static HttpClient to avoid exhausting system resources for network connections.
        // private static HttpClient client = new HttpClient();

        #endregion

        #region Properties
        #endregion

        #region Constructors
        #endregion

        #region Public Methods

        /// Creates a new transaction that allows to share the document associated
        /// with the given [contentUri] and having the given [metadata]
        /// and [checksum]. If [encryptedData] is specified, encrypts the proper
        /// data for the specified [recipients] and then sends the transaction
        /// to the blockchain.
        public static async Task <TransactionResult> shareDocument(
            String id,
            CommercioDocMetadata metadata,
            List <String> recipients,
            Wallet wallet,
            CommercioDoSign doSign             = null,
            CommercioDocChecksum checksum      = null,
            KeyParameter aesKey                = null,
            List <EncryptedData> encryptedData = null,
            StdFee fee            = null,
            String contentUri     = null,
            BroadcastingMode mode = BroadcastingMode.SYNC
            )
        {
            // Build a generic document
            CommercioDoc commercioDoc = await CommercioDocHelper.fromWallet(
                wallet : wallet,
                recipients : recipients,
                id : id,
                metadata : metadata,
                checksum : checksum,
                contentUri : contentUri,
                doSign : doSign,
                encryptedData : encryptedData,
                aesKey : aesKey
                );


            // Build the tx message
            MsgShareDocument msg = new MsgShareDocument(document: commercioDoc);

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(await TxHelper.createSignAndSendTx(new List <StdMsg> {
                msg
            }, wallet, fee : fee, mode : mode));
        }
Ejemplo n.º 12
0
        /// Performs a transaction setting the [didDocuments] list as being
        /// associated with the address present inside the specified [wallet].
        /// Optionally [fee] and broadcasting [mode] parameters can be specified.
        public static Task <TransactionResult> setDidDocumentsList(List <DidDocument> didDocuments, Wallet wallet, StdFee fee = null, BroadcastingMode mode = BroadcastingMode.SYNC)
        {
            List <MsgSetDidDocument> msgs = didDocuments
                                            .Select(x => new MsgSetDidDocument(x))
                                            .ToList();

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            // And I need to declare the thing explicitly in C#!
            return(TxHelper.createSignAndSendTx(msgs.ToList <StdMsg>(), wallet, fee: fee, mode: mode));
        }
Ejemplo n.º 13
0
        /// Performs a transaction setting the specified [didDocument] as being
        /// associated with the address present inside the specified [wallet].
        public static Task <TransactionResult> setDidDocument(DidDocument didDocument, Wallet wallet, StdFee fee = null, BroadcastingMode mode = BroadcastingMode.SYNC)
        {
            MsgSetDidDocument msg = new MsgSetDidDocument(didDocument: didDocument);

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(TxHelper.createSignAndSendTx(new List <StdMsg> {
                msg
            }, wallet, fee: fee, mode: mode));
        }
Ejemplo n.º 14
0
        /// Creates a transaction having the given [msgs] and [fee] inside,
        /// signs it with the given [Wallet] and sends it to the blockchain.
        /// Optional parameters can be [fee] and broadcasting [mode],
        /// that can be of type "sync", "async" or "block".
        public static async Task <TransactionResult> createSignAndSendTx(List <StdMsg> msgs, Wallet wallet, StdFee fee = null, BroadcastingMode mode = BroadcastingMode.SYNC)
        {
            if (fee == null)
            {
                // Set the default value for fee
                int msgsNumber = msgs.Count > 0 ? msgs.Count : 1;
                fee = GenericUtils.calculateDefaultFee(msgsNumber: msgsNumber, fee: defaultAmount, denom: defaultDenom, gas: defaultGas);
            }

            String modeStr  = MyEnumExtensions.ToEnumMemberAttrValue(mode);
            StdTx  stdTx    = TxBuilder.buildStdTx(stdMsgs: msgs, fee: fee);
            StdTx  signedTx = await TxSigner.signStdTx(wallet : wallet, stdTx : stdTx);

            // return await TxSender.broadcastStdTx(wallet: wallet, stdTx: signedTx, mode: modeStr);
            TransactionResult res = await TxSender.broadcastStdTx(wallet : wallet, stdTx : signedTx, mode : modeStr);

            return(res);
        }
Ejemplo n.º 15
0
        /// Closes the CDP having the given [timestamp].
        /// Optionally [fee] and broadcasting [mode] parameters can be specified.
        public static async Task <TransactionResult> closeCdp(int timestamp, Wallet wallet, StdFee fee = null, BroadcastingMode mode = BroadcastingMode.SYNC)
        {
            CloseCdp closeCdp = CloseCdpHelper.fromWallet(wallet, timestamp);

            MsgCloseCdp msg = new MsgCloseCdp(closeCdp: closeCdp);

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(await TxHelper.createSignAndSendTx(new List <StdMsg> {
                msg
            }, wallet, fee : fee, mode : mode));
        }
Ejemplo n.º 16
0
        /// Performs a transaction opening a new CDP [openCdp] as being
        /// associated with the address present inside the specified [wallet].
        /// Optionally [fee] and broadcasting [mode] parameters can be specified.
        public static async Task <TransactionResult> openCdpSingle(OpenCdp openCdp, Wallet wallet, StdFee fee = null, BroadcastingMode mode = BroadcastingMode.SYNC)
        {
            MsgOpenCdp msg = new MsgOpenCdp(openCdp: openCdp);

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(await TxHelper.createSignAndSendTx(new List <StdMsg> {
                msg
            }, wallet, fee : fee, mode : mode));
        }
Ejemplo n.º 17
0
        /// Opens a new CDP depositing the given Commercio Token [amount].
        /// Optionally [fee] and broadcasting [mode] parameters can be specified.
        public static async Task <TransactionResult> openCdp(int amount, Wallet wallet, StdFee fee = null, BroadcastingMode mode = BroadcastingMode.SYNC)
        {
            List <StdCoin> depositAmount = new List <StdCoin> {
                new StdCoin("ucommercio", amount.ToString())
            };

            OpenCdp openCdp = OpenCdpHelper.fromWallet(wallet, depositAmount);

            MsgOpenCdp msg = new MsgOpenCdp(openCdp: openCdp);

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(await TxHelper.createSignAndSendTx(new List <StdMsg> {
                msg
            }, wallet, fee : fee, mode : mode));
        }
Ejemplo n.º 18
0
        /// Sends a new transaction in order to invite the given [userDid].
        public static async Task <TransactionResult> inviteUser(String userDid, Wallet wallet, StdFee fee = null, BroadcastingMode mode = BroadcastingMode.SYNC)
        {
            InviteUser inviteUser = InviteUserHelper.fromWallet(wallet, userDid);

            MsgInviteUser msg = new MsgInviteUser(inviteUser: inviteUser);

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(await TxHelper.createSignAndSendTx(new List <StdMsg> {
                msg
            }, wallet, fee : fee, mode : mode));
        }
Ejemplo n.º 19
0
        /// Buys the membership with the given [membershipType].
        public static async Task <TransactionResult> buyMembership(MembershipType membershipType, Wallet wallet, StdFee fee = null, BroadcastingMode mode = BroadcastingMode.SYNC)
        {
            BuyMembership buyMembership = BuyMembershipHelper.fromWallet(wallet, membershipType);

            MsgBuyMembership msg = new MsgBuyMembership(buyMembership: buyMembership);

            // Careful here, Eugene: we are passing a list of BaseType containing the derived MsgSetDidDocument msg
            return(await TxHelper.createSignAndSendTx(new List <StdMsg> {
                msg
            }, wallet, fee : fee, mode : mode));
        }
        public async Task test_broadcastStdTx()
        {
            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            NetworkInfo networkInfo = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: "http://localhost:1317");

            //primo mnemonic
            String        mnemonicString1 = "gorilla soldier device force cupboard transfer lake series cement another bachelor fatigue royal lens juice game sentence right invite trade perfect town heavy what";
            List <String> mnemonic        = new List <String>(mnemonicString1.Split(" ", StringSplitOptions.RemoveEmptyEntries));

            //secondo mnemonic
            String        mnemonicString2 = "daughter conduct slab puppy horn wrap bone road custom acoustic adjust target price trip unknown agent infant proof whip picnic exact hobby phone spin";
            List <String> mnemonic2       = new List <String>(mnemonicString2.Split(" ", StringSplitOptions.RemoveEmptyEntries));


            Wallet wallet          = Wallet.derive(mnemonic, networkInfo);
            Wallet recipientWallet = Wallet.derive(mnemonic2, networkInfo);


            List <StdCoin> depositAmount = new List <StdCoin> {
                new StdCoin(denom: "ucommercio", amount: "10000")
            };

            var dict = new Dictionary <string, object>();

            dict.Add("from_address", wallet.bech32Address);
            dict.Add("to_address", recipientWallet.bech32Address);
            dict.Add("amount", depositAmount);


            StdMsg        testmsg     = new StdMsg("cosmos-sdk/MsgSend", dict);
            List <StdMsg> Listtestmsg = new List <StdMsg>();

            Listtestmsg.Add(testmsg);

            StdFee fee = new StdFee(depositAmount, "200000");

            //Invio
            try
            {
                var stdTx = TxBuilder.buildStdTx(Listtestmsg, "", fee);

                var signedStdTx = await TxSigner.signStdTx(wallet : wallet, stdTx : stdTx);

                var result = await TxSender.broadcastStdTx(wallet : wallet, stdTx : signedStdTx);

                if (result.success)
                {
                    Console.WriteLine("Tx send successfully:\n$lcdUrl/txs/${result.hash}");
                }
                else
                {
                    Console.WriteLine("Tx error message:\n${result.error?.errorMessage}");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while testing Sacco:\n$error");
            }
        }