1 of 86

Introduction to

Smart Contracts

Slides and code partially from

Jason Weathersby, Algorand

With Examples on Algorand

Fabrice Benhamouda

2 of 86

Agenda

  • General overview of smart contracts
  • Deep dive in Algorand smart contracts:
    • Overview: storage and application call transactions
    • Send tokens out: escrow / inner transactions
    • Receive tokens: transaction groups / atomic transfer
    • Case study: crowdfunding
    • Deep dive on runtime architecture and TEAL/PyTeal (programming language)
    • Fees, min balance, cost, and other constraints
  • Quick comparison with Ethereum
  • Wallets for dApps and Demo of a real-world DApp
  • Advanced topics on Algorand

2

3 of 86

General Overview

of Smart Contracts

4 of 86

What is a Smart Contract

4

Smart Contract

In Development

Smart Contract

Blockchain State

Algorand

Blockchain

Deploy

  • Small Program that lives on the chain
  • Can interact with data on chain

Smart Contract

Smart Contract

5 of 86

Example of Use of Smart Contracts

  • DeFi Apps (decentralized finance)
    • Exchange / Automated Market Maker
    • Lending
  • Crowdfunding
  • Voting
  • Decentralized name services
  • Lottery*

5

6 of 86

What a Smart Contract Can Do?

  • Read & write data/state on the blockchain
    • E.g., votes, ownership of an asset, properties of an asset, DeFi exchange rate, …
  • Receive tokens from other accounts
    • E.g., receive tokens for a crowdfunding campaign
  • Send tokens it owns to another accounts
    • E.g., send the tokens to the project owner if the campaign is successful
  • Interact with other smart contracts
    • Reading data (e.g., result of a vote, on-chain price, oracle) or taking actions (e.g., voting, exchange of tokens)

6

7 of 86

What a Smart Contract Cannot Directly Do?

  • Interact directly with the outside world (and other blockchains)
    • ⛔ Directly access a website, weather, price EUR/USD, …
    • ⛔ Insurance smart contract that automatically reimburses customers after storm
      • Where does the info about storm/damage come from?
      • but: may be useful for transparency
    • but: oracles and bridges allow some interactions but require new components & trust

7

Smart Contract

Smart Contract

8 of 86

What a Smart Contract Cannot Directly Do?

  • ⛔ Work on any secret information
    • Everything a smart contract does is PUBLIC
    • Smart contract to store medical data
      • but: secrets on the blockchain may later provide such a solution
    • but: combined with zkSNARKs can provide transaction privacy

  • ⛔ Internal direct access to randomness
    • Smart contracts are deterministic
    • but: randomness oracles exist

8

Smart Contract

9 of 86

How to Interact with Smart Contracts?

9

Application Transaction

Deployment and Interaction

Transactions

Smart Contract

Blockchain State

Algorand

Blockchain

Smart Contract

Smart Contract

10 of 86

Algorand Smart Contracts

Overview: storage and transaction types

11 of 86

Accounts & Smart Contracts

  • Accounts (sometimes called “wallets”)
    • Basic accounts defined by signature public key
    • Hold token balances
    • Hold “local state” of smart contracts
    • Issue transactions: (for basic accounts, using secret key)
      • Transfer tokens
        • Only way tokens can leave the account
      • Call/deploy/update/delete/… smart contracts

11

Account address

=public key for basic accounts

PU3KOXQX5OGSUHEBWQTSVI47QZJSRX5RY3IJI3RNFDWCX5LJKBP5L43XAQ

Smart Contract

Application ID

=

68633014

  • Smart Contracts = Applications
    • Program living on chain
    • Accounts can send transactions to deploy/call/update/delete/… apps

(on Algorand)

= 25-word mnemonic:�

attract tourist harbor warfare employ harbor unfair code coach nest zero tool game blur heavy stock novel giggle quiz grunt note endless day abandon cage

12 of 86

Account

12

Address of the account

Transaction of the account

Balances of the account

Application call transaction

Transfer of asset USDC

Transfer of Algos

13 of 86

Application

13

Application ID

14 of 86

Don’t Get Confused

  • Stateless Smart Contracts
  • Contract accounts
  • Smart signatures
  • Delegated Logic Signature

14

At the end of the presentation only

Smart Contract

=

Application

15 of 86

Full Blockchain vs State

  • Full blockchain:
    • List of all blocks
    • Each block contains transactions
    • Very large:

15

State of the blockchain

can computed

from all the transactions

Transactions

Transaction 1

Transaction 2

Transaction 3

  • State of the Blockchain:
    • Database stored in each node
    • Much smaller than full ledger
    • Accounts ➤
      • Balance of tokens
      • Consensus keys
    • Applications ➤ state

16 of 86

Effect of a Transaction

16

Alice sends

2 Algos to Bob

State

Full Blockchain

Alice

NX2J4…

Bob

GVD7Z…

2 Algos

Address

Algo Balance

NX2J4…

20

GVD7Z…

7

Address

Algo Balance

NX2J4…

18

GVD7Z…

9

Before

After

(ignoring transaction fees and many more details)

State size = the same*

Blockchain size increased

*some operations increase the state size

17 of 86

Global State

Application can store data in

  • Global State:
    • Up to 64 key ➤ value pairs
    • (“key + value” at most 128 bytes)
    • ✅ Example of key ➤ value pair:
      • “tally_vote_yes” ➤ 120
      • “tally_vote_no” ➤ 250
      • “admin” ➤ C6G2TUQWZ7VIDVY5UUKBTNT4L7EY4V3NTABCZAEBSGSRD62QDWIQL76IXY

17

Local State

State

Application ID

Key

Value

68633014

tally_vote_yes

120

68633014

tally_vote_no

250

    • ⛔ Impossible to store in global state:
      • The list of all voters
      • The list of all the votes

18 of 86

Local and Global State

Application can store data in

  • Global State:
    • Up to 64 key ➤ value pairs
    • ✅ Examples:
      • “tally_vote_yes” ➤ 120
      • “tally_vote_no” ➤ 250
  • Local State:
    • Per account that “opts-in” �to the application �(special transaction)
    • Up to 16 key ➤ value pairs
    • ✅ Examples:
      • “registered_voter” ➤ 1
      • “vote” ➤ yes

18

Everything stored on chain in the state.

State

Application ID

Key

Value

68633014

tally_vote_yes

120

68633014

tally_vote_no

250

Account

Application ID

Key

Value

NX2J4…

68633014

registered_voter

1

NX2J4…

68633014

vote

yes

GVD7Z…

68633014

registered_voter

1

GVD7Z…

68633014

vote

no

19 of 86

Local and Global State: Access Restrictions

19

Even with secret key of U,

it is impossible to change the local storage of A for U,

without making an application call to A

Application A

Application B

Global state of A

Read/Write

Read only

Local state of A

for account U

Read/Write

even if transaction sender is not U

Read only

20 of 86

Some More Details

20

Application Transaction

Smart Contract

TEAL

Global State

Local State Account 1

Approval Program

Clear Program

TEAL

Generated, signed, sent using SDK

(Python, JS, Go, Java, …)

(Uses an algod endpoint)

Written in TEAL

Or generated by a PyTEAL

script (written in Python)

(No SDK, no algod endpoint)

21 of 86

Transaction Sub-Types for Application

21

Smart Contract

NoOp

TEAL

TEAL

Approval Program

Clear Program

OptIn

DeleteApplication

UpdateApplication

CloseOut

Clear

Used to Communicate With Smart Contract

Graceful clear

local storage

Force clear

local storage

Allocate

local storage

Default call

+ creation if AppID=0

22 of 86

Algorand Smart Contracts

Inner transactions / smart contracts as escrow

23 of 86

Application Account = Smart Contract Escrow

23

Application

Account

deploy/create

ASA

Smart Contract

control

transfer

creator

call

transaction

user/account

App ID

E.g, 68633014

Algorand Address

E.g, C6G2TUQWZ7VID…

24 of 86

Sending Tokens out of the Application Account

24

Application Transaction

Global State

Local State User 1

Local State User 1

Local State User 1

Local State User 1

Inner Transaction

Application

Account

Smart Contract

  • Normal account�⇒ transactions signed by secret key
  • Application account�⇒ transactions issued by smart contract as inner transaction

25 of 86

Summary of Smart Contracts / Applications

  • Read & write data/state on the blockchain
    • 👍 Using global and local state
    • Can also read balances of accounts
  • Receive tokens from other accounts
    • 👍 In their application account
  • Send tokens it owns to another accounts
    • 👍 Via inner transactions from their application account
  • Interact with other smart contracts
    • 👍 (v6) Via inner transactions application calls from their application account

25

How does the smart

contract knows it

received the tokens?

26 of 86

Algorand Smart Contracts

Understanding ASA, Group Transactions / Atomic Transfer

27 of 86

Algorand Standard

Assets ASA

  • Algo = native token
  • ASA = custom token
    • Anyone can create their own ASA
    • Same fee as Algos txs
    • Example: loyalty program, stable coin USDC
  • Equivalent on Ethereum:
    • ERC-20, ERC-721, ERC-1155
    • ASA pros: lower tx fees and no smart contracts

27

Create your token in one click on https://algodesk.io !

28 of 86

Atomic Transfers / Group Transactions

28

Alice

Bob

Atomic transfer:

Either all transactions succeed

Or all transactions fail

(work for up to 16 transactions)

ASA

1 Algo

20 USDC

Any transaction can be part of atomic transfer

Can include up to 16 transactions

29 of 86

Allow a Smart Contract to Receive Tokens

29

Alice

1 Algo

Application call

Application

Account

Smart Contract

Smart contract can inspect

the transactions in their atomic group.

(Note: smart contracts can only act when triggered by an application call transaction and cannot inspect transactions outside of their own group.)

30 of 86

Algorand Smart Contracts

Case Study: Crowdfunding

31 of 86

Crowdfunding

  • Like https://www.kickstarter.com but decentralized
  • A creator proposes a project with:
    • A fund goal to reach
    • An end date for funding
  • Donators can then fund the project
  • At the end:
    • If fund goal achieved: all the funds go to the creator = received address
    • If fund goal not achieved: users are reimbursed

31

32 of 86

Crowdfunding — Creation and Funding

32

Global State

Fund Start Date

Fund End Date

Fund Goal�Current Funding Received

Receiver Address

App transaction create

Sets dates, Fund goal, fund receiver and creator

Payment Tx

From Donator to Smart Contract Escrow

App transaction optin

before Fund end date

Atomic group

Local State

of each User

Giving Amount

1

2

Application

Account

Smart Contract

33 of 86

Crowdfunding — Payout / Reimbursement (after fund end)

33

Global State

Fund Start Date

Fund End Date

Fund Goal�Current Funding Received

Receiver Address

App transaction noop

Pay the project

if fund goal reached

App transaction noop

Reimburse user funds

if fund goal not reached

Local State

of each User

Giving Amount

3

4

Application

Account

Smart Contract

Payouts and reimbursements

made via Inner Transactions from

Application Accounts

If Current Funding Received >= Fund Goal

If Current Funding Received < Fund Goal

(transaction to be sent by each user)

34 of 86

Algorand Smart Contracts

Runtime Architecture and TEAL

35 of 86

Smart Contract Runtime Architecture

35

Smart Contract Runtime

Global

Variables

Transaction(s)

Properties

Read Only

Stack

TEAL Program(s), Loaded on Create Update

Application Array

Arguments Array

Per Transaction

Transaction Submission

Accounts Array

Temporary Scratch

Read/Write

Global/LocalState

Assets Array

36 of 86

TEAL — Transaction Execution Approval Language

  • Stack-based language
  • Turing Complete (if memory was infinite)
    • Looping and Subroutines
  • Return True (=1) or False (=0) (accept/reject)
  • Two types: uint64 / byte arrays []byte
  • Support for 512-bit integers as []byte
  • PyTEAL library to write in python

36

1000

5

hello

Stack

Push

= add on top

Pop

= remove the top

37 of 86

Simple Stack Example

37

int 5

int 1000

>=

1000

5

int 5

int 1000

>=

2

5

int 5

int 1000

>=

1

int 5

int 1000

>=

5

3

1000

0 (=false)

5 >= 1000

(true = 1)

https://developer.algorand.org/docs/get-details/dapps/avm/teal/opcodes/#_7

38 of 86

TEAL Basic Opcodes for State

38

“tally_vote_yes”

byte “tally_vote_yes”

app_global_get

120

State

Application ID

Key

Value

68633014

tally_vote_yes

120

39 of 86

TEAL Scratch Space

256 position of scratch space to store temporary values

39

40 of 86

State Demo

40

Every time called, increment a global counter

41 of 86

41

42 of 86

42

43 of 86

TEAL: Jumps and Loops

43

// loop 1 - 10

// init loop var

int 0

loop:

int 1

+

// implement loop code

// …

// check upper bound

int 10

<=

bnz loop

44 of 86

TEAL Opcodes and Pseudo-Opcodes (advanced)

  • Opcodes:
    • Converted directly to machine code or bytecode
    • Examples: >=, +, *, …
    • Reference document

  • Pseudo-Opcodes:
    • Converted to simpler opcodes
    • Examples: int, byte, addr, …
    • Reference document

44

>=

0x10

0x8105

pushint 5

int 5

intcblock 5

intc_0

0x200105…22

or

45 of 86

PyTeal — Python Library

45

def app():

handle_noop = Seq(

Assert(Txn.application_args[0] == Bytes("payme")),

InnerTxnBuilder.Begin(),

InnerTxnBuilder.SetFields({

TxnField.type_enum: TxnType.Payment,

TxnField.amount: Int(5000),

TxnField.receiver: Txn.sender()

}),

InnerTxnBuilder.Submit(),

Int(1)

)

return Cond(

[Txn.application_id() == Int(0), Approve()],

[Txn.on_completion() == OnComplete.NoOp, Return(handle_noop)]

)

if __name__ == '__main__':

print(compileTeal(app(), mode=Mode.Application, version=5))

#pragma version 5

txn ApplicationID

int 0

==

bnz main_l4

txn OnCompletion

int NoOp

==

bnz main_l3

err

main_l3:

txna ApplicationArgs 0

byte "payme"

==

assert

itxn_begin

int pay

itxn_field TypeEnum

int 5000

itxn_field Amount

txn Sender

itxn_field Receiver

itxn_submit

int 1

return

main_l4:

int 1

return

outputs

46 of 86

PyTeal Documentation

46

47 of 86

TEAL: Transaction Properties and Global Variables

  • global/Global: access to global parameters and group information
    • Example: size of the group, timestamp of latest block, …

  • txn/Txn: access to its own transaction fields
    • Example: Check Application Call subtype (txn OnCompletion / Txn.on_completion())

  • gtxn/Gtxn: access to transaction fields of another transaction in the group
    • Example: Check first transaction is a payment to the application account

47

48 of 86

Checking Type of Transaction

48

gtxn 0 TypeEnum

int pay

==

TEAL Program

Gtxn[0].type_enum() == TxnType.Payment

PyTEAL Program

Transaction 0 in the group

is a payment transaction

49 of 86

Application Transaction Sub-Types

49

txn OnCompletion

int NoOp

==

TEAL Program

Txn.on_completion() == OnComplete.NoOp

PyTEAL Program

Current application call is NoOp

50 of 86

Global Variables

50

50

global LatestTimestamp

int 1643691600

>=

TEAL Program

Global.latest_timestamp() >=

Int(1643691600)

PyTEAL Program

Previous round was after*

02/01/2022, 00:00 EST

Timestamp = 1643691600

* LatestTimestamp is best effort and may not be 100% accurate

51 of 86

TEAL: Checking Payment to Application Account

51

Payment of 2 Algos to

Application Account

Atomic

Application Call

**It is recommended not to enforce the atomic group size (as done in this simplified example) as it prevents “composition”. Instead look at previous transaction.

Seq([

Assert(Global.group_size() == Int(2)),

Assert(Gtxn[0].type_enum() == TxnType.Payment),

Assert(Gtxn[0].amount() == Int(2000000)),

Assert(Gtxn[0].receiver() == Global.current_application_address()),

])

PyTEAL Program

global GroupSize

int 2

==

assert

gtxn 0 TypeEnum

int pay

==

assert

TEAL Program

gtxn 0 Amount

int 2000000

==

assert

gtxn 0 Receiver

global CurrentApplicationAddress

==

assert

52 of 86

TEAL: Inner Transactions

  • Up to 16 inner transactions
  • From the application account
  • Shows up as inner transactions within application transaction
  • Recipient must be in the accounts array

  • Example: payment of 1.42 Algos to the application called

52

52

Seq([

InnerTxnBuilder.Begin(),

InnerTxnBuilder.SetFields({

TxnField.type_enum: TxnType.Payment,

TxnField.amount: Int(1420000),

TxnField.receiver: Txn.sender(),

}),

InnerTxnBuilder.Submit(),

])

PyTEAL Program

itxn_begin

int pay

itxn_field TypeEnum

int 1420000

itxn_field Amount

txn Sender

itxn_field Receiver

itxn_submit

TEAL Program

53 of 86

TEAL: Subroutines

  • Internal functions

  • Use:
    • Reduce code size
    • Improve code quality

  • Not visible from the outside
    • An application call cannot call �a subroutine directly

53

@Subroutine(TealType.uint64)

def isEvenSubRoutine(i):

return i % Int(2) == Int(0)

�Seq([

Assert(isEvenSubRoutine(Gtxn[0].amount())),

Assert(isEvenSubRoutine(Gtxn[1].amount())),

]

PyTEAL Program

gtxn 0 Amount

callsub sub0

assert

gtxn 1 Amount

callsub sub0

assert

TEAL Program

sub0: // isEvenSubRoutine

store 0

load 0

int 2

%

int 0

==

retsub

54 of 86

54

54

@Subroutine(TealType.uint64)

def isEvenSubRoutine(i):

return i % Int(2) == Int(0)

�Seq([

Assert(isEvenSubRoutine(Gtxn[0].amount())),

Assert(isEvenSubRoutine(Gtxn[1].amount())),

]

PyTEAL Program

gtxn 0 Amount

callsub sub0

assert

gtxn 1 Amount

callsub sub0

assert

TEAL Program

sub0: // isEvenSubRoutine

store 0

load 0

int 2

%

int 0

==

retsub

def isEvenPyFunc(i):

return i % Int(2) == Int(0)

�Seq([

Assert(isEvenPyFunc(Gtxn[0].amount())),

Assert(isEvenPyFunc(Gtxn[1].amount())),

]

PyTEAL Program

gtxn 0 Amount

int 2

%

int 0

==

assert

TEAL Program

gtxn 1 Amount

int 2

%

int 0

==

assert

Normal Python Function

Subroutine

The code is copy-pasted

for every invocation

55 of 86

TEAL: Application Arguments and “Methods”

  • Examples of methods:
    • Voting: register, vote. Crowdfunding: fund, withdraw, reimburse
  • CANNOT use subroutines
  • Use the “Application Arguments” array in the transaction call
    • Access as txna ApplicationArgs i or Txn.application_args[i]
  • Convention:
    • Currently: use the first argument (index 0) as method name
    • Very soon: follow the ABI�https://github.com/algorandfoundation/ARCs/blob/main/ARCs/arc-0004.md

55

How to specify which action/method to do in application call?

56 of 86

PyTEAL: Classic Skeleton for Smart Contract

56

def approval_program():

is_creator = Txn.sender() == Global.creator_address()

on_vote = Seq([...])� on_register …

� program = Cond(

[Txn.application_id() == Int(0), on_creation],

[Txn.on_completion() == OnComplete.DeleteApplication, Return(is_creator)],

[Txn.on_completion() == OnComplete.UpdateApplication, Return(is_creator)],

[Txn.on_completion() == OnComplete.CloseOut, on_closeout],

[Txn.on_completion() == OnComplete.OptIn, on_register],

[Txn.application_args[0] == Bytes("vote"), on_vote],

)

return program

if __name__ == "__main__":

with open("approval.teal", "w") as f:

compiled = compileTeal(approval_program(), mode=Mode.Application, version=5)

f.write(compiled)

Only the creator of the app can delete/update it

Logic for all the methods

When the ABI is finalized, the skeleton will change slightly.

57 of 86

Quick Summary

57

Application Transaction

(specifies Application Arguments)

Smart Contract

TEAL

Global State

Local State

“opted-in” Account 1

Approval Program

Clear Program

TEAL

Generated, signed, sent using SDK

(Python, JS, Go, Java, …)

(Uses an algod endpoint)

Written in TEAL

Or generated by a PyTeal

script (written in Python)

(No SDK, no algod endpoint)

Smart Contract = Application

= program living on the chain

Current Convention*

First argument = method called

* (pre-ABI)

Everything stored on chain in the state.

Application

Account

Control via inner transactions

58 of 86

PyTeal Simple

Escrow Demo

58

Every time method “payme” called (first argument),

send 2.1 Algo to the transaction sender

59 of 86

59

60 of 86

60

61 of 86

Algorand Smart Contracts

Fees, min balance, cost, and other constraints

62 of 86

Fee vs Minimum Balance

  • Fee:
    • At least 0.001 Algo per transaction (paid by sender)
    • Goal: Payment for recording transactions�prevents spamming of transactions
    • If congestion, at least fee_per_byte * transaction size

62

Use constants.min_txn_fee

Since Algorand currently support about 1,000 transactions per sec,

congestion is extremely rare

To empty an account, special “close remainder to” transaction.

  • Minimum balance: (of accounts)
    • Must be kept at all time / deposit
    • Deposit for using space in blockchain state (like locker)
    • Reimbursed when closing account/smart contract/ASA
    • 0.1 Algo at all time�+ 0.1 Algo per ASA created/opted-in�+ ** Algo per smart contract created/opted-in

63 of 86

TEAL: Cost and Constraints

  • Each opcode has a cost
    • Most opcodes cost = 1
  • Constraint: opcode budget
    • Cost at most 700 per call
    • (Can be pooled over transactions in a group)
  • Constraint: program size
    • 2k - 8k for total for approval and clear programs
  • Other constraints:
    • Up to 64 global state key/values, 16 local state key/values per account
    • “key+value” size at most 128 bytes
    • Up to 16 inner transactions
    • More, see Algorand Parameter Tables:�https://developer.algorand.org/docs/get-details/parameter_tables

63

64 of 86

Reach.sh — Alternative to PyTeal with guarantee safety properties

64

Same code targets �both Ethereum and Algorand

65 of 86

Comparison with Ethereum

Smart Contracts

66 of 86

Comparison with Ethereum (1/2)

66

Algorand

Ethereum

Smart contracts ≠ accounts

Smart contract is an account

Lang.

TEAL, PyTeal, Reach, …

Solidity, Reach, …

Fees

Independent of complexity of smart contract�Almost no congestion on Algorand

0.001 Algo per tx (<$0.002 in Feb 2022)

Gas fee depends on smart contract complexity�Gas price depends on congestion� More than $10 for ERC-20 in early Feb 2022

Storage

64 k/v global�16 k/v local per account�Deposit via min balance (reimbursable)

Unlimited global storage�Payment via gas fee (non-reimbursable)

Computation

Very constrained but sufficient

for most applications

Less constrained but expensive gas fee

67 of 86

Comparison with Ethereum (2/2)

67

Algorand

Ethereum

Receive native token

Atomic transfer�1. Payment�2. Application call

Part of application call transaction�(no need for extra transaction)

Custom�tokens

ASA �= similar to native token, same tx fee

ERC-20, ERC-721, ERC-1155 �= smart contracts, higher fee

Receive custom tokens

Same as receiving native token

Two-step process: (not easily atomic)�1. Approval of transfer from sender�2. Application call

Atomic transfer

Layer-1 feature

Requires writing a smart contract

68 of 86

DApps and Wallets

68

69 of 86

Decentralized Applications = DApp

Usually, two parts:

  • Smart contract:
    • On Algorand: written in TEAL, PyTeal, or Reach
    • On Ethereum: written in Solidity or Reach

  • Frontend:
    • Usually a webapp/website
    • Connect to the blockchain via a node/API service or through a full backend
    • Connect to the user wallet to issue transactions

69

Frontend cannot ask user’s secret key for security reasons

70 of 86

Wallets for DApps

  • Wallet that allows signing transactions generated by a DApp website:
    • Browser extension: AlgoSigner (Algorand), MetaMask (Ethereum), …
    • Website: MyAlgoWallet (Algorand), …
    • Connection to wallet application: WalletConnect (Algorand, Ethereum)

  • Keys kept by the user/wallet: the DApp never sees the key �(the DApp only sees the signed transaction)

70

  • Alternative: custodial wallets:
    • Another party (sometimes the DApp) keeps the key for the user
    • Example: Aikon ORE ID

User must check the transactions to be signed

(e.g., not moving all their tokens to a malicious party)

71 of 86

TinyMan Demo

71

72 of 86

72

73 of 86

73

74 of 86

74

75 of 86

75

76 of 86

76

77 of 86

77

78 of 86

78

79 of 86

Advanced Algorand Topics

79

80 of 86

Fee Pooling

  • Transaction can pay fees for other transaction in a group�including other inner transactions�
  • Example to simplify withdrawal of funds from application account:
    • Set inner transaction fee to 0 Algo
    • Increase the outer transaction fee by 0.001 Algo

  • (Inner transaction fees cannot be used to pay for top-level transaction fees to prevent spamming)

80

81 of 86

Account Types

  • Basic (ED25519) account
    • Address = signature public key
    • Transactions approved by signing them with secret key
  • Application account
    • Address ≈ hash of application ID
    • Transactions approved/issued by associated smart contract

81

  • Multi-signature account (t-out-of-n multisig)
    • Address ≈ hash of threshold t and n public keys pk[1], …, pk[n]
    • Transactions approved if at least t signatures with t of the associated secret keys
  • Smart signature contract account
    • Address ≈ hash of a TEAL program
    • Transactions approved if the TEAL program executed

82 of 86

Smart Signatures (former Stateless Smart Contracts)

  • Smart signature contract account uses:
    • Sending tokens in exchange �of another tokens

82

Alice

Bob

1 Algo

20 USDC

Albert

2 Algos

20 USDC

Alma

1 Algo

20 USDC

Signed by Albert

Signed by Alice

Signed by Alma

Signed by Bob

Signed by Bob

Signed by Bob

Smart signature!

1 Algo

83 of 86

Smart Signatures (former Stateless Smart Contracts)

  • Smart signature contract account uses:
    • Sending tokens in exchange of another tokens
      • Smart contracts can also be used but smart signatures are simpler
    • Advanced authorization structure:
      • Transactions approved if the CEO approves OR (both the COO and the CTO approve)
    • Allow free application call (pay transaction fee) to specific application
      • For users without accounts on Algorand / without Algos
    • Very complex operations (smart signatures allow for higher cost than smart contracts)
  • Smart signature delegated account (aka delegated logicsig)
    • A basic or multisig account can sign a TEAL program
    • Any transaction approved by the TEAL program can be sent on behalf of the account
    • Example of uses:
      • Delegate the ability to make low-value transactions to someone else

84 of 86

Rekeying

  • Change the address allowed to sign/authorize transactions�without changing the actual account address

  • After rekey an account has:
    • Same address
    • A different “authorized address”
    • (Warning: closing an account remove the rekeying.)

  • Uses:
    • Increase security: change from basic to multisig, change to more secure basic public key, …
    • Rekey to application account: give control of an existing account to a smart contract

84

85 of 86

Use New Accounts Local State to Extend Global State

  • To extend global state: 💡use local state of some fresh accounts
  • Issue: local state can be cleared at any time

85

2 solutions:

  • New accounts are rekeying to application account
    • Now only smart contract can clear
    • Additional advantage: create
  • New accounts are smart signature contract account
    • More complex
    • Useful if you want some unicity
    • Example 1 account = 1 pair of two currencies USDC/Algos, USDT/Algos, …

86 of 86

Resources

86

This presentation used resources from Flaticon.com