preface

Recently with the star investment NFT project fire, a pile of “meta-universe” concept of marketing number began to make demon, side also have friends eager to try. It’s hard to convince, but I just want to illustrate the underlying nature of this type of Web3-based NFT project and the stack of technologies for blockchain application development through a minimalist version of an actual project.

The entire app will use Solidity to write smart contracts, Python for AI, and React for the front interface. There will be a lot of complexity involved in the process, so I will introduce it in several chapters. I hope I can clear my mind, as soon as possible to serialize the simple.

In the first article, I will be relaxed and happy. I will simply talk about my personal views on blockchain and send a coin to experience the process.

The nature of blockchain

The essence of a blockchain is a stack of ledgers strung together using asymmetric encryption. Yes, your intuition is right, it’s like a snapshot database with state in it, without a cloud server as a back end, a bit Serverless. The only difference is that it is decentralized and blocks are acknowledged by multiple nodes (upchain writes), so reads are fast and writes are slow.

It saves you the cost of renting a server, but every write on the chain costs gas, and you have to endure a long block validation process, so there is no free lunch. Efficiency, security and privacy are a set of contradictions. In reality, most scenarios have nearly perfect solutions in centralized programs. In fact, there are not many scenarios that really need blockchain.

It is useful only in the face of public trust or cross-domain cooperation.

  • Solving trust Issues

    Smart contracts pre-stipulate a set of rules and trigger conditions that, once in effect, can be invoked. Since the beginning was “solidified” in the chain, there is no need for a third party notarization to do the letter, which greatly dispels the source of all kinds of suspicion chain in reality.

    The cost of distrust is high, because you need to double-check before you do anything (coders can recall the percentage of actual working code in your program versus the percentage of troubleshooting code). And even when confirmed many times, people are always the biggest source of instability. (Even if the supply chain system of blockchain is “adulterated” at the human input stage, then the most reliable smart contract is only an accomplice in distorting history.)

    To “solidify” programs and data on a chain is to turn a test of human nature into a test of asymmetric encryption (mathematics) and a more manageable and quantifiable test of the “economics” that attack the entire ecosystem.

  • Natural historical record tracing

    Any operation once be credited on the chain, can not be modified on chain (as long as the good control of the problem of “dirty data”), and the subsequent data are real and effective, back the chain can restore the truth the whole truth, bring their own timestamp attribute (although this block mining time not very accurate, but generally not suitable for high frequency application block chain, At the very least, the precise time can be packaged as data and stored on the chain).

    Public welfare applications are particularly suitable for blockchain, such as public donations, public social services, public pension services, etc. Natural “public” accounts and records can give public welfare projects the greatest sense of trust.

  • “Sustainability” in exchange for community governance

    “Sustainability” is too important to pin the program on one person, one company or even one country, as with the recent events of Faker.js or Blizzard Fall. The popularity of the DAO reflects the fact that this is a typical blockchain application scenario, a mutually successful process.

  • Sliced metaverse

    Sub-chain has become the next consensus base, more side chains means lower transaction speed and lower transaction cost. I don’t want to talk about currency price here. After all, coinage is too sensitive, and I don’t understand economics. But you can think of tokens as proof of entitlement, proof of credit, game coupons, etc., like Q coins, ant points. If it has nothing to do with reality, it is not a meta-universe, which is a closed VR space. One of the values of blockchain is to make reality more diversified, to establish a bridge of communication among many split parallel universes and help serve reality.

  • Anonymous credit systems

    In fact, everyone should have their own tokens, such as credit points. Imagine going to the bank to get a loan and saying, “I’ll use my credit guarantee without any proof of consumption or real estate.” It’s like going to a restaurant with no money and asking for facial payment. If you can have credible data on the blockchain as a credit, it can not only sell privacy to the bank, but also give enough credible proof of assets.

    Just like in the open source world, we recognize the technology behind that Id, not a celebrity or authority. With tens of millions of Zhihu and hundreds of millions of Xiaohongshu per capita, it would be more credible to show the wallet address before Posting, which also does not violate privacy.

    Network red KOL and community organizations are also suitable to use tokens to feedback fans, mark workload, so that the flow of private domain has a better quantitative basis. In the era of meta-universe, both the consumer end can get infinite satisfaction in the virtual world, and the production end can make a pot full of real world, win-win!

    Similarly, the private key is the only proof of the blockchain. If you lose it, you will “really die”. It is not necessary to retrieve the account with real identity, which is the price of anonymity.

It is too difficult for ordinary developers to build basic mainchains, and private chains are not decentralized, have no credibility, and have high relative costs. In the long run, it is necessary for the blockchain ecosystem to take the lead in building the public chain of POS. The token is not directly connected to the main coin market, and there is no centralized exchange to avoid many financial risks.

So-called, a generation of leek belief ICO air currency value; The second generation of leek in the centralized exchange buying and selling contracts; The third generation of Chinese chive obtained substitute currency by pledging stable currency through DeFi; Fourth generation leek goes to NFT metaverse….

Well, understand, the above is just as a helpless pain AI developer, in those years of chaos, no graphics card no computing power available when the bitterness. Now, back to the implementation, let’s talk about the dry stuff.

Blockchain application

Apart from the basic public chain selection (or private chain construction), a complete blockchain application is generally divided into the following steps:

  • Tokens, casting
  • Contract writing
  • Compile the deployment
  • Chain on the debugging
  • The front-end calls

As a coder, we need to choose a more secure and reliable solution than a bunch of 3-minute alternatives on the Internet. Because in the case of blockchain, once deployed, it cannot be changed, meaning that all bugs are also hard to fix (just upgrade the version by migrating the whole to a new contract).

This is a bit like firmware burning in “embedded development”, where the ultimate application deployed on top of token security is at great financial risk in the future without any consideration for token security. Over the years, hackers have replaced coins in many projects.

Before you start writing a smart contract, you tend to put two constraints on yourself:

  • At all costs to reduce GAS costs, the harsh reality is that “without extreme optimization, end users will choose to copy”;
  • Do security checks at all times and be prepared to be attacked by hackers. The attacks are not just at the code level, but at various tests of traditional financial rules.

Based on the above ideas, we will first create our own ERC20 token, with a fixed issuance total of 21 million, and reserve a contract interface, which can wait to be triggered by other smart contracts.

  • Why ERC20

    ERC20 is a widely used token contract on the Ethernet chain that provides standardized token minting, transfer, and approval operations. As the most widely used contract, it is ideal for basic tokens.

  • Why is the fixed amount 21 million

    In fact, the number of fixed aggregate supply does not matter, it only marks a “total credit”. For reference in the future, benchmark against bitcoin with the same total circulation. The more you issue, the smaller the unit value, isn’t that counterintuitive, but it’s the same thing as currency inflation or deflation.

  • Why reserve a contract interface

    As the main contract, we do not want to introduce too many functions, and the specific business logic can be realized through the subsequent issuance of N sub-contracts.

The main contract

Remix is the best option for simple contracts. Go to our website

https://remix.ethereum.org/
Copy the code

Under the contracts directory, create a new file named maintoken.sol

Inherit the contract

It is based on the OpenZeppelin open source library, which has been honed by the community to minimize security risks.

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
Copy the code

Inherits the ERC20 base contract, Ownable checks contract ownership, and uses SafeERC20 to enhance security for transferring tokens using contracts.

contract MainToken is ERC20, Ownable { using SafeERC20 for IERC20; . }Copy the code

Casting tokens,

In the constructor, declare the token name, abbreviation, and total supply, with a default accuracy of 18 bits. Variables are reserved so that you can specify a specific name during deployment. The constructor is called only once at creation time, meaning that the token is mined in one go and is a fixed total token.

constructor(
	string memory _name,
	string memory _symbol,
	uint256 totalSupply
	) ERC20(_name, _symbol) {
	_mint(msg.sender, totalSupply);
}
Copy the code

Contract transfer interface

With SafeERC20 packaging, you are guaranteed to accept tokens from the sender only at the contract address. The sender can be a personal wallet or other contract. We use this interface here to “authorize” each sub-contract to use the token of the master contract for specific transactions.

function safeInteractWithToken(uint256 sendAmount) external {
	IERC20 token = IERC20(address(this));
	token.safeTransferFrom(msg.sender, address(this), sendAmount);
}
Copy the code

Withdrawal interface

The tokens received on the main contract are withdrawn to the wallet of the contract owner, completing the whole loop. Note that tokens are being withdrawn, not master coins.

function withdraw() external onlyOwner {
	_transfer(address(this), msg.sender, balanceOf(address(this)));
}
Copy the code

Sub contract

Configuration interface

Two functions on the main contract are configured as interfaces,

interface MainInterface {
  function safeInteractWithToken(uint256 sendAmount) external;
  function approve(address spender, uint256 amount) external returns (bool);
}
Copy the code

Binding master contract

Constructor accepts a contract address to complete the binding operation.

contract SubToken{ address private _mainAddress; MainInterface private _mainContract; constructor(address _slotAddress) { _mainAddress = _slotAddress; _mainContract = MainInterface(_slotAddress); }... }Copy the code

Submit tokens,

Approve the token on the sub-contract to the main contract first. SafeInteractWithToken then invokes the main contract to obtain the token and complete the transfer of the real token. Here is a simple example combined together. The function is similar to transfer method. In actual business, it will be called separately.

function transferWithToken(uint256 sendAmount) external {
	_mainContract.approve(_mainAddress, sendAmount);
	_mainContract.safeInteractWithToken(sendAmount);
}
Copy the code

We can call any deployed contract through a new subcontract, not necessarily written by ourselves. Serverless Cloud Function (SCF) is a Cloud Function in Serverless.

There can be many such sub-contracts. The NFT contract we will write later, NFTToken.sol, will be one of them.

After the main contract is deployed, fixed total tokens will be pre-mined for the contract owner; Then the contract owner transfers a certain amount of initial tokens to the sub-contract as project funds. The sub-contract uses the token of the main contract as the settlement tool for specific business; When the project ends or is suspended, the remaining tokens can be returned to the main contract; Finally, cash is withdrawn from the master contract to the wallet of the contract owner, completing the whole loop.

The basic architecture diagram is as follows:

Test the contract

Deployment master contract

Confirm the compiler version and select Automatic compilation. With optimization enabled, contract compilation is performed every time the code is saved.

We tested the deployment in virtual machine first, selected MainToken, filled in the token name bluishfish Coin, abbreviated BLF and the total supply 21000000 (note that the 18-bit precision value was ignored here, reducing the circulation). The main wallet address ACCOUNT can be copied first, which will be used in the subsequent transfer (contract owner’s wallet).

Click On Transact to deploy, and once the main contract is deployed, we can test the functionality using the command button below the contract. Yellow or red costs gas, blue is read-only and free.

That’s because whether a piece of data is written or changed, it’s permanently written to the blockchain.” Permanent “Ah! This data needs to be stored on hard drives at thousands of nodes around the world, and it costs money! Each call to change costs money, so in order to reduce user costs, you should avoid writing big data to the chain unless you have to.

Call the balanceOf function to fill in the address of the wallet copied before, and the number of tokens on the wallet can be queried, indicating that the main contract has been successfully deployed.

Deployment subcontract

The compilation of the subcontract is the same as before, but it is worth noting that we need to collect the contract address of the main contract as the deployment parameter to complete the binding.

After selecting the SubToken, copy the main contract address below, then fill in _SLOTADDRESS and click Transact Deploy.

Transfer to sub-contracts

Now that we have two deployed contracts in the virtual machine, we need to clarify the concept that the contract has its own address, and the deployer, as the owner of the contract, also has a master wallet address, which is independent of each other.

The main wallet address: 0 x5b38da6a701c568545dcfcb03fcb875f56beddc4

The main address: 0 xd9145cce52d386f254917e481eb44e9943f39138

The child address: 0 xd8b934580fce35a11b58c6d73adee468a2833fa8

Yours may be different, depending on the virtual machine assignment, and in production depending on the actual address assigned on the chain. After sorting out the relationship, you can see the corresponding screenshot.

When we deploy the master contract, the token is already in the master wallet. Therefore, 10,000 tokens will be used as the initial fund of the project and transferred from the master wallet to the sub-contract.

Copy the address of the subcontract, expand the main contract, call the Transfer method, fill in the address of the subcontract, the quantity is 10000, and click Transact to transfer.

Call the balanceOf function, fill in the sub-contract address, and check whether the token has arrived.

Transfer to the master contract

After completing all the business of the sub-contract, we can return its remaining tokens to the main contract.

For example, to call transferWithToken to return 5000 token to the main contract, it can be called several times. After the first two successful attempts, the third attempt will show insufficient balance and the transfer fails.

withdrawal

Back to the master contract, let’s check the balance of the master purse, 20.99 million.

Check the balance on the main contract. $10,000. Good. That means the previous subcontract has fully repaid the token.

Finally, the tokens from the master contract are withdrawn to the master wallet.

After we execute withdraw and check the balance of the main wallet, we will find it changed to 21 million again.

Chain on the deployment

Install wallet plug-in

The MetaMask plugin is recommended to be used with Chrome. If it is not convenient to download outside the wall, you can also obtain the offline installation package from the resources at the end of this article.

https://metamask.io/download.html
Copy the code

Once the wallet is installed, switch to Remix and select Injected Web3 to connect the wallet.

To choose a network, you need to hold the main coin of the network. Etheric chains are ETH, Polygon is MATIC. Everything on the chain that involves a “write” operation costs the main coin, which generally consists of two parts: storage and execution (GAS).

For deployment, fill in the value of TOTALSUPPLY followed by 18 zeros, or modify the master contract to add precision.

_mint(msg.sender, totalSupply*10**decimals());
Copy the code

Ropsten test network

The test network environment is almost identical to the main network and costs nothing, so it is recommended to do the final version testing here before the product goes live.

There are several water pipes to get the test network ETH, once in the on-chain world, you can’t go anywhere without the master coin…

https://faucet.dimensions.network/
https://faucet.egorfine.com/
https://faucet.ropsten.be/
Copy the code

The deployment process is the same as the previous one and will not be described here. After finally clicking the deployment button, you need to confirm the handling fee in the pop-up wallet. Here, it is estimated to cost 0.03 ETH. The current price of Ethernet is about 20,000 yuan, which is not cheap. Test net not distressed, we click confirm to continue.

Wait patiently for the block confirmation, if everything is normal, it will be able to complete the chain operation in about a minute. You can look up your newly deployed contract in the blockchain browser

Ropsten. Etherscan. IO/token / 0 x2ed…

The main address: 0 x2ed5895a94720ae3c22b7bb30771641c9cdc976a

The child address: 0 xfc5790771590d48d6389f65809cbdd0fc7c8065e

Polygon:

The actual product will still be deployed on the main network. There is a bug in the current online version of Metamask 10.8.1 wallet when deployed on Polygon.

Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559 Object

Polygon supports IP-1559. Download the latest 10.8.2 release and fix it.

https://github.com/MetaMask/metamask-extension/releases/download/v10.8.2/metamask-chrome-10.8.2.zip

Polygon is an Ethereum side chain that is fully compatible with functionality on the Ethereum chain, which is much cheaper. Of course, there are also binance chain, wave field chain, etc. Different chains are actually different ecospheres. For example, there are multiple game applications on binance chain, casino applications on wave field chain, and financial applications on ether chain. Handling fee is also a threshold to some extent. Local private chains are the most efficient for developers, and we’ll talk more about this implementation later.

Polygon is slower than the test net, much slower, patience +1, enough to make a cup of coffee and get some exercise. After the deployment is complete, the wallet will pop up with a notification. Click on the status to directly open PolygonScan and check our tokens.

Polygonscan.com/token/0x1ab…

Wallet imports tokens

Copy the contract address in ‘Remix’. Then go back into your wallet and click ‘Import Tokens’ to Import your tokens into your wallet. 21 million arrived, please check!

It’s easy to send and exchange. Imagine finding some capital to add trading pairs to those decentralized exchanges, providing liquidity, and a few “good stories” to get those capital plates to work… Thinking is terrifying! Now you’re sure you want to buy those fake coins with real money.

If you’ve followed the above process to this point, congratulations, you should have your first fully owned smart contract and token.

Yes, it’s nothing, it can be everything, welcome to my metasomes, Enjoy Your Dream!

Download the source code

The relevant documents for this issue can be downloaded on the public account “Deep Awakening” and the link is “Chain01”.

Next up

Although online Remix is very easy to use, but not convenient debugging, that tedious test process, certainly do not want to come again. In the next article, we will do a local deployment based on Truffle and Ganache for further development and debugging.