N-in-One token contract erc1151 development tutorial

Blockchain tutorial 2022-04-03 14:53:44 阅读数:402

n-in-one token contract erc1151 erc

ERC-1155 yes ERC-20 and ERC-721 Upgrade specification , It allows multiple different tokens to be sent in one transaction , It's like transferring RMB and US dollars at the same time .ERC-1155 Famous for its wide use in blockchain games , But it is also suitable for many other application scenarios . In this tutorial, we will learn ERC-1155 The main interfaces agreed in the specification , And make use of openzepplin Implement a for the aviation industry ERC-1155 Multiple tokens .

 Insert picture description here

Learn in a familiar language The etheric fang DApp Development Java | Php | Python | .Net / C# | Golang | Node.JS | Flutter / Dart

1、 What is? ERC-1155?

ERC-1155 The key function introduced is multi token support . Let's understand the importance of this through airline tokens .

Suppose we are in a world , Every airline has its own token . Now? , I'd like to book a round the world flight , There are three connecting flights from three different airlines . To pay for the ticket , I need to make three separate transactions , And use different tokens for each transaction .

Many things may go wrong in this process . If I'm on a flight 1 pay , Then I have booked a flight 2 What do I do ? Now? , I have to find a new connection . In the real world with concentrated money , This work is done by an online travel agency (OTA) Or a more traditional travel agency . however , In our example , A new smart contract must be created , The contract can execute all three transactions in a row , Deploy it , Then call the transaction function. . It's a little complicated to pay for just one flight , isn't it? ?

Fortunately, we can create a single multi token contract containing individual tokens of multiple Airlines , That's exactly what it is. ERC-1155 Actions we are allowed to perform . We can add any kind of token , Not just an airline token . Let's have a deeper understanding of ERC-1155 The function of .

2、ERC-1155 Functions and features

 Insert picture description here

  • Batch transfer : Multiple assets can be transferred in one call .
  • Batch balance : One call can get the balance of multiple assets .
  • Batch approval : Approve all tokens to one address .
  • EIP-165 Support : Declare supported interfaces .
  • Hook interface : Provide token acceptance hook interface .
  • NFT Support : If the supply is only 1, Consider it NFT.
  • Safe transfer rules : Rule set for secure transfer

3、ERC-1155 Batch transfer

Batch transfer and general ERC-20 Transfers are very similar . Let's look at the regular ERC-20 transferFrom function :

// ERC-20
function transferFrom(address from, address to, uint256 value) external returns (bool);

ERC-1155 The only difference is , We pass values as arrays , And also passed id Array . for example , Given _ids= [3,6,13] and _values= [100,200,5], Then the transfer result is :

  • take ID by 3 Of 100 A token from _from Transferred to the _to.
  • take ID by 6 Of 200 A token from _from Transferred to the _to.
  • take ID by 13 Of 5 A token from _from Transferred to the _to.

stay ERC-1155 There are only transferFrom, No, transfer. To make it look like ERC20 Use the same as transfer , Just put the from Set the address to the address where the function is called .

  • Why is it called “ Security ” -BatchTransferFrom? - Rules on safe transfer , See section below 7 section .
  • Why not return a Boolean value ?- Rollback when transaction fails , With what we discussed earlier SafeERC-20 Achieve the same .
  • What is a byte data field ?- It's like ERC-777 equally , You can pass in any data , This data will also be passed to the receiving hook .
// ERC-1155
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external;

4、ERC-1155 Batch query balance

stay ERC-1155 in , And ERC-20 balanceOf The corresponding call also supports batch query . As a reminder , This is a ERC-20 edition :

// ERC-20
function balanceOf(address owner) external view returns (uint256);

For balance query , It's even simpler , We can retrieve multiple balances in one call . Pass in owner array , Then pass in the token ID Array .

// ERC-1155
function balanceOfBatch( address[] calldata _owners, uint256[] calldata _ids ) external view returns (uint256[] memory);

for example , Given _ids = [3,6,13] and _owners = [0xbeef ...,0x1337 ...,0x1111 ...], The return value is :

[
balanceOf(0xbeef...),
balanceOf(0x1337...),
balanceOf(0x1111...)
]

5、ERC-1155 Volume licensing

Approval and authorization ERC-20 It's a little different . stay ERC1155 There is no need to set the authorized amount in , Just call setApprovalForAll Set the operator to approved or unapproved .

// ERC-1155
function setApprovalForAll( address _operator, bool _approved ) external;

You can call isApprovedForAll Method to read the current authorization status . As you can see , Is it all or all . You cannot define the number of tokens to approve , Nor can you specify which token to authorize .

// ERC-1155
function isApprovedForAll( address _owner, address _operator ) external view returns (bool);

This is intentional design , The purpose is to keep the use simple . You can only approve all the contents of one address . If more detailed control of specific approvals is required , Please check out EIP-1761.

6、EIP-165 Support

If you don't understand EIP-165 What is it? , Please check out This tutorial . In short , EIP165 It specifies how smart contracts declare the interfaces they support . for example , Does the smart contract support receiving ERC-1155 Tokens, ? If so , The corresponding supportsInterface Function must exist , And return for the contract true.

This brings us directly to the next concept : hook .

7、EIP-1155 Receiving hook for

With EIP-165 Support ,ERC-1155 Only the receiving hook of smart contract is supported . The hook function must return a predefined 4 byte magic value , The value is specified as :

bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))

When the receiving contract returns this value , Suppose the contract accepts the transfer and knows how to deal with ERC-1155 Tokens, , Then the contract will no longer have stuck tokens .

function onERC1155BatchReceived(
address _operator,
address _from,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external returns(bytes4);

8、ERC-1155 Non homogeneous token support

If the issue of the token is 1, So this token is essentially a non homogenous token (NFT). according to ERC-721 Standards for , Metadata you can define URL. The client can read and modify the URL, For details, see here .

9、ERC-1155 Secure transfer rules

In the previous description , We've talked about some safe transfer rules . however , Let's look at the most important rules :

  • The caller must be approved to consume this _from Token held at address , Otherwise, the caller must be _from.
  • When the following conditions occur , Transfer transaction must be rolled back :
    • _to The address is 0.
    • _ids And _values Different length
    • Token holder at _ids Any balance in is less than _values The corresponding amount sent to the recipient .
    • Any other errors have occurred .

Be careful : All batch functions, including hooks, also exist as versions without batch . This is done for the sake of improvement gas Efficiency considerations , It may still be the most common way to consider transferring only one asset . For the sake of simplicity , We omitted them . The same name , Just delete Batch The prefix is enough .

10、 be based on ERC-1155 Realization of airline token

We use well documented and audited Openzeppelin Based on contract Library ERC-1155 Airline tokens . adopt npm Install them or directly Remix Import Github URL. Can be in here see Openzeppelin ERC-1155 Documents .

Our previous airline example can be implemented in this way :

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
contract AirlineTokens is ERC1155 {
address public governance;
uint256 public airlineCount;
modifier onlyGovernance() {
require(msg.sender == governance, "only governance can call this");
_;
}
constructor(address governance_) public ERC1155("") {
governance = governance_;
airlineCount = 0;
}
function addNewAirline(uint256 initialSupply) external onlyGovernance {
airlineCount++;
uint256 airlineTokenClassId = airlineCount;
_mint(msg.sender, airlineTokenClassId, initialSupply, "");
}
}

This is what we need . Now you can call :

AirlineTokens.safeBatchTransferFrom(
myBuyerAddress, sellerAddress,
[airlineId1, airlineId2, airlineId3],
[firstFlightPrice, secondFlightPrice, thirdFlightPrice],
''
);

One transaction can pay the tokens of Airlines . great !


Link to the original text :ERC-1155 Analysis and practice of multiple tokens — Huizhi. Com

版权声明:本文为[Blockchain tutorial]所创,转载请带上原文链接,感谢。 https://netfreeman.com/2021/01/20210112010526981O.html