1653174300
これは、4部構成のNFTCreatorシリーズの第4部です。
4部構成のNFTクリエーターシリーズの第4部
一緒にコーディングしたい場合は、前の部分で前提条件のコードを見つけることができます。
ミンティングとは何ですか?
ミンティングとは、デジタルファイルをイーサリアムブロックチェーン上のNFTに変換するプロセスを指します。このNFTは分散データベースに保存されるため、編集、変更、または削除することはできません。
WEB3ライブラリをインストールします
APIと対話するには、錬金術ライブラリが必要になります。したがって、これをインストールする必要があります。
コマンドラインで実行します。
chdir [INSERT HERE YOUR NFT PROJECT DIRECTORY]npm install @alch/alchemy-web3
ミンティングスクリプトを作成する
以下のコードを含むmint-nft.jsファイルを./scriptsディレクトリに作成します。
このスクリプトは、次の5つのステップで構成されています。
ミンティングプロセスには、メタマスクキーや錬金術のURLなどの変数が必要です。
それに応じて、NFTクリエーターシリーズのパート3で作成した.env
ファイルを更新してください。
小さな復習:
公開鍵の例
API_URL = "https://eth-ropsten.alchemyapi.io/v2/your-api-key"
PRIVATE_KEY = "your-private-account-address"
PUBLIC_KEY = "your-public-account-address"
.envファイル
//step 1: You define your variables from .env file
require('dotenv').config();
const API_URL = process.env.API_URL;
const PUBLIC_KEY = process.env.PUBLIC_KEY;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(API_URL);
ABI(Application Binary Interface)は、パート3で展開したスマートコントラクトと対話するためのインターフェイスです。
つまり、Hardhatは、MyNFT.jsonファイルに保存されているスマートコントラクトのABIを生成しました。
パート3で展開したスマートコントラクトアドレスを入力することが重要です。
上記の例では、契約アドレスは0x099D1751c33d75297c9f331a5Cd39275ff534f96
です。
//step 2: Define our contract ABI (Application Binary Interface) & adresses
const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json");
const contractAddress = "0x099D1751c33d75297c9f331a5Cd39275ff534f96";
const nftContract = new web3.eth.Contract(contract.abi, contractAddress);
1つのパラメーター「tokenURI」を必要とするmintNFTという関数を作成します。それを分解しましょう:
Nonce
あなたのアドレスから送信されたトランザクションの数を追跡するために使用されます。これは、リプレイ攻撃を防ぐためのセキュリティ目的で必要です。from
:トランザクションの発信元/開始者。これは私たちの公開アドレスです。to
:やり取りしたい契約アドレス。gas
:取引を完了するために必要な推定ガスmaxPriorityFeePerGas
:ガスあたりの推定入札料金data
:実行したい計算、これはnftを作成しています//step 3: Define the minting function
async function mintNFT(tokenURI) {
const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce
//the transaction
const tx = {
'from': PUBLIC_KEY,
'to': contractAddress,
'nonce': nonce,
'gas': 500000,
'maxPriorityFeePerGas': 1999999987,
'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI()
};
送信するには、トランザクションに署名する必要があります。
このために、web3.eth関数を利用します。これらは、トランザクションが効果的にマイニングされ、ネットワークによってドロップされていないことを確認するために、トランザクションハッシュを提供します。
//step 4: Sign the transaction
const signedTx = await web3.eth.accounts.signTransaction(tx, PRIVATE_KEY);
const transactionReceipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
console.log(`Transaction receipt: ${JSON.stringify(transactionReceipt)}`);
このmintNFT
関数にはtokenURI
、メタデータ(画像、プロパティ、名前、説明など)が保存されているJSONドキュメントを参照するパラメーターが必要です。
チュートリアルの第2部の指示に従って、クラウドでメタデータを生成してホストしてください。リンクを入力パラメータとしてコピーします。
//step 5: Call the mintNFT function
mintNFT("https://gateway.pinata.cloud/ipfs/Qmeou5f7ttU98n96mYWfYzKHV7pfRe5rcZBhYznHZCUV7M");
mint-nft.jsファイルは次のようになります。
//step 1: You define your variables from .env file
require('dotenv').config();
const API_URL = process.env.API_URL;
const PUBLIC_KEY = process.env.PUBLIC_KEY;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(API_URL);
//step 2: Define our contract ABI (Application Binary Interface) & adresses
const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json");
const contractAddress = "0x099D1751c33d75297c9f331a5Cd39275ff534f96";
const nftContract = new web3.eth.Contract(contract.abi, contractAddress);
//step 3: Define the minting function
async function mintNFT(tokenURI) {
const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce
//the transaction
const tx = {
'from': PUBLIC_KEY,
'to': contractAddress,
'nonce': nonce,
'gas': 500000,
'maxPriorityFeePerGas': 1999999987,
'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI()
};
//step 4: Sign the transaction
const signedTx = await web3.eth.accounts.signTransaction(tx, PRIVATE_KEY);
const transactionReceipt = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);
console.log(`Transaction receipt: ${JSON.stringify(transactionReceipt)}`);
}
//step 5: Call the mintNFT function
mintNFT("https://gateway.pinata.cloud/ipfs/Qmeou5f7ttU98n96mYWfYzKHV7pfRe5rcZBhYznHZCUV7M");
mint-nft関数を呼び出す
mint-nft
これで、ターミナルでスクリプトを実行してNFTを作成します。
ターミナルでこれを実行します。
node scripts/mint-nft.js
すべての手順を正しく実行すると、使用されたすべてのパラメータを規定した「取引領収書」を受け取るはずです。
トランザクションが成功したかどうかをRopstenEtherscanで確認することもできます。
Ropsten etherscanは、トランザクションが成功したと報告します
簡単にするために、1nftを作成しました。
ミントしたい画像が他に99個あるのでmint-nft
、異なるメタデータリンクごとに99回関数を実行するforループを作成できます。
//step 5: Call the mintNFT function
const metadatalinks = ["https://gateway.pinata.cloud/ipfs/Qmeou5f7ttU98n96mYWfYzKHV7pfRe5rcZBhYznHZCUV7M" , "https://gateway.pinata.cloud/ipfs/QmaUK792RLARk4y3yZww1tnvu5GGAXdVqKYVr76dwrHVfp/1.json"]
for (const s of metadatalinks) {
mintNFT(s)
};
forループの例
ミントされたNFTを表示する
0x099d1751c33d75297c9f331a5cd39275ff534f96
メタマスクを更新すると、新しく作成したNFTが表示されます。
メタマスクは、新たに作成されたnftを表示します
ハッピープログラミング!
ソース:https ://betterprogramming.pub/mint-your-own-nfts-with-web3-js-f32f7b1cd8cc
1657182720
Abstract
The demo code provides developers with an overview of how to sign, send, and receive receipt of transactions, and verify the results of their execution. The sample also provides the event monitoring code so that the developer can understand how to listen to an event one or more times.
Getting Started
Constructor
: The constructor function of the smart contract, which is called when the contract is deploying, at the same time it will initialize the number
to _initialNumber
;increment
: The function of incrementing the number
by given _value
;rest
: The function of resetting the number
to 0;getNumber
: The function of getting the number
.npm install
cp .env.example .env
vim .env
, copy your project ID and private key to the .env
file.PRIVATE_KEY=YOUR_PRIVATE_KEY
INFURA_ID=YOUR_PROJECT_ID
4. Run the index.js
file: node index.js
Interpret Source Code
compile.js
You can't use .sol
files directly, you need to compile it to binary file firstly.
Incrementer.sol
into source
variable.// Load contract
const source = fs.readFileSync("Incrementer.sol", "utf8");
const input = {
language: "Solidity",
sources: {
"Incrementer.sol": {
content: source,
},
},
settings: {
outputSelection: {
"*": {
"*": ["*"],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
| Note: The version of solidity in this task is 0.8.0
, different versions may have different compile ways.
const contractFile = tempFile.contracts["Incrementer.sol"]["Incrementer"];
contractFile
ObjectIf you want to use the contractFile
object in other js
files, you need to export it.
module.exports = contractFile;
index.js
Incrementer
smart contract from compile
fileconst contractOfIncrementer = require("./compile");
For security’s sake, the private key is not hard-coded, but it can be read as environment variables. When run this task, the dotenv
plugin will automatically read the configurations in the .env
file and load them as environment variables, and then you can use the private key and other environment variables via process.env
.
require("dotenv").config();
const privatekey = process.env.PRIVATE_KEY;
web3
instanceweb3
is the main API of the web3js
library. It is used to interact with the blockchain.
// Provider
const providerRPC = {
development: "https://kovan.infura.io/v3/" + process.env.INFURA_ID,
moonbase: "https://rpc.testnet.moonbeam.network",
};
const web3 = new Web3(providerRPC.development); //Change to correct network
| Note: The INFURA_ID
is the PROJECT ID
of the Infura
project you created in last task
account
addressOn blockchain, each user has a address
, which is unique for others, and you can get the address
by the private key. In this task, you can use the we3.eth.accounts.privateKeyToAccount
API to get your account
address by passing the private key as a parameter.
const account = web3.eth.accounts.privateKeyToAccount(privatekey);
const account_from = {
privateKey: privatekey,
accountAddress: account.address,
};
bytecode
and abi
When deploying the smart contract, you need to specify the bytecode
and abi
of the smart contract. The bytecode
is the compiled binary code of the smart contract, and the abi
(Application Binary Interface) is the interface of the smart contract.
const bytecode = contractOfIncrementer.evm.bytecode.object;
const abi = contractOfIncrementer.abi;
In the last step, you got the bytecode
and abi
, so you can create the contract instance by the abi
.
// Create contract instance
const deployContract = new web3.eth.Contract(abi);
deployContract
// Create Tx
const deployTx = deployContract.deploy({
data: bytecode,
arguments: [5],
});
Use your private key to sign the transaction.
// Sign Tx
const deployTransaction = await web3.eth.accounts.signTransaction(
{
data: deployTx.encodeABI(),
gas: 8000000,
},
account_from.privateKey
);
Send your deploy
transaction to the blockchain. You will receive a receipt, and get this contract address from the receipt.
const deployReceipt = await web3.eth.sendSignedTransaction(
deployTransaction.rawTransaction
);
console.log(`Contract deployed at address: ${deployReceipt.contractAddress}`);
In previous steps, you built a contract instance, and then deployed the transaction by sending the contract to the blockchain so that you can operate the transaction later. Besides, you could also load a contract instance that is already on the blockchain so that you can operate it directly and avoid the process of deploying it.
let incrementer = new web3.eth.Contract(abi, deployReceipt.contractAddress);
view
function of a contractWhether a contract instance is create by deploying, or by loading, you can interact with the contract once you have an instance of the contract already on the blockchain.
There are two types of contract functions: view
and without view
. The functions with view
promise not to modify the state, while the functions without view
will generate the corresponding block data on the blockchain. For example, after calling the getNumber
function of the contract, you will get the public variable number of the contract, and this operation will not charge any gas.
let number = await incrementer.methods.getNumber().call();
Before you send the transaction to the blockchain, you need to build the transaction, it means you need to specify the parameters of the transaction.
let incrementTx = incrementer.methods.increment(_value);
// Sign with Pk
let incrementTransaction = await web3.eth.accounts.signTransaction(
{
to: createReceipt.contractAddress,
data: incrementTx.encodeABI(),
gas: 8000000,
},
account_from.privateKey
);
You can use sendSignedTransaction
function to send above transaction to the blockchain, and got the receipt to check result.
const incrementReceipt = await web3.eth.sendSignedTransaction(
incrementTransaction.rawTransaction
);
When invoking the interfaces of the contract, the only way to get information about the processing details, apart from the results returned by the interface, is through events
.
In the interfaces, you retrieve the corresponding internal information by triggering an event, and then capturing this event generated by the external block.
const web3Socket = new Web3(
new Web3.providers.WebsocketProvider(
'wss://kovan.infura.io/ws/v3/' + process.env.INFURA_ID
));
incrementer = new web3Socket.eth.Contract(abi, createReceipt.contractAddress);
| kovan don't support http protocol to event listen, need to use websocket. More details , please refer to this blog
incrementer.once('Increment', (error, event) => {
console.log('I am a onetime event listener, I am going to die now');
});
incrementer.events.Increment(() => {
console.log("I am a longlive event listener, I get a event now");
});
References
Link: https://github.com/Dapp-Learning-DAO/Dapp-Learning/tree/main/basic/02-web3js-transaction
#solidity #blockchain #smartcontract #web3 #web3.js
1657183343
Abstract
The demo code provides developers with an overview of how to sign, send, and receive receipt of transactions, and verify the results of their execution. The sample also provides the event monitoring code so that the developer can understand how to listen to an event one or more times.
Getting Started
Constructor
: The constructor function of the smart contract, which is called when the contract is deploying, at the same time it will initialize the number
to _initialNumber
;increment
: The function of incrementing the number
by given _value
;rest
: The function of resetting the number
to 0;getNumber
: The function of getting the number
.npm install
cp .env.example .env
vim .env
, copy your project ID and private key to the .env
file.PRIVATE_KEY=YOUR_PRIVATE_KEY
INFURA_ID=YOUR_PROJECT_ID
4. Run the index.js
file: node index.js
Interpret Source Code
compile.js
You can't use .sol
files directly, you need to compile it to binary file firstly.
Incrementer.sol
into source
variable.// Load contract
const source = fs.readFileSync("Incrementer.sol", "utf8");
const input = {
language: "Solidity",
sources: {
"Incrementer.sol": {
content: source,
},
},
settings: {
outputSelection: {
"*": {
"*": ["*"],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
| Note: The version of solidity in this task is 0.8.0
, different versions may have different compile ways.
const contractFile = tempFile.contracts["Incrementer.sol"]["Incrementer"];
contractFile
ObjectIf you want to use the contractFile
object in other js
files, you need to export it.
module.exports = contractFile;
index.js
Incrementer
smart contract from compile
fileconst contractOfIncrementer = require("./compile");
For security’s sake, the private key is not hard-coded, but it can be read as environment variables. When run this task, the dotenv
plugin will automatically read the configurations in the .env
file and load them as environment variables, and then you can use the private key and other environment variables via process.env
.
require("dotenv").config();
const privatekey = process.env.PRIVATE_KEY;
web3
instanceweb3
is the main API of the web3js
library. It is used to interact with the blockchain.
// Provider
const providerRPC = {
development: "https://kovan.infura.io/v3/" + process.env.INFURA_ID,
moonbase: "https://rpc.testnet.moonbeam.network",
};
const web3 = new Web3(providerRPC.development); //Change to correct network
| Note: The INFURA_ID
is the PROJECT ID
of the Infura
project you created in last task
account
addressOn blockchain, each user has a address
, which is unique for others, and you can get the address
by the private key. In this task, you can use the we3.eth.accounts.privateKeyToAccount
API to get your account
address by passing the private key as a parameter.
const account = web3.eth.accounts.privateKeyToAccount(privatekey);
const account_from = {
privateKey: privatekey,
accountAddress: account.address,
};
bytecode
and abi
When deploying the smart contract, you need to specify the bytecode
and abi
of the smart contract. The bytecode
is the compiled binary code of the smart contract, and the abi
(Application Binary Interface) is the interface of the smart contract.
const bytecode = contractOfIncrementer.evm.bytecode.object;
const abi = contractOfIncrementer.abi;
In the last step, you got the bytecode
and abi
, so you can create the contract instance by the abi
.
// Create contract instance
const deployContract = new web3.eth.Contract(abi);
deployContract
// Create Tx
const deployTx = deployContract.deploy({
data: bytecode,
arguments: [5],
});
Use your private key to sign the transaction.
// Sign Tx
const deployTransaction = await web3.eth.accounts.signTransaction(
{
data: deployTx.encodeABI(),
gas: 8000000,
},
account_from.privateKey
);
Send your deploy
transaction to the blockchain. You will receive a receipt, and get this contract address from the receipt.
const deployReceipt = await web3.eth.sendSignedTransaction(
deployTransaction.rawTransaction
);
console.log(`Contract deployed at address: ${deployReceipt.contractAddress}`);
In previous steps, you built a contract instance, and then deployed the transaction by sending the contract to the blockchain so that you can operate the transaction later. Besides, you could also load a contract instance that is already on the blockchain so that you can operate it directly and avoid the process of deploying it.
let incrementer = new web3.eth.Contract(abi, deployReceipt.contractAddress);
view
function of a contractWhether a contract instance is create by deploying, or by loading, you can interact with the contract once you have an instance of the contract already on the blockchain.
There are two types of contract functions: view
and without view
. The functions with view
promise not to modify the state, while the functions without view
will generate the corresponding block data on the blockchain. For example, after calling the getNumber
function of the contract, you will get the public variable number of the contract, and this operation will not charge any gas.
let number = await incrementer.methods.getNumber().call();
Before you send the transaction to the blockchain, you need to build the transaction, it means you need to specify the parameters of the transaction.
let incrementTx = incrementer.methods.increment(_value);
// Sign with Pk
let incrementTransaction = await web3.eth.accounts.signTransaction(
{
to: createReceipt.contractAddress,
data: incrementTx.encodeABI(),
gas: 8000000,
},
account_from.privateKey
);
You can use sendSignedTransaction
function to send above transaction to the blockchain, and got the receipt to check result.
const incrementReceipt = await web3.eth.sendSignedTransaction(
incrementTransaction.rawTransaction
);
When invoking the interfaces of the contract, the only way to get information about the processing details, apart from the results returned by the interface, is through events
.
In the interfaces, you retrieve the corresponding internal information by triggering an event, and then capturing this event generated by the external block.
const web3Socket = new Web3(
new Web3.providers.WebsocketProvider(
'wss://kovan.infura.io/ws/v3/' + process.env.INFURA_ID
));
incrementer = new web3Socket.eth.Contract(abi, createReceipt.contractAddress);
| kovan don't support http protocol to event listen, need to use websocket. More details , please refer to this blog
incrementer.once('Increment', (error, event) => {
console.log('I am a onetime event listener, I am going to die now');
});
incrementer.events.Increment(() => {
console.log("I am a longlive event listener, I get a event now");
});
References
Link: https://github.com/Dapp-Learning-DAO/Dapp-Learning/tree/main/basic/02-web3js-transaction
#solidity #blockchain #smartcontract #web3 #web3.js
1655262720
Do you recall the early days of the video game industry when classic games in 2D environments had everyone stuck to their screen for hours? Retro games are still quite popular, and even modern game developers still create 2D games today. However, Web3 brings new concepts to the gaming industry, such as the play-to-earn (P2E) model, where players can earn fungible and non-fungible tokens (NFTs). Thus, if we combine popular 2D environments and Web3, offering earning potentials, the ability to use NFTs as in-game assets, etc., our 2D Web3 game would attract numerous users. As such, we decided to illustrate herein how to build a 2D Web3 game using the right Web3 tech stack and accomplish this process in a matter of minutes.
Moving forward, we’ll incorporate a publicly available 2D game into a React application. In addition, to include Web3 functionality, we’ll use the ultimate Web3 development platform, Moralis. This “Firebase for crypto” platform will enable us to easily incorporate Web3 authentication using the most popular Web3 wallet – MetaMask. Also, with Moralis’ SDK, we will get a chance to add other on-chain features to our 2D Web3 game example. Plus, we’ll rely on some other phenomenal tools to get us to the finish line, such as Phaser and Visual Studio Code (VSC). Nonetheless, we encourage you to follow our lead and join us by tackling this example project. By doing so, you will not only learn to create a 2D Web3 game but also get familiar with the tools mentioned above. So, create your free Moralis account, which you’ll need as we move on.
Before we start our example project, we want to do a quick demo of our example 2D Web3 game. This will help you determine whether or not you want to roll up your sleeves and follow our tutorial as we move on.
First, users are greeted by the “Start” button:
By clicking on the above button, users are prompted by their MetaMask extensions to sign the “Log in using Moralis” message. Essentially, this is how to authenticate with MetaMask:
After receiving the above signature request, users need to click on the “Sign” button. By doing so, they complete their Web3 login for our game.
Also, keep in mind that there are different ways to implement Web3 authentication. However, when using Moralis, things are made as simple as possible. For web dapps (decentralized applications), MetaMask integration is the go-to tool. On the other hand, WalletConnect is the best solution for mobile dapps. Nonetheless, Moralis also offers Web3 authentication via email and Web3 social login. Both of these options are excellent to boost Web3 user onboarding success rates.
Once users confirm the sign-in message, they are presented with the game’s main menu screen:
Then, users need to click anywhere on the screen to start the game. This loads the game:
Moreover, the purpose of the game is to click (shoot) the bandits (cowboys with the guns) before they shoot you. As you can see in the screenshot above, there are also characters with money bags. Players are not supposed to shoot them. In addition, the numbers at the top indicate the money bags that players need to collect to complete the level. However, if any of the bandits shoot the player before getting shot, it is game over:
Now you know what we will be creating. Hence, you can decide whether or not you want to follow along with our progress moving on. However, we need to point out that we will not be dealing with the frontend of the above-presented game. By using Phaser, we will use an existing Web2 game as a boilerplate and then just add Web3 backend features.
As mentioned, we will use Phaser, the most popular open-source studio game engine, to find a finished 2D game. Then, we will use the best Web3 backend platform, Moralis, to incorporate the above-presented blockchain functionality. Essentially, we will take a 2D Web2 game and convert it into a 2D Web3 game.
So, we start by going to Phaser’s official website. There, we select “Examples” from the top menu. On the next page, we scroll down a bit and click on the “Games” folder. From there, we select the “Bank Panic” game:
Now that we’ve set up our minds on a particular example game, we can use Phaser’s code and assets available on GitHub. Hence, use the “Download” option in the top menu:
On the “Download” page, we get to download Phaser:
Then, click on the “clone” option on the next page to get to Phaser’s GitHub:
There, click on “photonstorm”:
Next, we will select “phaser3-examples” to ensure that the “Bank Panic” game files are included:
Inside “phaser3-examples”, open the “public” folder:
Then, inside the “public” folder, click on the “assets” folder:
Next, open “games” and finally “bank-panic”:
When we look inside the “bank-panic” folder, we see that it contains sounds, images, and other files required for this game to function properly. As such, we have a green light to clone the code. Thus, we go back to the “phaser3-example” page, where we click on “code” and then ”Download ZIP”:
Note: We use VSC in this example; however, feel free to use your preferred code editor.
We start by creating a React app template. We do this by entering the “npx create-react-app phaser-moralis” command into VSC’s terminal:
Also, keep in mind that “phaser-moralis” is the name we decided to use for our dapp. You can follow our lead or use any name you want. To finally create our React app, enter “yes” next to “Ok to proceed? (y)”. Once that folder is created, we add it to our IDE workspace:
Then, select the “phaser-moralis” folder and click on “Add”:
Now, we unzip the “phaser3-examples-master.zip” file that we downloaded previously. Once unzipped, we navigate to the “bank panic” folder (phaser3-examples-master > public > src > games > bank panic). This is where our example game’s scene files are:
As you can see in the screenshot above, we select all files except the “main.js” file. We move those files into a new “scenes” folder, within our “src” folder inside our React app’s folder (created above):
Now that we’ve transferred our example game’s scene files, we need to do the same for all of the image and sound files. To do this, we have to locate the “bank panic” folder inside “assets” and then “games”. Then, we copy or move the entire folder into the new “assets” folder inside the “public” folder of our project:
By moving these files, we are essentially integrating Phaser’s example game into our ReactJS application. Next, we navigate into the “phaser-moralis” folder by entering the “cd phaser-moralis” command in VSC’s terminal.
All of you who want to access the finished code of our 2D Web3 game, you can do so on GitHub. Though, we recommend following along with our steps and making the necessary tweaks to get the most out of this article. We start by changing the title inside the “index.html” file from “React App” to “Phase x React x Moralis”:
Then, change “.js” extensions into “.jsx” extensions for “App.js” and for “index.js”:
Next, we tweak the “index.jsx” file by adding a container to which our canvas element will attach to. Above the “<App />” line, we add the following:
<div id= “game-container”></div>
Moreover, we wrap the above container around the “App” component:
Then, we open the “App.jsx” file, where we first import our Phaser files at the top:
This is also our cue to install Phaser by entering “npm i phaser” into VSC’s terminal. Next, still inside the “App.jsx” file, we initiate our “game” variable using “let game = null;”. Then, we need to add some additional imports and tweak the “App()” function. This is also where we add the following “config” object, through which our Phaser game gets initiated:
if (!loaded) {
setLoaded(true);
const config = {
type: Phaser.AUTO,
//gameTitle: "Phaser x Moralis",
parent: "game-container",
autoCenter: Phaser.Scale.CENTER_HORIZONTALLY,
autoFocus: true,
fps: {
target: 60,
},
physics: {
default: "arcade",
arcade: {
gravity: { y: 200 },
debug: false,
},
},
backgroundColor: "#282c34",
scale: {
mode: Phaser.Scale.ScaleModes.NONE,
},
scene: [Boot, Preloader, MainMenu, MainGame],
};
// init 2d game (Phaser canvas element)
if (game === null) {
// init instance of phaser game as per config
game = new Phaser.Game(config);
// listen to in-game events
// before starting we sign in with wallet
game.events.on("LOGIN_PLAYER", (event) => {
console.log("⛓⛓⛓ Login via Web3 Wallet ⛓⛓⛓");
// trigger wallet authentication
login();
});
}
For the above code to function, we also need to import Phaser in our scene files (“Boot.js”, “Door.js”, “Game.js”, “MainMenu.js”, and “Preloader.js”) using the ‘import phaser from “phaser”;’ line. Moreover, we also need to assign the initial values inside the “Game.js” file:
Furthermore, we need to change some file paths inside the “Preloader.js” and “Boot.js” files. Inside the former, we change the “assets/game/bank-panic/” value inside “this.load.setPath” to “assets/bank-panic/”. Moreover, inside the “Boot.js”, we change “assets/game/bank-panic/loading.png” to “assets/bank-panic/loading.png”.
With all of the above tweaks applied, we have a functioning 2D game available. However, it currently has nothing to do with Web3. Fortunately, we can use Moralis to include all sorts of Web3 features seamlessly. Though, for this example project, we will focus on adding Web3 authentication.
We start by importing React Moralis with the “npm i react-moralis” command in VSC’s terminal. Then, we revisit the “index.jsx” file, where we import “react-moralis” with the ‘import { MoralisProvider } from “react-moralis”;’ line. Next, we add a standard “Application” function (video below at 12:05). The latter serves as a standard login to our Moralis server. To make that work, we also create a new “.env” file (12:52), where we add our Moralis server’s details:
The next task is to obtain our Moralis server’s details. If you’re new to Moralis, here are the steps to get the details (13:15):
Moving forward, we made some small tweaks to the “index.jsx” file (14:10). Then, we add React-Moralis functions in “App.jsx” (14:36), which gives us the power of Moralis’ SDK. As such, we easily cover authentication with MetaMask. Finally, we include Redux for dispatching events from our 2D Web3 game to our React hooks and vice versa (15:13).
Note: Make sure to watch the video below and watch closely to get all the steps right.
https://www.youtube.com/watch?v=Z4dWavvyhbA
At this point, you should have your own 2D Web3 game functioning properly. Using Phaser, MetaMask, and Moralis, you’ve been able to do that in less than thirty minutes. Along the way, you’ve learned how to use Phaser’s example games. Moreover, you’ve learned how to complete the initial Moralis setup and then use it to include Web3 functionality. As such, you can now use these skills to create your own 2D Web3 games. However, you may not yet be confident enough to start your own projects. Thus, taking on other example projects may be the right direction for you. On the other hand, you may want to explore other blockchain development topics.
This story was originally published at https://moralis.io/how-to-build-a-2d-web3-game-full-guide%ef%bf%bc/
1648871509
Join Moralis Projects for weekly challenges building Web3 projects! Moralis Projects represent the best way to learn how to build Web3 projects with real-life use cases. You’ll build the projects alongside the community, allowing you to make new connections whilst building. What’s more, you can even earn NFTs for completing Moralis Projects! New Moralis Projects
In this week’s project you will be building a Web3 Netflix Clone, with movie assets stored in a decentral fashion on IPFS. Users will only be able to view a movie on the website if they have been authenticated through their crypto wallet.
This authentication is facilitated by Moralis’ Web3 Development Platform, which is the number one way to build your first dapp. We’ll also be using the Moralis database to allow authenticated users to add films to their personal list of favorites.
There is an official Discord channel on the Moralis Discord Server dedicated to each Moralis Project. This channel can be used to connect with others building each week’s projects, to ask questions, and present your builds. There will be a Moralis Tech Support wizard helping out as well if you’ve got any questions or need any assistance.
Be sure to join the Discord server to take part in the conversation! Then be sure to set up notifications in projects-notifications and jump into this week’s channel; #web3-Netflix.
All Moralis Projects are starter tutorials designed to give you a strong push in the right direction on your Web3 development journey. Also, if you want to go even further and build a more ambitious project based on what you learned in a Moralis Project, we highly encourage it!
If you find mistakes in any Moralis Projects, feel free to share them with the community and even suggest merge requests in the final build repos, to get you some extra brownie points.
The starter code required for this week’s build may be cloned from the youtube-tutorials GitHub Repository.
git clone https://github.com/MoralisWeb3/youtube-tutorials.git
After cloning the repo, be sure to navigate to the correct folder.
cd youtube-tutorials
cd Netflix-Starter
And finally you can install all the project dependencies by running the command
yarn
Original article source at https://moralis.io
#moralis #web3 #netflix #nft #blockchain
1657190583
Web3js ERC20
This basic task is to show how to interact with ERC20 contract, so the developer can understand the basic interface of ERC20 contract.
IERC20 totalSupply: Get the total amount of ERC20 token in the contract balanceOf: Get the amount of ERC20 token of specific account in the contract transfer: Transfer ERC20 token to specific account allowance: Get the amount of ERC20 tokens of the source account that the target account can use approve: Authorize the target account to transfer the specified amount of ERC20 Tokens transferFrom: (Third party call) Transfer a specific amount of ERC20 token from the source account to target account
IERC20Metadata name: Get the name of the Token symbol: Get the symbol of the Token decimals: Get the decimals of the Token
npm install
cp .env.example .env
vim .env
, copy your project ID and private key to the .env
file.PRIVATE_KEY=YOUR_PRIVATE_KEY
INFURA_ID=YOUR_PROJECT_ID
4. Run the index.js
file: node index.js
compile.js
You can't use .sol
files directly, you need to compile it to binary file firstly.
SimpleToken.sol
into source
variable.// Load contract
const source = fs.readFileSync('SimpleToken.sol', 'utf8');
2. Compile the smart contract file
// compile solidity
const input = {
language: 'Solidity',
sources: {
'SimpleToken.sol': {
content: source,
},
},
settings: {
outputSelection: {
'*': {
'*': ['*'],
},
},
},
};
const tempFile = JSON.parse(solc.compile(JSON.stringify(input)));
| Note: The version of solidity in this task is 0.8.0
, different versions may have different compile ways.
3. Get the Contract Binary Object
The solidity object that was successfully compiled in the previous step contains many properties/values, and what we only need is the contract object, so we can get the SimpleToken
contract object by accessing the object properties.
const contractFile = tempFile.contracts['SimpleToken.sol']['SimpleToken'];
4. Export contractFile
Object If you want to use the contractFile
object in other js
files, you can export it.
module.exports = contractFile;
index.js
SimpleToken
smart contract from compile
fileconst contractFile = require('./compile');
2. Load private key
For security’s sake, the private key is not hard-coded, but it can be read as environment variables. When run this task, the dotenv
plugin will automatically read the configurations in the .env
file and load them as environment variables, and then you can use the private key and other environment variables via process.env
.
require('dotenv').config();
const privatekey = process.env.PRIVATE_KEY;
3. Create a receiver
account for testing
const receiver = '0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266';
4. Build the web3
object
const web3 = new Web3(new Web3.providers.HttpProvider('https://kovan.infura.io/v3/' + process.env.INFURA_ID));
| Note: The INFURA_ID
is the PROJECT ID
of the Infura
project you created in last task
5. Get the account
address
On blockchain, each user has a address
, which is unique for others, and you can get the address
by the private key. In this task, you can use the we3.eth.accounts.privateKeyToAccount
API to get your account
address by passing the private key as a parameter.
const account = web3.eth.accounts.privateKeyToAccount(privatekey);
const account_from = {
privateKey: account.privateKey,
accountaddress: account.address,
};
6. Get the abi
and bin
When deploying the smart contract, we need two important parameters which are the bytecode
and abi
of the smart contract. In previous step 1, we loaded the compiled SimpleToken
object, so we can get the bytecode
and abi
from it.
const bytecode = contractFile.evm.bytecode.object;
const abi = contractFile.abi;
7. Get contract instance In the last step, you got the bin
and abi
, so we can create the contract instance by the abi
.
const deployContract = new web3.eth.Contract(abi);
8. Create the transaction of the deployContract
const deployTx = deployContract.deploy({
data: bytecode,
arguments: ['DAPPLEARNING', 'DAPP', 0, 10000000],
});
| So far, this transaction has not been deployed into the blockchain.
9. Sign the transaction Use your private key to sign the transaction.
const deployTransaction = await web3.eth.accounts.signTransaction(
{
data: deployTx.encodeABI(),
gas: '8000000',
},
account_from.privateKey
);
10. Deploy the contract Send your signed deployTransaction
transaction to the blockchain. You will receive a receipt, and get this contract address from it.
const deployReceipt = await web3.eth.sendSignedTransaction(deployTransaction.rawTransaction);
console.log(`Contract deployed at address: ${deployReceipt.contractAddress}`);
11. Create a transfer transaction
We created a transfer transaction for ERC20
token, the receiver is receiver
account, and the amount is 100000
token.
const transferTx = erc20Contract.methods.transfer(receiver, 100000).encodeABI();
12. Sign and send the transaction
const transferReceipt = await web3.eth.sendSignedTransaction(transferTransaction.rawTransaction);
13. Check the balance of the receiver
account
After the transaction is sent, you can log the balance of the receiver
and make sure the balance is correct.
erc20Contract.methods
.balanceOf(receiver)
.call()
.then((result) => {
console.log(`The balance of receiver is ${result}`);
});
infura
doesn't support sendTransaction
, only support sendRawTransaction
infura
doesn't invoke eth_sendTransaction
, so you need to an unlocked account on the ethereum
node. More details, please refer to thisLink: https://github.com/Dapp-Learning-DAO/Dapp-Learning/tree/main/basic/03-web3js-erc20
#solidity #blockchain #smartcontract #web3 #web3.js #ethereum