Code has been added to clipboard!
Solidity Contract Creation Basics Example
Example
pragma solidity ^0.4.0;
contract OwnToken {
// The contract type TokenGenerator is defined below.
// So long you do not use it to create a new contract,
// you can reference it.
TokenGenerator creator;
address owner;
bytes32 name;
// The constructor below is used to register the
// assigned name and the creator.
function OwnToken(bytes32 _name) {
// State variables get accessed using their name
// instead of, for example, this.owner. This applies
// to functions and even more so in constructors,
// as they can only be called this way, that is, "internally",
// since the contract is non-existent for now.
owner = msg.sender;
// We perform an type conversion explicitly from 'address'
// to `TokenGenerator`, assuming that the type of
// the contract that is calling is TokenGenerator, there is
// no actual way of checking that.
creator = TokenGenerator(msg.sender);
name = _name;
}
function nameChange(bytes32 nameNew) {
// The only one capable of altering the name is the creator --
// the comparison can be done since contracts
// can be implicitly converted to addresses.
if (msg.sender == address(creator))
name = nameNew;
}
function transfer(address ownerNew) {
// The current owner only may transfer the token.
if (msg.sender != owner) return;
// Also we would like to ask the creator whether the transfer
// is fine or not. Keep in mind that this calls a function of the
// contract that is only below. If the call happens to fail (e.g.
// due to an out-of-gas exception), the execution here will stop
// right away.
if (creator.isTokenTransferSuccess(owner, ownerNew))
owner = ownerNew;
}
}
contract TokenGenerator {
function generateToken(bytes32 name)
returns (OwnToken addressToken)
{
// A new token is created and returned to its address.
// From the side of JavaScript, the return type is simply
// "address", since this type is the closest available in
// the ABI.
return new OwnToken(name);
}
function nameChange(OwnToken addressToken, bytes32 name) {
// "addressToken" has the external type is "address".
addressToken.nameChange(name);
}
function isTokenTransferSuccess(
address currentOwner,
address ownerNew
) returns (bool ok) {
// Check an arbitrary condition.
address addressToken = msg.sender;
return (keccak256(ownerNew) & 0xff) == (bytes20(addressToken) & 0xff);
}
}