Solidity Read Transaction Hash Data Inside Smart Contract

A smart contract is a program that runs at an address on Ethereum. They're made up of data and functions that tin can execute upon receiving a transaction. Here's an overview of what makes up a smart contract.

Brand sure you've read about smart contracts first. This certificate assumes you're already familiar with programming languages such as JavaScript or Python.

Whatever contract data must be assigned to a location: either to storage or retentiveness. It'due south plush to modify storage in a smart contract so y'all need to consider where your data should live.

Persistent data is referred to as storage and is represented by state variables. These values become stored permanently on the blockchain. Y'all need to declare the type so that the contract tin keep track of how much storage on the blockchain it needs when it compiles.

          

1 // Solidity instance

two contract SimpleStorage {

3 uint storedData; // State variable

4 // ...

5 }

half-dozen

đź“‹ Copy

          

1

ii storedData : int128

3

đź“‹ Copy

If you've already programmed object-oriented languages, you'll likely exist familiar with almost types. However address should be new to y'all if you're new to Ethereum development.

An address type tin can hold an Ethereum address which equates to 20 bytes or 160 bits. It returns in hexadecimal notation with a leading 0x.

Values that are just stored for the lifetime of a contract function'southward execution are called memory variables. Since these are not stored permanently on the blockchain, they are much cheaper to employ.

Larn more than almost how the EVM stores data (Storage, Memory, and the Stack) in the Solidity docs.

In improver to the variables you define on your contract, there are some special global variables. They are primarily used to provide information about the blockchain or current transaction.

In the most simplistic terms, functions tin can become information or set information in response to incoming transactions.

          

1 // Solidity instance

ii office update_name(string value) public {

3 dapp_name = value;

four }

5

đź“‹ Copy

These functions promise not to alter the state of the contract's data. Common examples are "getter" functions – you might use this to receive a user's remainder for instance.

          

1 // Solidity instance

2 office balanceOf(address _owner) public view returns (uint256 _balance) {

iii render ownerPizzaCount[_owner];

4 }

5

đź“‹ Re-create

          

1 dappName : public ( string )

2

three @view

iv @public

v def readName ( ) - > cord :

6 render dappName

7

đź“‹ Copy

constructor functions are only executed in one case when the contract is outset deployed. Similar constructor in many form-based programming languages, these functions often initialize state variables to their specified values.

          

i // Solidity example

ii // Initializes the contract'south data, setting the `possessor`

3 // to the accost of the contract creator.

4 constructor() public {

v // All smart contracts rely on external transactions to trigger its functions.

6 // `msg` is a global variable that includes relevant information on the given transaction,

7 // such as the address of the sender and the ETH value included in the transaction.

8 // Larn more: https://solidity.readthedocs.io/en/v0.5.x/units-and-global-variables.html#block-and-transaction-properties

nine owner = msg.sender;

10 }

eleven

Prove all

đź“‹ Copy

          

ane

2

3 @external

4 def __init__ ( _beneficiary : accost , _bidding_time : uint256 ) :

5 self . casher = _beneficiary

6 cocky . auctionStart = block . timestamp

7 cocky . auctionEnd = self . auctionStart + _bidding_time

8

đź“‹ Re-create

In addition to the variables and functions you define on your contract, at that place are some special congenital-in functions. The most obvious example is:

These let contracts to send ETH to other accounts.

          

ane pragma solidity >=0.iv.0 <=0.six.0;

two

3 contract ExampleDapp {

iv string dapp_name; // state variable

five

6 // Chosen when the contract is deployed and initializes the value

7 constructor() public {

8 dapp_name = "My Example dapp";

9 }

10

11 // Get Office

12 function read_name() public view returns(string) {

xiii render dapp_name;

14 }

15

xvi // Prepare Function

17 office update_name(string value) public {

eighteen dapp_name = value;

nineteen }

20 }

21

Evidence all

đź“‹ Copy

A complete contract might wait something like this. Here the constructor part provides an initial value for the dapp_name variable.

Events let you communicate with your smart contract from your frontend or other subscribing applications. When a transaction is mined, smart contracts tin emit events and write logs to the blockchain that the frontend can and then procedure.

These are some examples written in Solidity. If you'd like to play with the code, yous can collaborate with them in Remix.

          

i // Specifies the version of Solidity, using semantic versioning.

2 // Learn more than: https://solidity.readthedocs.io/en/v0.v.ten/layout-of-source-files.html#pragma

3 pragma solidity ^0.five.10;

four

v // Defines a contract named `HelloWorld`.

half-dozen // A contract is a collection of functions and data (its state).

7 // Once deployed, a contract resides at a specific address on the Ethereum blockchain.

eight // Learn more: https://solidity.readthedocs.io/en/v0.5.10/structure-of-a-contract.html

9 contract HelloWorld {

x

11 // Declares a country variable `message` of type `string`.

12 // State variables are variables whose values are permanently stored in contract storage.

xiii // The keyword `public` makes variables accessible from outside a contract

xiv // and creates a function that other contracts or clients can call to access the value.

15 string public message;

16

17 // Similar to many grade-based object-oriented languages, a constructor is

18 // a special function that is only executed upon contract creation.

19 // Constructors are used to initialize the contract'due south data.

xx // Acquire more: https://solidity.readthedocs.io/en/v0.v.10/contracts.html#constructors

21 constructor(string retention initMessage) public {

22 // Accepts a string statement `initMessage` and sets the value

23 // into the contract's `message` storage variable).

24 bulletin = initMessage;

25 }

26

27 // A public part that accepts a string argument

28 // and updates the `message` storage variable.

29 function update(string memory newMessage) public {

xxx message = newMessage;

31 }

32 }

33

Testify all

đź“‹ Re-create

          

1 pragma solidity ^0.5.10;

2

3 contract Token {

4 // An `address` is comparable to an e-mail accost - it's used to place an business relationship on Ethereum.

5 // Addresses can represent a smart contract or an external (user) accounts.

6 // Larn more than: https://solidity.readthedocs.io/en/v0.five.10/types.html#address

7 address public owner;

viii

9 // A `mapping` is essentially a hash table data construction.

10 // This `mapping` assigns an unsigned integer (the token remainder) to an address (the token holder).

11 // Acquire more than: https://solidity.readthedocs.io/en/v0.5.10/types.html#mapping-types

12 mapping (address => uint) public balances;

13

fourteen // Events allow for logging of activity on the blockchain.

fifteen // Ethereum clients can listen for events in social club to react to contract country changes.

16 // Learn more than: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#events

17 issue Transfer(accost from, accost to, uint amount);

18

19 // Initializes the contract's data, setting the `owner`

20 // to the address of the contract creator.

21 constructor() public {

22 // All smart contracts rely on external transactions to trigger its functions.

23 // `msg` is a global variable that includes relevant information on the given transaction,

24 // such every bit the address of the sender and the ETH value included in the transaction.

25 // Acquire more: https://solidity.readthedocs.io/en/v0.five.10/units-and-global-variables.html#block-and-transaction-properties

26 owner = msg.sender;

27 }

28

29 // Creates an amount of new tokens and sends them to an address.

thirty office mint(address receiver, uint amount) public {

31 // `require` is a control structure used to enforce certain weather.

32 // If a `require` statement evaluates to `faux`, an exception is triggered,

33 // which reverts all changes made to the land during the electric current call.

34 // Learn more: https://solidity.readthedocs.io/en/v0.five.10/control-structures.html#error-handling-assert-require-revert-and-exceptions

35

36 // Only the contract owner tin can phone call this role

37 require(msg.sender == owner, "You lot are not the possessor.");

38

39 // Enforces a maximum amount of tokens

40 crave(corporeality < 1e60, "Maximum issuance exceeded");

41

42 // Increases the balance of `receiver` by `amount`

43 balances[receiver] += amount;

44 }

45

46 // Sends an corporeality of existing tokens from any caller to an address.

47 office transfer(accost receiver, uint amount) public {

48 // The sender must have plenty tokens to send

49 require(corporeality <= balances[msg.sender], "Insufficient balance.");

50

51 // Adjusts token balances of the two addresses

52 balances[msg.sender] -= amount;

53 balances[receiver] += amount;

54

55 // Emits the event defined before

56 emit Transfer(msg.sender, receiver, amount);

57 }

58 }

59

Show all

đź“‹ Copy

          

1 pragma solidity ^0.5.10;

ii

3 // Imports symbols from other files into the current contract.

4 // In this case, a series of helper contracts from OpenZeppelin.

5 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/layout-of-source-files.html#importing-other-source-files

6

7 import "../node_modules/@openzeppelin/contracts/token/ERC721/IERC721.sol";

8 import "../node_modules/@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";

9 import "../node_modules/@openzeppelin/contracts/introspection/ERC165.sol";

ten import "../node_modules/@openzeppelin/contracts/math/SafeMath.sol";

11

12 // The `is` keyword is used to inherit functions and keywords from external contracts.

13 // In this case, `CryptoPizza` inherits from the `IERC721` and `ERC165` contracts.

fourteen // Learn more: https://solidity.readthedocs.io/en/v0.v.ten/contracts.html#inheritance

15 contract CryptoPizza is IERC721, ERC165 {

sixteen // Uses OpenZeppelin'due south SafeMath library to perform arithmetic operations safely.

17 // Learn more than: https://docs.openzeppelin.com/contracts/2.x/api/math#SafeMath

18 using SafeMath for uint256;

19

20 // Constant country variables in Solidity are similar to other languages

21 // but you must assign from an expression which is constant at compile fourth dimension.

22 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#constant-state-variables

23 uint256 abiding dnaDigits = 10;

24 uint256 constant dnaModulus = 10 ** dnaDigits;

25 bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;

26

27 // Struct types allow you define your ain type

28 // Learn more: https://solidity.readthedocs.io/en/v0.5.x/types.html#structs

29 struct Pizza {

xxx string proper noun;

31 uint256 dna;

32 }

33

34 // Creates an empty array of Pizza structs

35 Pizza[] public pizzas;

36

37 // Mapping from pizza ID to its possessor'south address

38 mapping(uint256 => address) public pizzaToOwner;

39

40 // Mapping from owner'due south address to number of owned token

41 mapping(address => uint256) public ownerPizzaCount;

42

43 // Mapping from token ID to approved accost

44 mapping(uint256 => address) pizzaApprovals;

45

46 // You can nest mappings, this case maps possessor to operator approvals

47 mapping(address => mapping(address => bool)) individual operatorApprovals;

48

49 // Internal function to create a random Pizza from string (name) and Deoxyribonucleic acid

50 function _createPizza(string memory _name, uint256 _dna)

51 // The `internal` keyword means this function is only visible

52 // within this contract and contracts that derive this contract

53 // Larn more: https://solidity.readthedocs.io/en/v0.5.10/contracts.html#visibility-and-getters

54 internal

55 // `isUnique` is a part modifier that checks if the pizza already exists

56 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/structure-of-a-contract.html#role-modifiers

57 isUnique(_name, _dna)

58 {

59 // Adds Pizza to array of Pizzas and get id

sixty uint256 id = SafeMath.sub(pizzas.push button(Pizza(_name, _dna)), 1);

61

62 // Checks that Pizza owner is the same as current user

63 // Learn more: https://solidity.readthedocs.io/en/v0.5.10/control-structures.html#mistake-handling-assert-require-revert-and-exceptions

64 assert(pizzaToOwner[id] == accost(0));

65

66 // Maps the Pizza to the owner

67 pizzaToOwner[id] = msg.sender;

68 ownerPizzaCount[msg.sender] = SafeMath.add(

69 ownerPizzaCount[msg.sender],

70 1

71 );

72 }

73

74 // Creates a random Pizza from string (proper noun)

75 office createRandomPizza(cord memory _name) public {

76 uint256 randDna = generateRandomDna(_name, msg.sender);

77 _createPizza(_name, randDna);

78 }

79

80 // Generates random Deoxyribonucleic acid from string (name) and address of the owner (creator)

81 role generateRandomDna(string memory _str, address _owner)

82 public

83 // Functions marked as `pure` promise not to read from or change the land

84 // Learn more: https://solidity.readthedocs.io/en/v0.v.10/contracts.html#pure-functions

85 pure

86 returns (uint256)

87 {

88 // Generates random uint from string (name) + address (possessor)

89 uint256 rand = uint256(keccak256(abi.encodePacked(_str))) +

xc uint256(_owner);

91 rand = rand % dnaModulus;

92 return rand;

93 }

94

95 // Returns array of Pizzas found past owner

96 role getPizzasByOwner(address _owner)

97 public

98 // Functions marked equally `view` promise not to modify state

99 // Learn more than: https://solidity.readthedocs.io/en/v0.5.ten/contracts.html#view-functions

100 view

101 returns (uint256[] retentivity)

102 {

103 // Uses the `memory` storage location to store values but for the

104 // lifecycle of this office call.

105 // Learn more: https://solidity.readthedocs.io/en/v0.5.ten/introduction-to-smart-contracts.html#storage-memory-and-the-stack

106 uint256[] memory result = new uint256[](ownerPizzaCount[_owner]);

107 uint256 counter = 0;

108 for (uint256 i = 0; i < pizzas.length; i++) {

109 if (pizzaToOwner[i] == _owner) {

110 result[counter] = i;

111 counter++;

112 }

113 }

114 return issue;

115 }

116

117 // Transfers Pizza and ownership to other address

118 function transferFrom(address _from, address _to, uint256 _pizzaId) public {

119 require(_from != address(0) && _to != address(0), "Invalid address.");

120 require(_exists(_pizzaId), "Pizza does not be.");

121 require(_from != _to, "Cannot transfer to the same address.");

122 require(_isApprovedOrOwner(msg.sender, _pizzaId), "Accost is not approved.");

123

124 ownerPizzaCount[_to] = SafeMath.add together(ownerPizzaCount[_to], 1);

125 ownerPizzaCount[_from] = SafeMath.sub(ownerPizzaCount[_from], 1);

126 pizzaToOwner[_pizzaId] = _to;

127

128 // Emits upshot divers in the imported IERC721 contract

129 emit Transfer(_from, _to, _pizzaId);

130 _clearApproval(_to, _pizzaId);

131 }

132

133 /**

134 * Safely transfers the ownership of a given token ID to another address

135 * If the target address is a contract, information technology must implement `onERC721Received`,

136 * which is called upon a prophylactic transfer, and return the magic value

137 * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`;

138 * otherwise, the transfer is reverted.

139 */

140 function safeTransferFrom(address from, address to, uint256 pizzaId)

141 public

142 {

143 // solium-disable-side by side-line arg-overflow

144 this.safeTransferFrom(from, to, pizzaId, "");

145 }

146

147 /**

148 * Safely transfers the ownership of a given token ID to some other address

149 * If the target accost is a contract, information technology must implement `onERC721Received`,

150 * which is called upon a safe transfer, and render the magic value

151 * `bytes4(keccak256("onERC721Received(accost,address,uint256,bytes)"))`;

152 * otherwise, the transfer is reverted.

153 */

154 function safeTransferFrom(

155 address from,

156 address to,

157 uint256 pizzaId,

158 bytes memory _data

159 ) public {

160 this.transferFrom(from, to, pizzaId);

161 require(_checkOnERC721Received(from, to, pizzaId, _data), "Must implement onERC721Received.");

162 }

163

164 /**

165 * Internal part to invoke `onERC721Received` on a target address

166 * The call is non executed if the target address is not a contract

167 */

168 function _checkOnERC721Received(

169 address from,

170 address to,

171 uint256 pizzaId,

172 bytes memory _data

173 ) internal returns (bool) {

174 if (!isContract(to)) {

175 return true;

176 }

177

178 bytes4 retval = IERC721Receiver(to).onERC721Received(

179 msg.sender,

180 from,

181 pizzaId,

182 _data

183 );

184 return (retval == _ERC721_RECEIVED);

185 }

186

187 // Burns a Pizza - destroys Token completely

188 // The `external` function modifier ways this function is

189 // part of the contract interface and other contracts tin telephone call it

190 function fire(uint256 _pizzaId) external {

191 require(msg.sender != accost(0), "Invalid address.");

192 require(_exists(_pizzaId), "Pizza does non exist.");

193 crave(_isApprovedOrOwner(msg.sender, _pizzaId), "Accost is non canonical.");

194

195 ownerPizzaCount[msg.sender] = SafeMath.sub(

196 ownerPizzaCount[msg.sender],

197 ane

198 );

199 pizzaToOwner[_pizzaId] = accost(0);

200 }

201

202 // Returns count of Pizzas past address

203 office balanceOf(address _owner) public view returns (uint256 _balance) {

204 render ownerPizzaCount[_owner];

205 }

206

207 // Returns owner of the Pizza institute by id

208 office ownerOf(uint256 _pizzaId) public view returns (address _owner) {

209 address owner = pizzaToOwner[_pizzaId];

210 crave(owner != address(0), "Invalid Pizza ID.");

211 return owner;

212 }

213

214 // Approves other address to transfer ownership of Pizza

215 function approve(accost _to, uint256 _pizzaId) public {

216 require(msg.sender == pizzaToOwner[_pizzaId], "Must exist the Pizza owner.");

217 pizzaApprovals[_pizzaId] = _to;

218 emit Approval(msg.sender, _to, _pizzaId);

219 }

220

221 // Returns approved address for specific Pizza

222 function getApproved(uint256 _pizzaId)

223 public

224 view

225 returns (address operator)

226 {

227 require(_exists(_pizzaId), "Pizza does not be.");

228 return pizzaApprovals[_pizzaId];

229 }

230

231 /**

232 * Private function to clear current approval of a given token ID

233 * Reverts if the given address is not indeed the owner of the token

234 */

235 function _clearApproval(address possessor, uint256 _pizzaId) individual {

236 crave(pizzaToOwner[_pizzaId] == owner, "Must be pizza owner.");

237 require(_exists(_pizzaId), "Pizza does not be.");

238 if (pizzaApprovals[_pizzaId] != accost(0)) {

239 pizzaApprovals[_pizzaId] = address(0);

240 }

241 }

242

243 /*

244 * Sets or unsets the approval of a given operator

245 * An operator is immune to transfer all tokens of the sender on their behalf

246 */

247 function setApprovalForAll(address to, bool canonical) public {

248 require(to != msg.sender, "Cannot approve own address");

249 operatorApprovals[msg.sender][to] = approved;

250 emit ApprovalForAll(msg.sender, to, approved);

251 }

252

253 // Tells whether an operator is approved past a given possessor

254 function isApprovedForAll(address possessor, accost operator)

255 public

256 view

257 returns (bool)

258 {

259 return operatorApprovals[owner][operator];

260 }

261

262 // Takes ownership of Pizza - simply for approved users

263 function takeOwnership(uint256 _pizzaId) public {

264 require(_isApprovedOrOwner(msg.sender, _pizzaId), "Address is not approved.");

265 address owner = this.ownerOf(_pizzaId);

266 this.transferFrom(owner, msg.sender, _pizzaId);

267 }

268

269 // Checks if Pizza exists

270 function _exists(uint256 pizzaId) internal view returns (bool) {

271 address possessor = pizzaToOwner[pizzaId];

272 return owner != address(0);

273 }

274

275 // Checks if address is owner or is approved to transfer Pizza

276 part _isApprovedOrOwner(address spender, uint256 pizzaId)

277 internal

278 view

279 returns (bool)

280 {

281 address possessor = pizzaToOwner[pizzaId];

282 // Disable solium cheque because of

283 // https://github.com/duaraghav8/Solium/bug/175

284 // solium-disable-next-line operator-whitespace

285 render (spender == possessor ||

286 this.getApproved(pizzaId) == spender ||

287 this.isApprovedForAll(owner, spender));

288 }

289

290 // Cheque if Pizza is unique and doesn't exist yet

291 modifier isUnique(string memory _name, uint256 _dna) {

292 bool effect = true;

293 for (uint256 i = 0; i < pizzas.length; i++) {

294 if (

295 keccak256(abi.encodePacked(pizzas[i].proper name)) ==

296 keccak256(abi.encodePacked(_name)) &&

297 pizzas[i].dna == _dna

298 ) {

299 event = false;

300 }

301 }

302 require(result, "Pizza with such proper name already exists.");

303 _;

304 }

305

306 // Returns whether the target address is a contract

307 function isContract(address account) internal view returns (bool) {

308 uint256 size;

309 // Currently there is no better way to check if at that place is a contract in an accost

310 // than to bank check the size of the code at that address.

311 // Run across https://ethereum.stackexchange.com/a/14016/36603

312 // for more details near how this works.

313 // TODO Check this again before the Tranquillity release, because all addresses will be

314 // contracts so.

315 // solium-disable-adjacent-line security/no-inline-associates

316 assembly {

317 size := extcodesize(account)

318 }

319 return size > 0;

320 }

321 }

322

Evidence all

đź“‹ Copy

Bank check out Solidity and Vyper's documentation for a more complete overview of smart contracts:

archibaldasaints.blogspot.com

Source: https://ethereum.org/en/developers/docs/smart-contracts/anatomy/

0 Response to "Solidity Read Transaction Hash Data Inside Smart Contract"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel