Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use OpenZeppelin to develop ERC20 on RSK

2025-03-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "how to use OpenZeppelin to develop ERC20 on RSK". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Create a contract

The first thing we need to do is to know how to use Truffle.

When we do this,

$truffle init

In an empty folder, in addition to creating a configuration file, we also created a folder for the project and migration contract to record changes to the same contract.

The .sol code file for the contract is located in

~ / Truffle/contracts

The migration script is in

~ / Truffle/migrations

Compiled contracts are available in the

~ / Truffle/build

The test contract is in

~ / Truffle/test

We are only dealing with the first two folders now.

In the Truffle folder, we import the library from OpenZeppelin

$npm install-E openzeppelin-solidity

These libraries will install not only the main libraries of our token token, but also libraries related to ownership, secure math operations, and many other facilities. It is worth mentioning that these libraries have been audited for high standards of security, so contracts that rely on them are not vulnerable to hackers when used correctly.

Our library will be installed in the

~ / Truffle/node_modules/openzeppelin-solidity/contracts

After that, we can import the library ABCD.sol into our contract, as follows:

Import 'zeppelin-solidity/contracts/token/ERC20/ABCD.sol'

To create our ERC20 tokens, we will import two libraries from this repository: StandardToken.sol, which has the main functions of tokens, and has imported more libraries, such as SafeMath.sol;Ownable.sol, which allow us to set the owner's control over the functionality in the contract.

To inherit library properties and functions, we simply use the "is" keyword to define the contract as StandardToken and Ownable in this way:

Contract CoinFabrikToken is StandardToken, Ownable {}

After that, we have all the functionality in these libraries and import libraries.

Next, we define the name of the token as CoinFabrik, which is its symbol, 18 decimal places, for the precision of the token (a standard in Ethernet networks that makes it possible to use the Ethernet conversion function of web3) and set the initial supply of tokens to 1000, like this:

String public name = 'CoinFabrik';string public symbol =' CF';uint8 public decimals = 18X uint public INITIAL_SUPPLY = 1000

We will also create another string, a non-public variable independent of the token function, to show the use of the Ownable library property, which only allows the creator to interact with certain specified functions. We'll see later.

Now that our parameters are defined, it's time to assign them to the Token variable through the constructor. So far, the constructor has been defined as a function with the same name as the smart contract, but from now on, there will be a function called constructor (), which will replace the old method. If you call the constructor as before, the Solidity compiler will issue a warning.

INITIAL_SUPPLY multiplied by the power of decimal precision will be assigned to the totalSupply_: of the BasicToken contract

TotalSupply_ = INITIAL_SUPPLY * (10**uint (decimals))

And deposit them in the creator's account:

Balancesb [msg.sender] = totalSupply_

With this, we can use a simple and standard token, but as we said, we will use the Ownable contract to add some functionality. First, we will define some functions: one that modifies the state of our non-public variables, but only you have permissions, and the other function returns a string message. The definition is as follows:

Function setON (string _ n) public onlyOwner returns (bool) {Owner = _ n; return true;} function getON () public view returns (string) {return Owner;}

Both are public, so anyone can try to call them, but for the first, only the owner's address does not cause a restore. If you are the owner and call the function, the string will be saved in our variable Owner (with uppercase letters), and it will also return a true value that we can check in the transaction.

Since the Owner variable is not public and there is no Getter, we need a function to return the value of the variable without changing the state of the blockchain. This is the second function.

We will also create a callback function that will issue an event if someone mistakenly calls our contract:

Function () public payable {if (msg.value > 0) {emit Yes ('Thanks for donating SBTC!:)';} else {emit No ('Error 404: Function not found: P');}}

Finally, we added a destructible function to the contract, where the owner is the only one who can execute it.

Our simple token has been completed. All the code should be the same:

Pragma solidity ^ 0.4.17; import 'zeppelin-solidity/contracts/token/ERC20/StandardToken.sol';import "zeppelin-solidity/contracts/ownership/Ownable.sol"; contract CoinFabrikToken is StandardToken, Ownable {string public name =' CoinFabrik'; string public symbol = 'CF'; uint8 public decimals = 18; uint public INITIAL_SUPPLY = 1000; string Owner; event Yes (string); event No (string); constructor () public {totalSupply_ = INITIAL_SUPPLY * (10**uint (decimals)) Balances [msg.sender] = totalSupply_;} function setON (string _ n) public onlyOwner returns (bool) {Owner = _ n; return true;} function getON () public view returns (string) {return Owner;} function () public payable {if (msg.value > 0) {emit Yes ('Thanks for donating SBTC!:)');} else {emit No ('Error 404: Function not found: P') }} function destroy () public onlyOwner {selfdestruct (owner);}} create a migration

For each contract, we need to tell Truffle which contract is the one we want to deploy and where we can find it. This is done through the migration file in the / Truffle/migrations folder.

The migration script 02 _ deploy_token.js should look like this

Var CoinFabrikToken = artifacts.require (". / CoinFabrikToken.sol"); module.exports = function (deployer) {deployer.deploy (CoinFabrikToken);}

We have configured Truffle, our nodes have synchronized, our contract has been written and our migration has been configured, it is a matter of time to complete the deployment.

Deployment

If we stopped our node before, we will come back online, and then we will connect to Truffle:

$sudo service rsk start$ cd ~ / Truffle/ & & truffle console-- network rsk

Then compile the contract:

Truffle (rsk) > compile-- all

There should not be any mistakes or warnings about our contract. Then we transfer the contract:

Truffle (rsk) > migrate-- reset

To save time, we can execute two commands on one line

Truffle (rsk) > migrate-all-reset

The migration contract will be deployed first. Truffle provides us with a transaction hash for each operation, so we can check the details or logs later. This is the full output I received.

Truffle (rsk) > migrate-- all-- resetCompiling. / contracts/CoinFabrikToken.sol...Compiling. / contracts/Migrations.sol...Compiling zeppelin-solidity/contracts/math/SafeMath.sol...Compiling zeppelin-solidity/contracts/ownership/Ownable.sol...Compiling zeppelin-solidity/contracts/token/ERC20/BasicToken.sol...Compiling zeppelin-solidity/contracts/token/ERC20/ERC20.sol...Compiling zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol...Compiling zeppelin-solidity/contracts / token/ERC20/StandardToken.sol...Writing artifacts to. / build/contracts Using network 'rsk'. Running migration: 1_initial_migration.js Deploying Migrations... ... 0xf00d4ecf2b5752022384f7609fe991aa72dda00a0167a974e8c69864844ae270 Migrations: 0x1dc2550023bc8858a7e5521292356a3d42cdcbe9Saving successful migration to network... ... 0x3e759e8ff8a7b8e47a441481fa5573ccf502b83f3d591ad3047e622af0f9169eSaving artifacts...Running migration: 2_deploy_token.js Deploying CoinFabrikToken... ... 0x300c8bb1e434e2aa4b13dcc76087d42fcbe0cb953989ca53a336c59298716433 CoinFabrikToken: 0xc341678c01bcffa4f7362b2fceb23fbfd33373eaSaving successful migration to network... ... 0x71771f7ee5d4e251e386979122bdda8728fa519d95a054572751bb10d40eb8c5Saving artifacts...

If we check the transaction, we can calculate the gas cost for all deployment processes. In my case, it is 2340788gas (277462 / 42008 / 1994310 / 27008).

So change it to a real SBTC, and we get 23407881830000000 / 10 ^ 18 = 0men000428364 SBTC. At the time of this writing, this was about $4.

Our contract is now deployed in 0xc341678c01bcffa4f7362b2fceb23fbfd33373ea.

Congratulations!

Interact with the contract

With the address given by the Truffle migration, and the ABI of the contract, we created an instance, so the simplified syntax makes it easier to handle the function. To this end, after we deployed, we wrote

Truffle (rsk) > var cfToken = web3.eth.contract (CoinFabrikToken.abi) .at (CoinFabrikToken.address)

If the contract is deployed and we know its address and ABI, we can do it.

Truffle (rsk) > var cfToken = web3.eth.contract ('Contract_ABI'). At (' Contract_ADDRESS')

Where Contract_ABI is simplified to one line ABI,Contract_ADDRESS does not need to be explained.

I created two accounts before, and now we rename them for convenience:

Truffle (rsk) > var acc0 = web3.eth.accounts [0] truffle (rsk) > var acc1 = web3.eth.accounts [1]

Acc0 is the person who deploys the contract. Acc0 is added to the truffle.js and node.conf configuration files.

Ownership control

We will first use the libraries we discussed to test the ownership functionality of the contract.

If we call the getON function from any account, as long as it is public and there are no ownership issues, we get:

Truffle (rsk) > cfToken.getON ()'

The setON function now has an ownership attribute. Any transactions from other accounts will be rejected. For example, we see that trying to sign a contract from acc1 in my name does not change its value.

Truffle (rsk) > cfToken.setON ('Andres Bachfischer', {from: acc1}) 0x5f115190b60238240bedf36d1c5bb69a443a0f8ee971b0fc40fe5ca9c727d47c

Using the hash of the transaction, we see that the returned value is false and the function is not executed correctly. When we call the getON function again, we see that the variable does not change its value.

Now sign the same transaction but from the owner's account acc0, we get the status' 0x01 'and the function executes correctly.

Truffle (rsk) > cfToken.setON ('Andres Bachfischer', {from: acc0}) 0x0c894fa7e5369573fb14addeaed4cd9d5b6cd1425cb4eeeae16cb4e1fa8e0364

When we call the function getON again, we see that the ownership libraries work as we want them to.

Truffle (rsk) > cfToken.getON ()

Ownable.sol also has a feature that allows us to change the contract owner to a different address. We won't use it. However, its usage is as follows:

Truffle (rsk) > cfToken.transferOwnership (acc1, {from: acc0})

With this, acc1 will become the new owner of the contract.

Let's switch to tokens.

Token operation

The first thing we need to do is to check that the balance of the token was allocated correctly when the contract was created.

We check the balance of each account as follows:

Web3.fromWei (cfToken.balanceOf (acc0). ToString (10)) / / = '1000'web3.fromWei (cfToken.balanceOf (acc1). ToString (10)) / / =' 0'

Therefore, we can see that all tokens have been correctly allocated to our initial account.

The first transaction we need to do is to transfer some tokens to the second account, acc1, for three times.

Do this for the first deal:

Truffle (rsk) > cfToken.transfer (acc1, web3.toWei, {from: acc0}) 0xd45437b777f1430e7cec57bd80b261ce8f87bf8a3f9a113fecd20563403c4d9c

Truffle (rsk) > web3.fromWei (cfToken.balanceOf (acc0). ToString (10)) / / = '733.6'truffle (rsk) > web3.fromWei (cfToken.balanceOf (acc1). ToString (10)) / / =' 266.4'

We see that the number of tokens obtained from our deployment account is the same as that received in acc1.

Using the StandardToken contract, we also gain permission to spend tokens on behalf of an account (in this case, acc1). If we want to do this before approval is obtained, the deal will fail (status is "0x00")

Truffle (rsk) > cfToken.transferFrom (acc1, acc0, web3.toWei (5), {from: acc0}) 0x5cee7cf60849283a0088d71483a606ba2101b500e13f972abada4f75781596bf

After checking, acc0 does not allow sending from acc1:

Truffle (rsk) > web3.fromWei (cfToken.allowance (acc1, acc0, {from: acc0}) .toString (10) / / ='0'

We authorize acc0 to spend 10 tokens in the name of acc1 from acc1 transactions:

Truffle (rsk) > cfToken.approve (acc0, web3.toWei (10), {from: acc1}) 0x6e1a202f4ca7f43dfb28034952d54a572993b986a55857790aa51854afbc1fb4

In the output log, we see that the function has completed successfully, and the log shows the amount that acc0 is allowed to spend. Check allowance:

Truffle (rsk) > web3.fromWei (cfToken.allowance (acc1, acc0, {from: acc0}) .toString (10) / / = '10'

Now, if we execute the expense transaction again:

Truffle (rsk) > cfToken.transferFrom (acc1, acc0, web3.toWei (5), {from: acc0}) 0x41f750eabb6e0d3ab576aac0333b0d337ca61808aae1eeafa9d8e2a0b81b979b

We got a successful deal with a status of "0x01".

Check the balance again:

Truffle (rsk) > web3.fromWei (cfToken.balanceOf (acc0). ToString (10)) / / = '738.6'truffle (rsk) > web3.fromWei (cfToken.balanceOf (acc1). ToString (10)) / / =' 261.4'

Finally, if we sign a transaction that calls an unavailable function, we will call our fallback function. Sign a deal like this:

Truffle (rsk) > web3.eth.sendTransaction ({from: acc0, to: cfToken.address}) 0x4106a287fc60669bf9682a73ec4c457b094c086ec7408a5dea95d200688c4ee9

A log is returned with data representing the string Error 404:Function not found:P (hexadecimal: '0x00... 00204572726f72203430343a2046756e6374696f6e206e6f7420666f756e64203a50').

Our last function, which we will not perform for obvious reasons, is to destroy the function. We need the contract not to be destroyed to show the deal. To call, the owner should do this:

Truffle (rsk) > cfToken.destroy ({from: acc0}) conclusion

In the second part of the walkthrough, I showed an example of developing a simple smart contract in a RSK network. We have seen:

Import libraries and contracts from OpenZeppelin Suite

Use these libraries to create a simple token

Configure the migration process for Truffle

Deploy our contract to the RSK main network

Interact with contracts through different accounts

Check the log of the block for feedback on the transaction.

As we have seen, the use of the RSK network for Solidity Smart Contracts deployment and interaction is almost the same as in the Ethernet Fong node. Of course, this is still a test network, and problems and errors are expected, mainly in the nodes, but the RSK Labs team solves them as quickly as possible when they show up. Over time, robustness will be achieved.

This is the end of "how to use OpenZeppelin for ERC20 development on RSK". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report