Saturday, November 10, 2018

Building a Contract in Solidity and Uploading it to a Test Blockchain

In this lesson, we will write a contract and execute it on a test blockchain. The Ownable contract uses solidity 0.4.8, which is not the current version of solidity. For this reason we will debug the contract, replacing deprecated terms and syntax.

If you have not, you will need to download Visual Studio Code and install Juan Blanco’s Solidity compiler. You will need to download and install Node.js. This will allow you to download and install truffle with the command:

npm install truffle

You will also need to download and install Ganache, which will automatically set up the test blockchain.

To start, open PowerShell to start a new project with Truffle. Navigate to your desired directory and create a new folder with the mkdir command.  Since we will build the Ownable contract in this folder, name the folder ownable:

mkdir ownable
cd ownable

Once you have navigated to the new folder, create a new project using truffle:

truffle init

The console should return the following text:

Compile:        truffle compile
Migrate:        truffle migrate
Test contracts: truffle test

Now that you have initialized a project with truffle, it is time to create a contract. We are going to copy a contract from Chapter 7, page 148, of Blockchain: A PracticalGuide to Developing Business, Law, and Technology Solutions.

Write the following code in a Visual Studio file and save it as Ownable.sol under the contracts folder, created during the truffle initialization of the ownable folder.

pragma solidity ^0.4.8;
// module handling and transfer of contract ownership
contract Ownable {
    address public owner;
    function Ownable() {
        owner = msg.sender;
    }
    modifier onlyOwner {
        if(msg.sender != owner) revert();
        _;
    }
    function transferOwnership(address _newOwner) external onlyOwner {
        owner = _newOwner;
        TransferOwnership(msg.sender, _newOwner);
    }
    event TransferOwnership(address indexed _from, address indexed _to);
}

Now compile your code. You may use the short-cut F5 for this. Make sure that you have opened the file explorer. If not, you can use the command CTRL + SHIFT + E. Upon compiling the code, you should see a list of errors, under the PROBLEMS tab. We will solve these one at a time.




Debugging

The first error is not significant to the execution of the program. To make it disappear, we can enter a command above the first line:
//solium-disable linebreak-style
pragma solidity ^0.4.8;
// module handling and transfer of contract ownership
...

The next two errors appear on line 6:



The first error indicates we should have specified and access keyword like: public, private, internal or external. The second error notes that constructor() should be used to define a constructor for the class instead of function Ownable(). Edit the script to reflect this:
contract Ownable {
    address public owner;
    constructor() public {
        owner = msg.sender;
...

We change function Ownable() to constructor(). We also add the term public after the constructor. This allows the constructor to be called from both inside and outside of the contract.
A comprehensive list of visibility keywords for functions and state variables:
·        public - all can access the referenced object
·        external – The object cannot be accessed from outside of the contract
·        internal - only this contract and contracts deriving from it can access the object
·        private – the object can only be accessed only from this contract

After making the edits for the constructor, the errors for line 6 have disappeared.




Next is an error concerning the calling of revert().  The error suggests that a string should be passed into the revert function. We could pass one like this:

    modifier onlyOwner {
        if (msg.sender != owner) revert(“Error: non-owner access denied”);
        _;
...

The error disappears, but when we upload the contract to the blockchain, this will require more gas than if we do not pass a string to revert(). For now, we can leave this blank. The error will not affect anything.

To solve the next error, we need to call the event on line 15 using the term emit. This is required by more recent versions of solidity:

    function transferOwnership(address _newOwner) external onlyOwner {
        owner = _newOwner;
        emit TransferOwnership(msg.sender, _newOwner);
    }
...

If you have followed the instructions to this point, there should remain only the error concerning require() from line 6. The contract is ready to be executed. Before we do this, we will need to create a migration file for the Ownable contract and modify the Truffle.js file to point to a private blockchain.
Compile and Migrate
In order to upload the contract, we need to first convert the contract to a form that is readable in javascript. Then, this will be converted to byte code which is uploaded to the blockchain.
Using Visual Studio let’s create a javascript file called  2_ownable_migration.js , and save it under the ownable/migrations folder.
var Ownable  = artifacts.require('./Ownable.sol');
module.exports = function(deployer) {
    deployer.deploy(Ownable);
};

When the files are compiled using truffle, this script will be used to upload to the blockchain the json file representing the compiled contract.
Next, edit the truffle.js file, located in the ownable folder. This file identifies the network that will be used to locate the test blockchain to which we will upload the contract. Replace this code:
module.exports = {
  // See <http://truffleframework.com/docs/advanced/configuration>
  // to customize your Truffle configuration!
};

With the following:

module.exports = {
  networks: {
      development: {
          host: 'localhost',
          port: 7545,
          network_id: '*'
      }
  }
};

This points to the test blockchain on your local machine, that is created when you launch Ganache.
Now that everything is ready, make sure that you have navigated in the PowerShell to the ownable folder. Compile the contract using the commands:
truffle compile

If you were successful, you should see the following text:

Compiling .\contracts\Migrations.sol...
Compiling .\contracts\Ownable.sol...
Writing artifacts to .\build\contracts

Next, migrate the contracts to the blockchain. First, we will need to open Ganache so that there is a blockchain with which we can interact through truffle. When you launch Ganache, you will see the accounts created for the test blockchain:



Only the genesis block has been created. We will now upload the contract to the test blockchain by using the command:

truffle migrate

This will yield the following in the PowerShell

Using network 'development'.

Running migration: 1_initial_migration.js
  Deploying Migrations...
  ... 0x2bcc6f737e1244ee9be0db52bf59dd0e954b4c3c9ae2028b3f4479bd13d57cd6
  Migrations: 0xe9ab13bb64959432cf38416759cc2e4c0db7d6be
Saving successful migration to network...
  ... 0x661b37c2202a45457151ec65f23f15080f23238724c8d665db12df4bb67a6afc
Saving artifacts...
Running migration: 2_ownable_migration.js
  Deploying Ownable...
  ... 0x6603eaf64060e817a202810c5b6f717f3492a2f5d07fcef221b2af45057f5773
  Ownable: 0xcea93908c932064d61cd2dd1f72c974b190cc3ce
Saving successful migration to network...
  ... 0x6bfd670baad0f28816e6d0df7f2b9cd40e64b32fa70d2e3da73c241edcb09f47
Saving artifacts...

This reflects that blocks have been added to the genesis block. We also observe this in Ganache:



Create an Instance of the Contract
Now we can call the truffle console. Since we have already edited the truffle.js file, truffle will automatically connect to the network housing the test blockchain.

truffle console

If you have successfully connected the network provided by Ganache, you should see the following:

truffle(development)>

To create an instance of the contract, we must first create a variable using javascript commands. Enter the following lines one by one into the truffle console:

var ownable;
Ownable.deployed().then(function(instance){ownable = instance;})
ownable.transferOwnership(web3.eth.accounts[1]);

The command var ownable; creates a new object called ownable. The next line defines this object as an instance of the contract that we created.
After both commands the truffle console will return the result ‘undefined’.

If you are familiar with programming already, you will see that the contract is essentially a class. Finally we transfer ownership of the contract from the account identified by index [0] to the account identified by index[1].

The event is executed and logged, yielding the following text in the console:

{ tx: '0x20a8fd775c5c26868b18b2b61c127e6acdbc02e509fb28783aa9594b9195c9bc',
  receipt:
   { transactionHash: '0x20a8fd775c5c26868b18b2b61c127e6acdbc02e509fb28783aa9594b9195c9bc',
     transactionIndex: 0,
     blockHash: '0xa433b974f3ea4ae87aa94229263f64b2b3947056d77ca7be6212a569a5d8cf27',
     blockNumber: 5,
     gasUsed: 29986,
     cumulativeGasUsed: 29986,
     contractAddress: null,
     logs: [ [Object] ],
     status: '0x1',
     logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000400000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000800000000000004010002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000060000000000000000000000000000100000' },
  logs:
   [ { logIndex: 0,
       transactionIndex: 0,
       transactionHash: '0x20a8fd775c5c26868b18b2b61c127e6acdbc02e509fb28783aa9594b9195c9bc',
       blockHash: '0xa433b974f3ea4ae87aa94229263f64b2b3947056d77ca7be6212a569a5d8cf27',
       blockNumber: 5,
       address: '0xcea93908c932064d61cd2dd1f72c974b190cc3ce',
       type: 'mined',
       event: 'TransferOwnership',
       args: [Object] } ] }

Congratulations, you have successfully built and executed your first contract!

*Ingrid Caton shares credit for this post

Tuesday, February 21, 2017

The Emergence and Functions of Money 2.0

To the lay observer, the existence of money appears to be a given, and this is if they even notice money’s peculiarity. Money is a good, but unlike other goods, its primary use is as a medium of exchange. In the pre-modern era, money was typically linked to a commodity, but in the modern financial system, this is no longer true – at least not for base money. So how does money become an object of its own, delinked from any use value? How does money arise at all?

Given that humans preexisted money, there must have been a time where money did not exist. This is consistent with the framework that we have built over the last several weeks. Remember that analysis starts with agents. These agents have preferences that are revealed as they engage in exchange. Implicit in this exchange is the existence property rights. Every agent has opportunities to engage in entrepreneurial action. Our agent acts to attain profit. She imagines that she can transform the world from its present state into one that she prefers more greatly. She forms an expectation that she will use to frame and guide her action. The agent may prove successful and attain the profit or may break even or even incur a loss. In typical fashion, we can extend this concept to exchange. Two agents, both looking to improve the state of their existence, notice that each has a good desired by the other. It so happens that each wants the good that the other holds so they exchange the goods. Each has improved his or her lot, although we cannot be sure by how much exactly as there is no such thing as a cardinal utility measure – not even for a single agent. We must take agent action at face value and accept the action as a contextually constrained expression of the agent’s preference.

Barter is easy to accommodate in the model when the agents lacks geography. Action, however, always occurs at a particular time and place. The agent interested in a trade, let’s call him agent A, must find another agent, agent B, who owns the object of desire and who is interested in trading it for something owned by agent A. Often, this double coincidence of wants fails to arise. The agent can continue looking for a single trading partner, or he can partition his work. Instead of finding only a single agent, he can find a good that is demanded by agent B and trade that intermediate good for the desired good. Over time, the agent might realize that there are one or several goods that most easily accommodate this indirect exchange. First several other agents notice this wise idea and begin to copy the innovation. A small number of goods come to be recognized as having value in exchange in addition to value in use. These goods are different forms of money.

As we have seen, money does not arise by the plan of a single individual. It arises without intention. The goal of agent A was simply to find a good desired by agent B. There is no need for agent A to expect that other agents will adopt his strategy. His goal was simple. As the innovation is copied, the commodity becomes a network good. It gains value because other agents are willing to use it in indirect exchange, and therefore, charge prices in terms of the intermediate good. The good that becomes money comes to serve as a numeraire in which prices are denominated.

What makes for a good money? History provides an answer. Societies have tended to select money that meets 5 criteria. Money must be
1. durable
2. easily divisible
3. relatively scarce
4. highly saleable
5. portable.

These qualities promote the function of money. With these criteria more or less present, money can serve as:
1. a medium of exchange
2. a store of value
3. a unit of account
4. a standard of deferred payment.
Notice that the criteria for money relate to its functions. Saleability and portability allows money to function as a medium of exchange in the first place. What good is a money that is difficult to carry? Increased portability makes a money more easily saleable and more broadly acceptable. Durability and scarcity promote money’s function as a store of value. Divisibility is closely linked to money’s role as a unit of account. Prices, denominated in the unit of account, are more easily accommodated if money can be divided into homogeneous units. Given a common unit of account, agents can also lend money to one another. This allows an agent to attain a good that she otherwise could not afford or would be unable to borrow. Thus, money becomes a standard of deferred payment.

The development of money represents an innovation in accounting. A common standard or standards of measure allow for an approximation of the socially determined value of a good. Since prices are denominated in a common unit of account, the value of different goods, as determined in light of the demand of consumers and cost of supply, can be compared objectively. These prices represent the quantity of money a good can fetch if it is sold on the market. This allows producers to compare costs and revenues so that they can be certain of the magnitudes of their gain or loss.

These prices fluctuate according to changes in the quantity demanded at a given price (shifts in the demand curve) or as quantities available at given prices fluctuate (shift in the supply curve). They also change if either of these factors are expected to change. Thus, prices reflect not only present conditions but also expected changes in these factors. Since prices reflect information about agent valuations, they increase the accuracy with which agents can account for the value of their goods. This promotes an allocation of goods that reflect needs of all agents the preferences and budget constraints of those agents. With the addition of money, our model contains the building blocks requisite for economic calculation and widespread patterns of exchange.

Market regulation of the quantity of money

Just as money emerges from within a market dependent upon barter exchange, the quantity of money is also determined by market forces. Imagine that in some market, oats become the commonly accepted medium of exchange overnight. This change means that any person who buys or sells goods is willing to let money represent the other half of the exchange. A farmer who sells an apple use negotiates a price in terms of some weight of oats. He buys other goods using these same oats. 

Suppose that a community recognizes, overnight, that oats can now be used as money. Instantly demand for oats will increase as agents understand that oats can be exchanged for other goods. That is, oast not only have a use value – they can be eaten – but they also have an exchange value – they can be used to acquire other goods. The new price of oats, p1 (Figure 1) represent the combined use and exchange values. The original price, p0, represent the use value of oats. The difference between these two (p0 – p1), represent value derived from exchange. Note that if the supply curve was perfectly inelastic at q0, that the exchange value would be reflected by price implied at the intersection of Q0 and D1. For this example, the exchange value of oats in the short-run will be higher than the price reached in the long-run equilibrium.

The higher price sustained by the use of oats as medium of exchange incentivize greater production of oats. If the price is pushed high enough, it can also incentivize the development of technology that reduces the cost of oat production. Something similar occurred at the end of the 19th century when a relatively high price of gold incentivized the development of cyanide extraction process. For oats, this may include the development of new irrigation techniques or systematic use and breeding of the most productive strains of oats, among other possibilities. If the technology successfully reduces the cost of producing a unit of oats, the cost of supply falls. We represent this by shifting the supply curve to the right (Figure 2). Suppose that oat farmers suffer a drought one year. What will happen to the price of oats? In the case of a drought, the cost of supply increases. The supply curve for oats will shift left and the value of oats will increase.

Figure 1

Figure 2


The price of money
You may ask yourself, if oats are money, how do we determine their price. For any money, its price is what it exchanges for. If a quart of oats trades for 2 apples in equilibrium, then the price of a quart of oats is two apples. Likewise, if the same quart trades for 3 oranges, then the price of a quart of oats is also 3 oranges. Likewise, the price of an apple is 1/2 quart of oats and the price of an orange is 1/3 quart of oats. Money has an array of prices. Thus, the price of money is whatever it can exchange for. What we usually mean by the price of money, however, is the average price of money. This is often referred to as its purchasing power. Typically, we refer to the price level, which is the inverse of the purchasing power of money. A price index considers all exchanges for each type of good. Ideally, the price of each category of good sold is weighted according to the total number of goods exchanged. In reality, the basket of goods and weights of these goods change overtime, so there exists no perfect estimation of the price level and, by implication, the purchasing power of money.



[1] Another term commonly used is the purchasing power of money.

*Expanded from The Emergence and Functions of Money

Specialization and the Extended Order

In earliest society, the number of jobs that were available to men and women were limited. They were also strictly allocated on the basis of gender. Goods were allocated amongst a community according to one’s position in the hierarchy. As society grows larger, this structure of cooperation is difficult to maintain. Groups tend to divide at Dunbar’s number, which lies somewhere between 150 and 300 persons. When groups split in two, there will likely remain contact and cooperation between the groups, but as groups grow more numerous they become more difficult to manage. The structure of society must become more sophisticated if many parts are to form a coherent whole.

In a world where resources are scarce, humans must necessarily be value creating if they are to survive. At its core, this value consists in the provision of goods that promote survival. In pre-modern society, this may consist only of finding goods and shelter. As society grows more complex, many agents are expected to acquire more skills and means to augment their labor.  One person’s livelihood may depend on his Volkswagen van to deliver mail in rural Nebraska. The van is a means to providing the income that maintains his life. Others must develop specialized skills, a form of human capital, in order to offer a service that generates income. Plumbers, lathe operators, auto mechanics, programmers, and many other fall under this category. Blue collar and white collar jobs typically fall within this domain.

Specialization requires the development of technology and capital that embodies this technology. To move from a society of hunter-gatherers to a society of farmers, the technology for farming must be developed and spread. One cannot farm without knowledge of the seasons and of planting. One must also have available means of protecting one’s crops from hungry animal and thieves. All of this is technology that would otherwise be unnecessary and relatively costly in a world where food is abundant. As regions become more crowded, inhabitants face two options: move to regions with fewer people or begin farming. Hunter-gathering groups cannot remain in these areas. Herders are forced to the outskirts of this society as farmers develop land for intensive cultivation. The movement from a life in transit to a relatively sedentary existence enables the formation of a governing structure that is also stable. This may not happen immediately, but it does not take long. We will discuss this further in the next lecture.

Specialization and Technological Development

Specialization also enables the development of technology and capital. Imagine two castaways stranded one an island. We often use the story of Robinson Crusoe in this manner. Crusoe, stranded on an island, must find the means to satisfy his desire for food and shelter. He cannot work simultaneously to achieve both. Thus, he must spend some portion of his time fishing or harvesting coconuts and another portion to dedicated to building and maintain shelter. As long as Robinson Crusoe is alone, it is difficult for him to develop means for either. When Friday arrives on the island, he brings with him similar demand for food and shelter. Yet, the economic problem becomes more complex and, therefore, provides more possibilities. If Friday enjoys fishing, he can spend his time gathering food in this manner while Robinson Crusoe concentrates his energies on providing shelter. Perhaps Friday can catch enough fish for Robinson Crusoe in 6 hours. If he likes, he can spend the rest of the day resting. However, since Robinson Crusoe is working on the other side of the island, he may feel an obligation to contribute to the team so as to leave everyone better off. Suppose that Friday would like to be able to catch more fish in less time, so he spends his free time trying to create a net. At first, this is a laborious process as he lacks the knowledge for this, so he must spend time experimenting. Perhaps Friday needs two months two develop a proper net. Once he has discovered a successful strategy for building nets, he dedicate less time to fishing. Further, the time taken to create a new net will be less as it will not require the initial costs of discovery that Crusoe first faced. Now Crusoe can spend his time searching for new food sources. Or if he would, he can work with Robinson Crusoe to improve their shelter.

Once shelter is built, Robinson Crusoe and Friday will need clothes to stay warm at night. If the productive potential of both persons for each good is given, we can perform some simple operations to understand how specialize improve outcomes in a world of exchange. Imagine that, if Robinson Crusoe and Friday specialized, their maximum production of either good is as follows.
Table 1
Production Possibilities
Frontier

RC
F

Clothing
20
20
Fish
10
30

If both Robinson Crusoe and Friday split their productive energies evenly between the two goods, they will produce the following amounts.
Table 2
Production absent
 Specialization
and Trade

RC
F

Clothing
10
10
Fish
5
15

This is not the most efficient outcome. Robinson Crusoe must sacrifice 2 units of clothing for every fish he catches, while Friday sacrifices 2/3 units of clothing for every 1 fish he catches. Inversely, he sacrifices 1.5 fish for every 1 unit of clothing he creates. If they were to specialize, they would produce as follows
Table 3
Production
with Specialization
and Trade

RC
F

Clothing
20
0
Fish
0
30

Robinson Crusoe will be willing to trade up to 2 pieces of clothing for 1 fish. Let’s assume that Friday is willing to trade fish at a price of one piece of clothing, which he would surely accept because the opportunity cost of producing one unit of clothing himself is 1.5 fish. That represents a discount of 1/3 for Friday. In the final allocation, Robinson Crusoe has 5 more fish than he could produce on his own. Friday also has 5 more fish. As fish provide positive utility to both parties, we observe a pure pareto improvement as a result of specialization and exchange.

Table 4
Final Quantities
with Specialization
and Trade

RC
F

Clothing
10
10
Fish
10
20

If both Robinson Crusoe and Friday develop technology to improve their efficiency, we may see their production possibilities frontier shift out. We could perform the same exercise and see that, assuming that specialization enables the development of technology, the situation of both parties will continue to improve so long as technological advancement is possible.

Table 5
New Technology Shifts
Production Possibilities
Frontier

RC
F

Clothing
40
20
Fish
10
50

One change enables another. The development of a more cost efficient form of production can support larger populations and more complex societies. Before this change, it may be difficult for metallurgists to survive. To the extent that one can develop and maintain a social position for oneself with a specialization such as this, he can maintain his well-being through production and exchange. Likewise, this change in society opens the opportunity for carpenters who have specialized knowledge of constructing and repairing buildings. Underlying this change is the fundamental principle we identified early on: humans act to improve the state of the world as they perceive it.

Decision to action occurs in light of the costs and benefits that such action is expected to generate. Humans rarely imagine radical change. Even that thought be radical is usually marginal in light of the present state. Thomas Edison’s discovery of the light bulb, while unexpected by many, required a combination of elements that were readily available to him. This innovation required a search through the vast space of possibility that exists at the fringes of existence. Once found it may enable and encourage many other innovations that were not previously possible. The development of the light bulb, for example, made valuable the provision of electricity in cities. This further provision opened up many opportunities as it allowed for technical development and specialization that would have otherwise been impossible.

Comparative Advantage and Opportunity Cost

So far, we have been thinking of action solely in terms of the exploitation and creation of profit opportunities. If we also integrate the notion of the opportunity cost that inherently exists as a result of living in a world of scarcity, we add another dimension to specialization. Ricardo first spoke of this dimension as comparative advantage. Consider the job of Stephen Curry who plays for the Golden State Warriors. Stephen Curry is a phenomenal leader and basketball player. He seems to make best use of his talents playing for the Golden State Warriors. Curry is not just a talented player, his presence is a unifying force that has helped move the team to win a championship and a heartbreaking miss last season. The opportunity cost of Curry’s participation with the Golden State Warriors is likely participation with another team. The value he creates for the Golden State Warriors is substantial enough that the team has retained him since his entrance in 2009. Although Curry would likely be valuable for any team on which he plays, he has a comparative advantage playing for the Golden State Warriors.

This becomes more obvious if Curry were to change his occupation altogether. Curry may be a fantastic manager. When he graduated from college, he could have entered a field that allowed him to exploit his leadership ability through management. Even if Curry was one of the best managers, it would be difficult for him to surpass his current pay and other benefits he receives playing for the Warriors. This is to say that Curry may have an absolute advantage in comparison to others both in his management ability and his ability on the basketball court. Market prices, however, inform Curry that the most valuable use of his skills will leave him playing for the Warriors, even if he had an absolute advantage as a manager and as a basketball player, he has a comparative advantage in playing basketball.

Comparative advantage allows us to explore areas that may, at first glance, seem to be a source of waste or laziness. Bill Gates, who is estimated to be the world’s wealthiest person in 2017, generates a tremendous amount of value with his time. It makes little sense for Bill Gates to spend time preparing meals or cleaning his own home. Every moment he spends engaged in this activity, he could be dedicating to create more value elsewhere. Cleaning and cooking is especially costly for Bill Gates. He is better served by purchasing cleaning and cooking services than by performing these tasks himself. He may choose to do this simply out of enjoyment of the activity or belief in the personal enrichment from such activity. In terms of value as measured by money prices, he is incurring great cost if he chooses to do so.


Development of specialization that arises due to comparative advantage plays a significant role in the provision of knowledge in society. Specialization itself allow individuals to develop knowledge of a particular category of activity. Gold refining processes could not be developed unless individuals were allowed to spend their time and creative energies developing them. The same can be said of computer processors, means of transportation, mass production, and so forth. The development of cost-reducing technology that allowed much farmland to be tended by far fewer people has allowed individuals to invest their labor in other ventures. It is no coincidence that, within a century of this shift, we live in a world that is dominated by technology. The pace of change appears only to increase as freedom to develop technology and organization also increases.

(Table structure borrowed from Don Boudreaux's article on comparative advantage.)