-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathsolidity.html
1653 lines (1278 loc) · 48.3 KB
/
solidity.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<base target="_blank">
<meta charset="utf-8">
<title>CCC: Cryptocurrency Course slide set</title>
<meta name="description" content="A set of slides for a course on Cryptocurrency">
<meta name="author" content="Aaron Bloomfield">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, minimal-ui">
<link rel="stylesheet" href="../slides/reveal.js/dist/reset.css">
<link rel="stylesheet" href="../slides/reveal.js/dist/reveal.css">
<link rel="stylesheet" href="../slides/reveal.js/dist/theme/black.css" id="theme">
<link rel="stylesheet" href="../slides/ccc.css">
<!-- Code syntax highlighting -->
<link rel="stylesheet" href="../slides/reveal.js/plugin/highlight/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? '../slides/reveal.js/css/print/pdf.scss' : '../slides/reveal.js/css/print/paper.scss';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
<!--[if lt IE 9]>
<script src="../slides/reveal.js/lib/js/html5shiv.js"></script>
<![endif]-->
<style>
.reveal li {
font-size:90%;
line-height:120%;
}
</style>
</head>
<body>
<div class="reveal">
<!-- Any section element inside of this container is displayed as a slide -->
<div class="slides">
<section data-markdown><textarea>
# CS 4501
### Cryptocurrency
<p class='titlep'> </p>
<div class="titlesmall"><p>
<a href="http://www.cs.virginia.edu/~asb">Aaron Bloomfield</a> ([email protected])<br>
<a href="http://github.com/aaronbloomfield/ccc">@github</a> | <a href="index.html">↑</a> | <a href="?print-pdf"><img class="print" width="20" src="../slides/images/print-icon.png" style="top:0px;vertical-align:middle"></a>
</p></div>
<p class='titlep'> </p>
## Solidity
</textarea></section>
<section data-markdown><textarea>
# Contents
[Types](#/types)
[Concepts](#/concepts)
[Poll Example](#/poll)
[Debtor's Example](#/debtor)
[Testing & Debugging](#/debugging)
</textarea></section>
<!-- ============================================================ -->
<section>
<section id="types" data-markdown class="center"><textarea>
# Types
</textarea></section>
<section data-markdown data-separator="^\n\n\n"><textarea>
## Sources
- The main reference for this slide set is the [Solidity language documentation](https://docs.soliditylang.org/en/latest/index.html)
- URL: https://docs.soliditylang.org/en/latest/index.html
- This section is the [Types section therein](https://docs.soliditylang.org/en/latest/types.html)
- https://docs.soliditylang.org/en/latest/types.html
- Many of the examples herein are from there
- Also some code examples from the [Poll.sol](../hws/dappintro/Poll.sol.html) contract from the [dApp introduction](../hws/dappintro/index.html) assignment
## A note about these slides
- These slides are meant as a explanation
- You are not expected to remember everything!
- Since you all know OOP, it's just showing what is different in Solidity
- You can come back to use this as a reference later
## Value types: integers
- Signed and unsigned ints from 8 bits (1 byte) to 256 bits (32 bytes) in size
- And in all byte sizes between
- Unsigned: `uint8`, `uint16`, `uint24`, ... `uint256`
- `uint` is an alias for `uint256`
- Signed: `int8`, `int16`, `int24`, ..., `int256`
- `int` is an alias for `int256`
- Standard operations (arithmetic, comparisons, bit operators, shift operators)
- Exponentiation is $\ast \ast$
- `type(int256).max` and `type(uint160).min` for min/max
## Value types: integers
- Most used: `uint` (aka `uint256`) and `uint8`
- Warning: a subtraction into a `uint` that is negative will cause a reversion
- A revert is basically an abort -- more on this later
- And it will not give a useful error message indicating so!
## Integer literals
- Scientific notation: `1e12` equals $10^{12}$
- `3.4e8` equals $3.4 \ast 10^8$
- Underscores separate digits for readability, but do not affect its value
- 0x12345678 == 0x1234_5678
## Other value types
- Booleans: type is `bool`, values are `true` and `false`
- All comparisons evaluate to a Boolean
- Fixed point numbers: not yet fully supported
- Types are `fixed` and `ufixed`
- But don't use them!
- No floating point numbers!
- Note that all variables have an initial value of 0
## Addresses
- Types are `address` and `address payable`
- It's just a number: a 160-bit (20 byte) Ethereum address
- Allows standard comparison operators
- Used for:
- Keeping track of who is the contract initiator
- Addresses of other contracts to call
- Can cast between `address` and: `uint160` or `bytes20`
```
address a = address(0);
uint160 u = uint160(a);
bytes20 b = bytes20(u);
```
- The address of a caller of a function is in `msg.sender`
## Address examples
- You can convert to a payable address:
```
address a;
// set a = something...
address payable b = payable(a);
```
- Conversions:
```
uint160 b = uint160(msg.sender);
bytes20 c = bytes20(msg.sender);
```
- More examples:
```
if ( a == address(0) ) { ... }
address initiator = msg.sender;
```
## Address fields
- Although a primitive type, it has fields and methods:
- `balance`: the balance, in wei, for that address
```
address payable x = payable(0x123);
address myAddress = address(this);
if (x.balance < 10 && myAddress.balance >= 10) {...}
```
- Other methods we won't see in this course:
- `transfer()` to send wei (requires a `receive()` function on the receiving contract)
- `send()`: low-level and not safe version of `transfer()`
- `call()`, `delegatecall()`, and `staticcall()`: calling a contract with an unknown ABI
- `code()` and `codehash()` to get the bytecode of the contract
## Fixed-sized Byte Arrays
- Fixed sized array of bytes: `bytes1`, `bytes2`, up to `bytes32`
- The size is the integer in the type name; max of 32 bytes
- `.length` to get the length
- Indexing with `[]`
- Operators:
- Comparisons, bit operators, shift operators
- Treats the byte array like a similarly sized `uint` when performing the operation
## Dynamically-sized arrays
- `bytes`: dynamically sized array of bytes
- `string`: dynamically sized array of UTF-8 characters
- We'll see string functions in a bit...
## String literals
- Strings can be enclosed in single quotes or double quotes
- Can use the backslash for escape characters
- Two strings next to each other is concatenation:
```
string s = "CS" '4501'; // equals "CS4501"
```
## More general arrays
- We can create arrays of any type:
```
uint8[6] memory p = [ 1, 2, 3, 4, 5, 6 ];
```
- We'll see the `memory` keyword shortly...
## Enums
- Enumerated type, which is mapped to a `uint`
```
enum ActionChoices { GoLeft, GoRight,
GoStraight, SitStill }
ActionChoices choice;
ActionChoices constant default = ActionChoices.GoLeft;
function setGoStraight() public {
choice = ActionChoices.GoStraight;
}
```
## Mappings
- An associative array (like a hash table) that holds a key-value pair
```
mapping (address => bool) public override voted;
mapping (uint => Choice) internal _choices;
```
- We'll talk about `public`, `internal`, and `override` later
- To access a mapping value:
```
if ( voted[msg.sender] ) { ... }
```
- To write to a mapping:
```
voted[msg.sender] = true;
```
## Mappings of mappings
- You can have mappings to mappings:
```
mapping (uint => mapping(string => address) )
public twodmap;
```
- It's just like a 2-dimensional array:
```
twodmap[3]["foo"]
```
## Mapping keys
- The keys are actually the *hash* of the key you provide
- If you provide the character `1` as the key, the actual key is the Keccak256 hash of that
- Or 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cd cb4c672f298b8bc6
- In every mapping, *all* $2^{256}$ keys exist
- Anything not explicitly set returns 0 / false / all zero's
- All mappings thus have size $2^{256} \approx 1.15 \ast 10^{77}$
- You can delete an element from a mapping:
- `delete map[1];`
- This really just sets the value to 0
- And it *restores* gas (since it's shrinking the EVM state)
## Is an element in a mapping?
- Consider:
```
mapping (address => bool) public override voted;
// this next one was not in the original Poll.sol:
mapping (address => uint) public how_voted;
// or:
mapping (uint => Choice) internal _choices;
uint public override num_choices;
```
- The `voters` tells if an address has voted
- If they haven't, then that key's value will be 0 (false)
- The `how_voted` will tell what they voted for
- For the Choices, the uint tells how many keys there are
- Our code has keys 0 to num_choies-1
## Structs
- Like a class without methods
```
struct Choice {
uint id;
string name;
uint votes;
}
```
- Structs can contain mappings as well
- They are often kept in a mapping:
```
mapping (uint => Choice) internal _choices;
```
- If you put the same `Choice` struct into different mappings, you *might* now have *two* copies of that struct!
## Time
- All time is kept as a UNIX timestamp
- The number of seconds since January 1st, 1970
- This is how it's kept in the blockchain as well
- Only time available in a contract is the timestamp of the block
- Via `block.timestamp`
- Can use `seconds`, `minutes`, `hours`, `days`, and `weeks` as time units
- They are always pluralized
- But the number before each must be a literal, not a variable!
- Example on the next slide
## Time units example
```
uint a = 1;
uint b = 5;
uint c = 2;
// valid:
uint endTime = block.timestamp +
1 seconds + 5 minutes + 2 days;
// not valid:
uint endTime = block.timestamp +
a seconds + b minutes + c days;
// valid:
uint endTime = block.timestamp +
a * 1 seconds + b * 1 minutes + c * 1 days;
```
## Ether units
- Can convert ether units as well
- All convert to wei (recall that 1 ether is $10^{18}$ wei)
```
assert(1 wei == 1);
assert(1 gwei == 1e9);
assert(1 ether == 1e18);
```
## Reference types
- Reference types are: strings, arrays, mappings, and structs
- Like Java and Python, the language often hides that it's a reference
## Memory locations
- All reference types must specify a memory location
- `storage`: for all state variables, it is stored on the blockchain
- statically allocated, like the stack on x86
- two sub-types:
- local storage (local subroutine variable)
- state storage (state/class variable on the blockchain)
- `memory`: a local variable, it only exists while the subroutine is executing
- dynamically allocated, like the heap in x86
- `calldata`: read-only, used for function parameters
## Assignments of references
- If you assign one reference type to another, what happens depends on where the data is stored:
| To (lhs) | From (rhs) | Result |
|--|--|--|
| memory | memory | reference aliasing |
| memory | any storage | full copy |
| memory | calldata | full copy |
| any storage | memory | full copy |
| any storage | calldata | full copy |
| local storage | any storage | reference aliasing |
| state storage | any storage | full copy |
| calldata | (any) | not allowed |
## Assignments of references
- How to remember:
- You can't ever write to `calldata`
- Anything assigned between *different* types of memory is always a copy, as references can't point from one memory type to another
- State storage, which is on the blockchain, never stores references -- so anything copied to state storage is always a full copy
- Reference aliasing works in the 2 cases when the memory types are the same and it's not going into state storage: memory to memory, and any storage to local storage
## Type names
- For certain types, you have to give a qualifier as to where it is stored
- `bytes` and `string`
- The qualifier is `memory`, `storage`, or `calldata`
- The type name is *two words*
- `string memory`
- `bytes storage`
## String functions
- No (direct) built-in string comparison!
- Reasons:
- It is difficult / expensive to compare across memory locations
- Instead, compare their hashes:
```
if ( keccak256(x) == keccak256(y) ) { ... }
```
- Note that `keccak256()` uses a lot of gas
- Can concatenate two strings:
```
string memory s = string.concat(s1, s2);
```
- Only returns a `string memory`
- There are 3rd party string function libraries
- Which contain comparisons, among other functions
<h2>Code Example</h2>
<pre class="code-wrapper"><code class="hljs d small" style="height:100%;">// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.9.0;
contract C {
// The data location of x is storage; this is the
// only place where the data location can be omitted
uint[] x;
// The data location of memoryArray is memory.
function f(uint[] memory memoryArray) public {
x = memoryArray; // works, copies the whole array to storage
uint[] storage y = x; // works, assigns a pointer, y's location is storage
y[7]; // fine, returns the 8th element
y.pop(); // fine, modifies x through y
delete x; // fine, clears the array, also modifies y
// The following doesn't work; it would need to create a new temporary /
// unnamed array in storage, but storage is "statically" allocated:
// y = memoryArray;
// This does not work either, since it would "reset" the pointer,
// but there is no sensible location it could point to.
// delete y;
g(x); // calls g, handing over a reference to x
h(x); // calls h and creates an independent, temporary copy in memory
}
function g(uint[] storage) internal pure {}
function h(uint[] memory) public pure {}
}
</code></pre>
## Even more...
- There are a lot of types we are skipping
- See them all in the [Solidity types reference](https://docs.soliditylang.org/en/latest/types.html)
- https://docs.soliditylang.org/en/latest/types.html
</textarea></section>
</section>
<!-- ============================================================ -->
<section>
<section id="concepts" data-markdown class="center"><textarea>
# Concepts
</textarea></section>
<section data-markdown data-separator="^\n\n\n"><textarea>
## Learning Solidity
- The easy part: learning the language
- It's just an OO language with familiar syntax
- The hard part is understanding:
- The restrictions that blockchain programs have
- No time or random numbers
- No print statements!
- How to best interact with the blockchain
- What the heck do you do with it?
- The easy part will be done in the next 20 minutes
- The hard part will be the rest of this course
## Sources
- The main reference is the [Solidity language documentation](https://docs.soliditylang.org/en/latest/index.html)
- URL: https://docs.soliditylang.org/en/latest/index.html
- [Ethereum developer resources](https://ethereum.org/en/developers/)
- URL: https://ethereum.org/en/developers/
- [Solidity reference](https://docs.soliditylang.org)
- URL: https://docs.soliditylang.org
- [Remix documentation](https://remix-ide.readthedocs.io/en/latest/) (the Solidity IDE)
- URL: https://remix-ide.readthedocs.io/en/latest/
## Solidity Overview
- An object-oriented language with C++/Java like syntax
- Same set of control structures with the same syntax (for, if/else, while, etc.)
- A class is called a "contract"
- Methods are called functions
## License identifier
- All Solidity smart contracts must have a license line as the first line
- SPDX is the [Software Package Development Exchange](https://spdx.org/licenses/)
- Examples:
```
// SPDX-License-Identifier: MIT
```
```
// SPDX-License-Identifier: CC BY-SA
```
```
// SPDX-License-Identifier: GPL
```
- A compiler will issue a warning if it's not there
- The actual license type is not checked, so you can also use:
```
// SPDX-License-Identifier: Unlicensed
```
## Pragma
- We'll only use the following Solidity version pragma:
```
pragma solidity ^0.8.24;
```
- The three numbers are: major version, minor version, bugfix version
- By default, it forces a compiler error if the wrong compiler version is being used
- Some platforms, such as Truffle or Remix, will try to find the right compiler version
- This will only compile with version 0.8.24 or later
- But will NOT allow compilation with version 0.9.0 or later
- Note that breaking changes (very few!) are only (intentionally) introduced on major versions
## Pragma
- More complicated examples are possible:
```
pragma solidity >=0.4.0 <0.6.0;
```
- One to avoid: note there is no carat before the version number
- Reason: a later bugfix version, 0.8.12, will not compile this program
```
pragma solidity 0.8.11;
```
- In this course, we'll use ONLY the following:
- As this will compile on all of the platforms we will be using
```
pragma solidity ^0.8.24;
```
## Comments
- C++ and Java style comments
```
// this is a comment
/* this is a
multi-line
comment
*/
/* this is a
* multi-line
* comment with better
* formatting
*/
```
## Import
- Default import statement:
```
import "./filename.sol";
```
- Note that this will pollute the namespace
- We can also use:
```
import * as symbolName from "./filename.sol";
```
- All names from the file can be accessed via `symbolName.thing`
- An equivalent version of this is:
```
import "./filename.sol" as symbolName;
```
- Naming collision? Then rename it upon import:
```
import {symbol1 as alias, symbol2} from "./filename.sol";
```
## High-level "things"
- `contract`
- Essentially an OO class
- Can also be `abstract`
- `interface`
- Just like interfaces in Java, or pure abstract classes in C++
- By convention, their names always start with a capital I (India)
- `library`
- Can contain ONLY functions that do not access state
- Meaning no contract field access
- Specifically, they can only contain `pure` functions (we'll see `pure` shortly)
- Unless you have a reason otherwise, have everything inside have `internal` visibility
- We'll see visibilities shortly...
## Inheritance
- Contracts can inherit from interfaces and other contracts
- Interfaces can inherit from (only) other interfaces
- Via the `is` keyword
- The super-class (or super-interface) must be defined above or `import`'ed
```
interface Foo is Bar {
// ...
}
```
```
contract Student is Person, Learner {
// ...
}
```
- Any contract that inherits from an interface, but does not implement all the methods, must be declared `abstract`
</textarea></section>
<section data-markdown data-separator="^\n\n\n" id='multioverride'><textarea>
## Inheritance
- `virtual`: if a *thing* (function, field, etc.) in a contract can be overridden
- All function prototypes in interfaces are assumed to be `virtual`
- `override`: when a sub-class is replacing an inherited function
- If the function is multiply inherited, you may have to specify which (or all) that it overrides (needed for the Tokens assignment):
```
function foo() public override(IERC165,ERC721) {
```
- The requirement to specify `override` varies by compiler and version
</textarea></section>
<section data-markdown data-separator="^\n\n\n" id='abscon'><textarea>
## Abstract Contracts
- A `contract` must have all the methods implemented
- An `interface` must have no methods implemented
- An `abstract contract` can have some methods implemented and some not
- Part interface, part contract
- Example: if you inherit from an interface, but only implement some of the methods
```
abstract contract Foo is Bar {
// ...
}
```
</textarea></section>
<section data-markdown data-separator="^\n\n\n"><textarea>
## What we have so far
```
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
interface IERC165 {
// ...
}
interface IERC721 is IERC165 {
// ...
}
contract ERC721 is IERC721 {
// ...
}
library Address {
// ...
}
```
## Visibilities
- `public`: like any other OO language, it can be called by anybody or anyone
- For fields, this is only the *readability* of the field; only contract functions can *write* to the field
- `private`: like any other OO language, it can be called only by code in that class
- `internal`: like `protected` in other OO languages: it can be called by that class or it's sub-classes
- `external`: like `public`, but can ONLY be called by code *outside* the contract; code in the contract can not call an `external` function
- Functions in interfaces must be declared `external`
- The implementing contract can then "raise" the visibility to `public`
</textarea></section>
<section data-markdown data-separator="^\n\n\n" id="getters"><textarea>
## Visibilities
- The stated visibility in an interface can be expanded (only) in the contract
- Example: if an interface specifies a function as `external`...
- Then the implementing contract can specify it either as `external` or `public`
- As `public` is *more* visible than `external`
- Anything field defined as `public` has a getter function defined for it -- see the next slide
- If you have `uint public k`, then you can call the `k()` getter function to access its value
- The default, if unspecified, is `public`
- But without a getter function
- Note that all data is still visible on the blockchain, even for `private` fields!
</textarea></section>
<section data-markdown data-separator="^\n\n\n"><textarea>
## Getter functions
- The following code:
```
uint public num_assignments;
mapping (address => string) public aliases;
mapping (uint => mapping(string => address) )
public twodmap;
```
- Creates the following getter functions:
```
function num_assignments() public view returns (uint);
function aliases(address a) public view
returns (string memory);
function twodmap(uint id, string s) public view
returns (address);
```
## Function Qualifiers
- `view`: this function does not *modify* the state of the contract
- It can read state variables, but not write to any state variables
- It can write to local variables, of course
- Like `const` in C++
- `pure`: this function does not *read or write* the state of the contract
- Any function in a `library` must be `pure`
- `view` and `pure` are mutually exclusive
- Using these qualifiers allows calls without having to make a transaction
- And *may* allow optimizations which reduce contract size and gas costs
## Declarations for fields
- Format:
```
<type> <visibility> <override?> <name> [= <value>];
```
- Examples:
```
uint public duration = 86400;
uint public override k;
address public override initiator;
mapping (address => uint) internal values;
```
- Local variables are similar
- But without the visibility and `override` qualifiers
## Declarations for functions
- Format:
```
function <name> ([<parameter_list>]) <visibility>
<qualifiers> [returns (<list>)] {
```
- Examples:
```
function addChoice (string memory _name) public
{ /* ... */ }
function unnecessaryFunction() public view
returns (string memory) { /* ... */ }
function overridePureFunction() external pure
override returns (uint,bool) { /* ... */ }
```
## Require and revert
- A reversion means the transaction method fails, and all state is rolled back to before it started
- Still costs gas fees!
- `revert()` will do this
- Also:
- `require(a>0);` will revert if $a$ is not greater than zero
- Better to use the two-parameter version:
- `require(a>0,"a must be greater than zero");`
- Now, if/when it reverts, it will tell you why
- Use this all the time!!!
## Receiving ether
- The `payable` qualifier means the function can accept ether as part of the call
- The amount of ether received is in `msg.value`
- And is added to the contract's balance
- ... assuming it doesn't revert
## Constructors
- Syntax:
```
constructor() {
// ...
}
```
- No `function` keyword, no return type
- Default, if not specified, is an empty body
- Can take parameters:
```
constructor(uint foo) {
// ...
}
```
- Only one constructor is allowed per class!
- They may eventually allow multiple, differentiated by the parameter list
## Destructor
- `selfdesctruct()`
- Only if enabled (declared)
- Disables the contract permanently
- Caller claims the ether balance
## Contract elements
- A contract can have:
- Fields
- Functions
- A constructor and a `selfdestruct()` method
- A few other special-purpose methods we won't see here
- Modifiers
## Modifiers
- A modifier changes how a function works
- You put in conditions (or whatever) and then indicate where the function body goes
- That indication is with the underscore
- Example:
```
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
```
## Modifiers
- This code adapted from [solidity-by-example.org](https://solidity-by-example.org/function-modifier/):
<pre class="code-wrapper"><code class="hljs d small" style="height:100%;"
>contract Modifiers {
address public owner;
constructor() {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
modifier validAddress(address _addr) {
require(_addr != address(0), "Not valid address");
_;
}
function changeOwner(address _newOwner) public onlyOwner
validAddress(_newOwner) {
owner = _newOwner;
}
}
</code></pre>
## Events & emit
- An *event* is when something happens
- Allows for logging of what has happened to a contract
- They are declared in contracts or interfaces:
```
event votedEvent (uint indexed _id);
event choiceAddedEvent (uint indexed _id);
```
- The `indexed` keyword allows for searching the event log by that value
- Events are called via `emit`:
```
emit choiceAddedEvent(num_choices);
emit votedEvent(_id);
```
- Events can be "watched" for (or "subscribed to")
- We'll see this later this semester
## Try-catch
- Try-catch:
```
try <something> {
// what to do if it succeeds
} catch {
// what to do if it fails (reverts)
}
```
- The "something" can be:
- Calling a function
- Creating a new contract
- Or anything else
- If the *something* reverts, the catch clause is executed
</textarea></section>
<section data-markdown data-separator="^\n\n\n" id='payeth'><textarea>
## Transferring ether in Solidity
- To transfer ether from a Solidity contract:
```
(bool success, ) = payable(a).call{value: v}("");
require(success, "Failed to transfer ETH");
```
- The amount, in `v`, is in wei
- The address to pay it to is in `a`
- This reverts if the contract does not have sufficient balance
- Or if it fails for any other reason, such as an invalid address
</textarea></section>
<section data-markdown data-separator="^\n\n\n"><textarea>
## Contracts creating contracts
- We can have a contract `Foo` deploy another contract `Bar`
- Given a field in Foo such as either:
```
Bar public b;
address public c;
```
- Then we can initialize it via either (respectively):
```
b = new Bar();
c = address(new Bar());
```
## Most useful global variables
From [here](https://docs.soliditylang.org/en/v0.8.12/units-and-global-variables.html)
- block.timestamp (uint)
- current block timestamp as seconds since unix epoch
- msg.sender (address)
- sender of the message (current call)
- msg.value (uint)
- number of wei sent with the message
- this
- the current contract (example: address(this).balance)
## Other global variables
- block.basefee (uint): current block's base fee
- block.chainid (uint): current chain id
- block.coinbase (address payable): current block miner's address
- block.difficulty (uint): current block difficulty