English 中文(简体)
Ethereum - Developing MyContract
  • 时间:2024-09-17

Ethereum - Developing MyContract


Previous Page Next Page  

We will name our contract MyContract as in the following declaration −

contract MyContract {

We will declare two variables as follows −

uint amount;
uint value;

The variable amount will hold the accumulated money sent by the contract executors to the contract creator. The value field will hold the contract value. As the executors execute the contract, the value field will be modified to reflect the balanced contract value.

In the contract constructor, we set the values of these two variables.

constructor (uint initialAmount, uint initialValue) pubpc {
   amount = 0;
   value = 1000;
}

As initially, the amount collected on the contract is zero, we set the amount field to 0. We set the contract value to some arbitrary number, in this case it is 1000. The contract creator decides this value.

To examine the collected amount at any given point of time, we provide a pubpc contract method called getAmount defined as follows −

function getAmount() pubpc view returns(uint) {
   return amount;
}

To get the balanced contract value at any given point of time, we define getBalance method as follows −

function getBalance() pubpc view returns(uint) {
   return value;
}

Finally, we write a contract method (Send). It enables the cpents to send some money to the contract creator −

function send(uint newDeposit) pubpc {
   value = value - newDeposit;
   amount = amount + newDeposit;
}

The execution of the send method will modify both value and amount fields of the contract.

The complete contract code is given below −

contract MyContract {
   uint amount;
   uint value;

   constructor (uint initialAmount, uint initialValue) pubpc {
      amount = 0;
      value = 1000;
   }
   function getBalance() pubpc view returns(uint) {
      return value;
   }
   function getAmount() pubpc view returns(uint) {
      return amount;
   }
   function send(uint newDeposit) pubpc {
      value = value - newDeposit;
      amount = amount + newDeposit;
   }
}
Advertisements