Blockchain-Smart Contract Simple scripting Method (solidity) __ Blockchain

Source: Internet
Author: User
Tags assert

"A smart contract is a set of commitments (promises), defined in digital form, that includes the agreement that the contract participants can execute on the above commitments." "The protocol is a technology implementation (technical implementation), on which a contractual commitment is fulfilled, or a contractual commitment is recorded." The choice of which protocol depends on many factors, the most important factor is the nature of the assets being traded during the performance of the contract. Again, take the sales contract as an example. It is assumed that the participant agrees to pay the purchase price in Bitcoin. The chosen protocol will obviously be the Bitcoin protocol, in which the smart contract is implemented. Therefore, the "digital form" that the contract must use is the Bitcoin scripting language. The Bitcoin scripting language is a non-Turing complete, imperative, stack-based programming language, similar to forth. A simple contract script and a corresponding contract function test script are explained below.

Here is a simple contract script:

Import "Convertlib.sol";

This was just a simple example of a coin-like contract.
IT is not standards compatible and cannot are expected to the other
/coin/token contracts. If you want to create a standards-compliant
//token, See:https://github.com/consensys/tokens. Cheers!

Contract Metacoin {
	mapping (address ~ = uint) balances;

	function Metacoin () {
		Balances[tx.origin] = 10000;
	}

	function Sendcoin (address receiver, uint amount) returns (bool sufficient) {
		if (Balances[msg.sender] < amount) RE Turn false;
		Balances[msg.sender]-= amount;
		Balances[receiver] + = amount;
		return true;
	}
	function Getbalanceineth (address addr) returns (UINT) {
		return Convertlib.convert (getbalance (addr), 2);
	}
  	function getbalance (address addr) returns (UINT) {
    	return balances[addr];
  	}
}
The script contract sets the initial value of the account and some rules for making the transfer, and basically all of the contract scripts follow such a form of code, following a brief description of some keywords:

Address: This address is assigned a value in the contract's constructor Functionconference (). This address is often called ' owner ' (everyone).

UINT.: unsigned integer, the storage space on the blockchain is tight, keeping the data as small as possible.

Public: This keyword indicates that a variable can be used by an object other than the contract. The private modifier indicates that the variable can only be used by objects within this contract (or derivative contracts).

Mapping or array: Before solidity joins the array type, everyone uses a mapping type similar to mapping (address = = uint). This statement can also be written in address registrantspaid[], but mapping's storage footprint is smaller (smaller footprint). This mapping variable will be used to save the number of payments to the participants (as indicated by their wallet address) for refund purposes.

After writing the contract script, we need to deploy it on our blockchain network (truffle open source framework has done better, interested to see the relevant information), after the deployment is complete, we can write some simple test Case to verify that our contract script can be called correctly by the peer node in the blockchain, such as:

Contract (' Metacoin ', function (accounts) {It ("should put 10000 metacoin in the first account", function (done) {//it
    Should is executed every time to any testcase var meta = metacoin.deployed (); /* Those then and return in the code are promise. Their role is written in a deep nested call chain that would be like this conference.numRegistrants.call (). Then (function (num) {assert.equal (num, 0, "registrants
    should be zero! "); Conference.organizer.call (). Then (function (organizer) {assert.equal (organizer, Accounts[0], "Owner doesn ' t m Atch! ");}).
            Then (function (...))
            }). Then (function (...)) Because this would get hairy ... */Meta.getBalance.call (accounts[0]). Then (function (balance) {assert.equal (b
	  
	  Alance.valueof (), 10000, "10000 wasn ' t in the first account");
  Stops tests at the ()). then (DO). catch (done);
  
  }); It ("should call a function so depends on a linked library", function (done) {var meta = metacoin.deployed ();
    var metacoinbalance;

    var metacoinethbalance;
      Meta.getBalance.call (Accounts[0]). Then (function (outcoinbalance) {metacoinbalance = Outcoinbalance.tonumber ();
    Return Meta.getBalanceInEth.call (Accounts[0]);
      
    }). Then (function (outcoinbalanceeth) {metacoinethbalance = Outcoinbalanceeth.tonumber (); }). Then (function () {assert.equal (metacoinethbalance,2*metacoinbalance, "Library function returned unexpeced function
      
    , linkage may broken ");
  }). Then (did). catch (done);
  
  });

    It ("should send coin correctly", function (done) {var meta = metacoin.deployed ();
    Get initial balances of first and second account.
    var account_one = accounts[0];

    var account_two = accounts[1];
    var account_one_starting_balance;
    var account_two_starting_balance;
    var account_one_ending_balance;

    var account_two_ending_balance;

    var amount = 10; Meta.getBalance.call (Account_one). Then (function (balance) {AccounT_one_starting_balance = Balance.tonumber ();
    Return Meta.getBalance.call (Account_two);
      }). Then (function (balance) {account_two_starting_balance = Balance.tonumber ();
    Return Meta.sendcoin (Account_two, amount, {from:account_one});
    }). Then (function () {return meta.getBalance.call (Account_one);
      }). Then (function (balance) {account_one_ending_balance = Balance.tonumber ();
    Return Meta.getBalance.call (Account_two);

      }). Then (function (balance) {account_two_ending_balance = Balance.tonumber (); Assert.equal (Account_one_ending_balance, Account_one_starting_balance-amount, "amount wasn ' t correctly taken from the
      Sender "); Assert.equal (account_two_ending_balance, account_two_starting_balance + amount, "Amount wasn ' t correctly sent to the
    Receiver ");
  }). Then (did). catch (done);
  
});
 });
The key fields have already given some simple explanations, with the emphasis on the use of the then statement, and the then statement, which is the pre-defined contract method in our contract, that is, how to deal with an event when it comes.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.