erc20 open zeppelin что это

ERC 20

This set of interfaces, contracts, and utilities are all related to the ERC20 Token Standard.

For an overview of ERC20 tokens and a walkthrough on how to create a token contract read our ERC20 guide.

There a few core contracts that implement the behavior specified in the EIP:

IERC20 : the interface all ERC20 implementations should conform to

ERC20 : the base implementation of the ERC20 interface

Additionally there are multiple custom extensions, including:

designation of addresses that can create token supply ( ERC20Mintable ), with an optional maximum cap ( ERC20Capped )

destruction of own tokens ( ERC20Burnable )

designation of addresses that can pause token operations for all users ( ERC20Pausable ).

Finally, there are some utilities to interact with ERC20 contracts in various ways.

SafeERC20 is a wrapper around the interface that eliminates the need to handle boolean return values.

TokenTimelock can hold tokens for a beneficiary until a specified time.

This page is incomplete. We’re working to improve it for the next release. Stay tuned!

IERC20

totalSupply () → uint256 external

Returns the amount of tokens in existence.

balanceOf (address account) → uint256 external

transfer (address recipient, uint256 amount) → bool external

Returns a boolean value indicating whether the operation succeeded.

allowance (address owner, address spender) → uint256 external

This value changes when approve or transferFrom are called.

approve (address spender, uint256 amount) → bool external

Sets amount as the allowance of spender over the caller’s tokens.

Returns a boolean value indicating whether the operation succeeded.

Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender’s allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729

transferFrom (address sender, address recipient, uint256 amount) → bool external

Moves amount tokens from sender to recipient using the allowance mechanism. amount is then deducted from the caller’s allowance.

Returns a boolean value indicating whether the operation succeeded.

Transfer (address from, address to, uint256 value) event

Emitted when value tokens are moved from one account ( from ) to another ( to ).

Note that value may be zero.

Approval (address owner, address spender, uint256 value) event

ERC20

Implementation of the IERC20 interface.

We have followed general OpenZeppelin guidelines: functions revert instead of returning false on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications.

Источник

Что такое токены ERC-20?

Что такое токены ERC-20?

Что означает аббревиатура ERC-20?

ERC (Ethereum Request for Comments) — это официальный протокол для внесения предложений по улучшению сети Ethereum; 20 – уникальный идентификационный номер предложения. Технические спецификации для токенов, выпускаемых на блокчейне Ethereum, были опубликованы в 2015 году. Токены, отвечающие этим спецификациям, известны как токены стандарта ERC-20 и фактически являются смарт-контрактами на блокчейне Ethereum. Несмотря на то, что токены ERC-20 функционируют в пределах фреймворка, установленного командой Ethereum, этот фреймворк достаточно широк, обеспечивая разработчикам большую гибкость при их создании.

Стандарт ERC-20 определяет набор правил, которые должны быть соблюдены для того, чтобы токен был принят и имел возможность взаимодействовать с другими токенами в сети. Сами токены представляют собой блокчейн-активы, которые могут иметь ценность, а также могут быть отправлены и получены как любая другая криптовалюта.

Чем была вызвана необходимость создания стандарта ERC-20?

Чем токены ERC-20 отличаются от традиционных криптовалют?

Отличие токенов ERC-20 от других известных криптовалют, например, биткоина или Litecoin, в том, что они привязаны к сети Ethereum, используют принятый внутри этой сети формат адресов и отправляются при помощи Ethereum-транзакций. Соответственно, транзакции с участием токенов ERC-20 можно прослеживать в обозревателе блоков.

На первый взгляд, такая транзакция может выглядеть пустой, поскольку в поле ‘Value’ указан ноль, однако количество отправленных токенов (в данном случае — OmiseGo) можно увидеть в отдельном поле.

Важно понимать, что токены ERC-20 не являются полностью независимыми – как было сказано выше, в их основе лежит блокчейн Ethereum, на распределенные вычислительные способности которого они и полагаются в своей работе.

Для чего нужны токены ERC-20?

Сценарии использования токенов ERC-20 – самые различные. Например, они могут выступать как акции проекта, сертификаты, подтверждающие владение активами, очки в программах лояльности или как криптовалюта. Также возможны варианты, при которых токены ERC-20 одновременно выполняют несколько таких ролей.

Среди наиболее известных токенов ERC-20 можно называть: 0x, Aragon, Augur, Aeternity, Aion, Binance Coin, BAT, Bancor, Civic, Decentraland, Dentacoin, DigixDAO, Dragon, District0x, EOS, FirstBlood, Gnosis, Golem, Iconomi, Kin, KuCoin, Kyber, Melonport, Matchpool, Numeraire, OmiseGo, Po.et, Raiden, RChain, Ripio, SingularDTV, Status, Storj, TAAS, TenX, TTron, VeChain, Veritaseum, Viberate, WeTrust, Wings и iExec RLC.

Каковы основные характеристики протокола ERC-20?

Стандарт ERC-20 предусматривает шесть обязательных и три опциональных (но рекомендуемых) параметра для любого смарт-контракта.

Обязательные параметры включают в себя функцию totalSupply, которая отвечает за общую эмиссию токенов, обеспечивая невозможность создания новых токенов по достижении максимального числа.
Функция balance0f определяет изначальное количество токенов, приписанных к определенному адресу. Обычно, это адрес, принадлежащий организаторам ICO.

Читайте также:  lvm debian что это

Также стандарт описывает два метода перемещения токенов, необходимые для их распределения среди пользователей и возможности совершения транзакций. Так, функция transfer обеспечивает передачу токенов пользователю, который инвестировал в проект во время ICO; функция
transferFrom необходима для совершения транзакций между пользователями.

Кроме того, необходимы еще две функции для верификации двух предыдущих методов перемещения токенов. Функция approve служит для проверки того, что смарт-контракт, исходя из общей эмиссии, может осуществлять дистрибуцию токенов, в то время как функция allowance необходима для проверки того, на адресе имеется достаточный баланс для отправки токенов на другой адрес.

Среди опциональных параметров – определение максимального количества дробных цифр после запятой (для сравнения, биткоин имеет восемь таких цифр – 1.00000000 BTC), названия токена и его символа.

Набор этих параметров позволяет биржам и провайдерам кошельков создавать единую кодовую базу, взаимодействующую с любым смарт-контрактом ERC-20.

Есть ли риски при использовании токенов ERC-20?

Поскольку токены ERC-20 фактически являются смарт-контрактами, они, несмотря на всю свою эффективность, имеют определенные риски. Например, смарт-контракт не может быть изменен после того, как его инициировали организаторы ICO, также в нем могут оказаться баги и уязвимости, которые могут привести к потере средств.

История Ethereum знает немало подобных инцидентов — одним из наиболее известных примеров стал взлом The DAO в 2016 году. Для устранения его последствий и возврата средств в сети был проведен хардфорк, в результате которого новая цепь продолжила существование под названием Ethereum, а противники такого решения сохранили старую цепь, объявив о создании Ethereum Classic.

Какие другие проблемы могут возникнуть с токенами ERC-20?

Следует отметить, что протокол ERC-20 не всегда оказывается достаточным для целей, которые преследуются при создании токенов, и сам по себе не гарантирует, что токен будет полезным, ценным или функциональным.

Кроме того, одним из недостатков стандарта ERC-20 можно считать то, что он делает возможность создания токенов достаточно тривиальным делом на техническом уровне. Это позволяет многим проектам достаточно просто запустить ICO, что подтверждается и совокупным количеством токенов – по состоянию на 1 мая 2018 их существовало уже около 80 тысяч. Это ведет к обилию похожих друг на друга токенов, существенно затрудняя процесс их выбора инвесторами.

Источник

Creating ERC20 Supply

In this guide you will learn how to create an ERC20 token with a custom supply mechanism. We will showcase two idiomatic ways to use OpenZeppelin Contracts for this purpose that you will be able to apply to your smart contract development practice.

The standard interface implemented by tokens built on Ethereum is called ERC20, and Contracts includes a widely used implementation of it: the aptly named ERC20 contract. This contract, like the standard itself, is quite simple and bare-bones. In fact, if you try to deploy an instance of ERC20 as-is it will be quite literally useless…​ it will have no supply! What use is a token with no supply?

The way that supply is created is not defined in the ERC20 document. Every token is free to experiment with their own mechanisms, ranging from the most decentralized to the most centralized, from the most naive to the most researched, and more.

Fixed Supply

Let’s say we want a token with a fixed supply of 1000, initially allocated to the account that deploys the contract. If you’ve used Contracts v1, you may have written code like the following:

Encapsulating state like this makes it safer to extend contracts. For instance, in the first example we had to manually keep the totalSupply in sync with the modified balances, which is easy to forget. In fact, we omitted something else that is also easily forgotten: the Transfer event that is required by the standard, and which is relied on by some clients. The second example does not have this bug, because the internal _mint function takes care of it.

Rewarding Miners

The internal _mint function is the key building block that allows us to write ERC20 extensions that implement a supply mechanism.

As we can see, _mint makes it super easy to do this correctly.

Modularizing the Mechanism

This can be used for centralized minting, where an externally owned account (i.e. someone with a pair of cryptographic keys) decides how much supply to create and for whom. There are very legitimate use cases for this mechanism, such as traditional asset-backed stablecoins.

The accounts with the minter role don’t need to be externally owned, though, and can just as well be smart contracts that implement a trustless mechanism. We can in fact implement the same behavior as the previous section.

This contract, when initialized with an ERC20PresetMinterPauser instance, and granted the minter role for that contract, will result in exactly the same behavior implemented in the previous section. What is interesting about using ERC20PresetMinterPauser is that we can easily combine multiple supply mechanisms by assigning the role to multiple contracts, and moreover that we can do this dynamically.

Automating the Reward

So far our supply mechanisms were triggered manually, but ERC20 also allows us to extend the core functionality of the token through the _beforeTokenTransfer hook (see Using Hooks).

Читайте также:  при перечислении зарплаты какой код дохода указывать

Adding to the supply mechanism from previous sections, we can use this hook to mint a miner reward for every token transfer that is included in the blockchain.

Wrapping Up

Источник

Что такое токены ERC-20 и как их использовать

Токены ERC-20: что это?

Это универсальный протокол для создания новых токенов, которые соответствуют стандартам и является основой множества современных токенов. Основные характеристики:

Что означает аббревиатура ERC-20?

Ethereum Request for Comments — это протокол, позволяющий вносить предложения по улучшению сети Ethereum. Цифра 20 означает номер предложения, являясь уникальным идентификатором. Соответственно, токены ERC-20 — это все токены, соответствующие протоколу.

Какие еще существуют стандарты ERC?

Необходимо понимать, что кроме 20 протокола, существуют и другие, например:

Зачем нужен стандарт ERC-20?

Необходимость поддерживать растущее количество токенов стало времязатратным и трудным, поэтому был создан общий протокол для всех токенов, как решения этой проблемы.

Среди целей создания:

Протокол действительно упростил жизнь пользователям сети, решив сразу несколько задач:

Основные характеристики протокола

Итак, какие же правила объединились в стандарт, упростивший разработку новых токенов?

Определяющие факторы — это 6 обязательных и 3 опциональных параметра:

Чем токены ERC-20 отличаются от традиционных криптовалют?

Токены ERC-20, выпущенные на стандарте ERC-20 (блокчейн Ethereum) отличаются от криптовалют рядом характеристик:

Детально разницу между токенами и монетами мы рассматривали в этом материале:

ERC-20: список популярных токенов

Среди наиболее известных в списке выделим:

Каковы основные преимущества?

Преимущества понятны из целей создания. Перечислим их:

Недостатки

Токены ERC-20 имеют определенные риски: баги, уязвимости, невозможность вносить изменения после инициации. Известный пример — The DAO. Чтобы устранить последствия взлома и вернуть средства инвесторам в 2016 году, был произведен хардфорк, в результате которого появилась новая цепь Ethereum Classic.

Простота создания токенов дает возможность мошенникам создавать “фейковые” проекты и запускать ICO, которые зачастую исчезают после завершения приема инвестиций.

Значительный минус также — токены можно ошибочно отправить на смарт-контракт другого ICO, что означает потерю средств, если смарт-контракт не предусматривает возможность принять эти токены.

Низкая пропускная способность — еще одна из проблем сети. Когда поднимается спрос на децентрализованные приложения (dapps), нагрузка на сеть Ethereum увеличивается, скорость ее работы уменьшается и стоимость транзакций становится выше. Дополнительных трудностей добавляет оплата комиссий сети в ETH для отправки токенов ERC-20.

Как использовать?

Базовый функционал похож на любую криптовалюту :

Токены стандарта ERC-20 применяются различными способами, например, могут выполнять роль “акций” проекта (секьюрити-токены), подтверждать владение активом, обеспечивать программу лояльности. Utility-токены подразумевают получение товара или услуги.

Кошелек для токенов ERC-20

Самый удобный криптокошелек для работы с токенами готов к использованию!

Чтобы добавить любой токен ERC-20 в Trustee Wallet, совершите следующие действия:

Подведем итоги

ERC-20 — это универсальный протокол для создания новых токенов, основные спецификации которых — взаимозаменяемость, переносимость и фиксированная эмиссия. Благодаря этому протоколу в сети Ethereum стало проще и быстрее добавлять, удалять и перемещать токены; больше не нужно писать новый код для создания нового токена, а размещение на крипто сервисах не требует дополнительных технических действий.

Источник

ERC 20

This set of interfaces, contracts, and utilities are all related to the ERC20 Token Standard.

For an overview of ERC20 tokens and a walk through on how to create a token contract read our ERC20 guide.

There a few core contracts that implement the behavior specified in the EIP:

IERC20 : the interface all ERC20 implementations should conform to.

Additionally there are multiple custom extensions, including:

ERC20Permit : gasless approval of tokens.

ERC20Snapshot : efficient storage of past token balances to be later queried at any point in time.

ERC20Burnable : destruction of own tokens.

ERC20Capped : enforcement of a cap to the total supply when minting tokens.

ERC20Pausable : ability to pause token transfers.

Finally, there are some utilities to interact with ERC20 contracts in various ways.

SafeERC20 : a wrapper around the interface that eliminates the need to handle boolean return values.

TokenTimelock : hold tokens for a beneficiary until a specified time.

The following related EIPs are in draft status and can be found in the drafts directory.

This core set of contracts is designed to be unopinionated, allowing developers to access the internal functions in ERC20 (such as _mint ) and expose them as external functions in the way they prefer. On the other hand, ERC20 Presets (such as ERC20PresetMinterPauser ) are designed using opinionated patterns to provide developers with ready to use, deployable contracts.

IERC20

Interface of the ERC20 standard as defined in the EIP.

totalSupply () → uint256 external

Returns the amount of tokens in existence.

balanceOf (address account) → uint256 external

transfer (address recipient, uint256 amount) → bool external

Returns a boolean value indicating whether the operation succeeded.

allowance (address owner, address spender) → uint256 external

This value changes when approve or transferFrom are called.

approve (address spender, uint256 amount) → bool external

Sets amount as the allowance of spender over the caller’s tokens.

Returns a boolean value indicating whether the operation succeeded.

Beware that changing an allowance with this method brings the risk that someone may use both the old and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this race condition is to first reduce the spender’s allowance to 0 and set the desired value afterwards: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
Читайте также:  что делать если star wars the force unleashed 2 вылетает после заставки на виндовс 10

transferFrom (address sender, address recipient, uint256 amount) → bool external

Moves amount tokens from sender to recipient using the allowance mechanism. amount is then deducted from the caller’s allowance.

Returns a boolean value indicating whether the operation succeeded.

Transfer (address from, address to, uint256 value) event

Emitted when value tokens are moved from one account ( from ) to another ( to ).

Note that value may be zero.

Approval (address owner, address spender, uint256 value) event

ERC20

Implementation of the IERC20 interface.

We have followed general OpenZeppelin guidelines: functions revert instead of returning false on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications.

constructor (string name_, string symbol_) public

All three of these values are immutable: they can only be set once during construction.

name () → string public

Returns the name of the token.

symbol () → string public

Returns the symbol of the token, usually a shorter version of the name.

decimals () → uint8 public

Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value ERC20 uses, unless _setupDecimals is called.

totalSupply () → uint256 public

balanceOf (address account) → uint256 public

transfer (address recipient, uint256 amount) → bool public

recipient cannot be the zero address.

allowance (address owner, address spender) → uint256 public

approve (address spender, uint256 amount) → bool public

spender cannot be the zero address.

transferFrom (address sender, address recipient, uint256 amount) → bool public

sender and recipient cannot be the zero address.

increaseAllowance (address spender, uint256 addedValue) → bool public

Atomically increases the allowance granted to spender by the caller.

Emits an Approval event indicating the updated allowance.

spender cannot be the zero address.

decreaseAllowance (address spender, uint256 subtractedValue) → bool public

Atomically decreases the allowance granted to spender by the caller.

Emits an Approval event indicating the updated allowance.

spender cannot be the zero address.

_transfer (address sender, address recipient, uint256 amount) internal

sender cannot be the zero address.

recipient cannot be the zero address.

_mint (address account, uint256 amount) internal

Emits a transfer event with from set to the zero address.

to cannot be the zero address.

_burn (address account, uint256 amount) internal

Emits a transfer event with to set to the zero address.

account cannot be the zero address.

account must have at least amount tokens.

_approve (address owner, address spender, uint256 amount) internal

Sets amount as the allowance of spender over the owner s tokens.

owner cannot be the zero address.

spender cannot be the zero address.

_setupDecimals (uint8 decimals_) internal

Sets decimals to a value other than the default one of 18.

This function should only be called from the constructor. Most applications that interact with token contracts will not expect decimals to ever change, and may work incorrectly if it does.

_beforeTokenTransfer (address from, address to, uint256 amount) internal

Hook that is called before any transfer of tokens. This includes minting and burning.

when to is zero, amount of from ‘s tokens will be burned.

from and to are never both zero.

To learn more about hooks, head to Using Hooks.

Extensions

ERC20Snapshot

This contract extends an ERC20 token with a snapshot mechanism. When a snapshot is created, the balances and total supply at the time are recorded for later access.

This can be used to safely create mechanisms based on token balances such as trustless dividends or weighted voting. In naive implementations it’s possible to perform a «double spend» attack by reusing the same balance from different accounts. By using snapshots to calculate dividends or voting power, those attacks no longer apply. It can also be used to create an efficient ERC20 forking mechanism.

Snapshots are created by the internal _snapshot function, which will emit the Snapshot event and return a snapshot id. To get the total supply at the time of a snapshot, call the function totalSupplyAt with the snapshot id. To get the balance of an account at the time of a snapshot, call the balanceOfAt function with the snapshot id and the account address.

Gas Costs

Snapshots are efficient. Snapshot creation is O(1). Retrieval of balances or total supply from a snapshot is O(log n) in the number of snapshots that have been created, although n for a specific account will generally be much smaller since identical balances in subsequent snapshots are stored as a single entry.

There is a constant overhead for normal ERC20 transfers due to the additional snapshot bookkeeping. This overhead is only significant for the first transfer that immediately follows a snapshot for a particular account. Subsequent transfers will have normal cost until the next snapshot, and so on.

Источник

Сказочный портал