Yusef Napora
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # encode club challenges ## challenge 1 - deploy an NFT contract ### Tools used - Node.js, version 16 - NPM, version 7 - HardHat - ethereum development framework & blockchain simulator - https://hardhat.org - OpenZeppelin Contracts - base Solidity contracts - https://docs.openzeppelin.com/contracts/4.x ### Steps 1. Make a new directory for the project and enter it ```bash mkdir nft-challenge cd nft-challenge ``` 1. Start a new NPM project with default settings ```bash npm init -y ``` 1. Install HardHat and OpenZeppelin contracts as development dependencies ```bash npm install --save-dev hardhat @openzeppelin/contracts ``` 1. Use hardhat to generate a project scaffold ```bash npx hardhat ``` Accept the defaults when prompted about installing dependencies. At the end, you should see something like this: ``` ✨ Project created ✨ Try running some of the following tasks: npx hardhat accounts npx hardhat compile npx hardhat test npx hardhat node node scripts/sample-script.js npx hardhat help ``` And there will be some new files in the directory: ```bash ls contracts node_modules package.json test hardhat.config.js package-lock.json scripts ``` 1. (optional) Checkpoint your work with a git commit ```bash git init . git add . git commit -m 'solidity boilerplate' ``` 1. Open your favorite editor and open the project directory ```bash code . ``` Click into the `contracts` directory and open `Greeter.sol` to see a "hello world" smart contract. 1. Make a new file in the contracts dir called 'GameItem.sol' and paste this in: Source: https://docs.openzeppelin.com/contracts/4.x/erc721 ```solidity // contracts/GameItem.sol // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; contract GameItem is ERC721URIStorage { using Counters for Counters.Counter; Counters.Counter private _tokenIds; constructor() ERC721("GameItem", "ITM") {} function awardItem(address player, string memory tokenURI) public returns (uint256) { _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(player, newItemId); _setTokenURI(newItemId, tokenURI); return newItemId; } } ``` 1. Compile the contract ```bash npx hardhat compile ``` 1. Open the sample script from the HardHat skeleton Open `scripts/sample-script.js` in your editor. Rename `Greeter` to `GameItem` and `greeter` to `gameItem`. Remove the argument to `GameItem.deploy()`. The `main` function in the end result should look like this: ```js async function main() { // Hardhat always runs the compile task when running scripts with its command // line interface. // // If this script is run directly using `node` you may want to call compile // manually to make sure everything is compiled // await hre.run('compile'); // We get the contract to deploy const GameItem = await hre.ethers.getContractFactory("GameItem"); const gameItem = await GameItem.deploy(); await gameItem.deployed(); console.log("GameItem deployed to:", gameItem.address); } ``` 1. Run the script using the `hardhat` command: ```bash npx hardhat run scripts/sample-script.js GameItem deployed to: 0x5FbDB2315678afecb367f032d93F642f64180aa3 ``` It says it's deployed and gives us an address! Great, so we're done, right? Not quite... by default, HardHat uses an ephermeral blockhain simulator as it's target environment. This is useful for writing automated tests, but it's not much fun to play with interactively. Next we'll start a local node and tell HardHat to use it. 1. Open a new terminal in the project directory and run a hardhat node ```bash npx hardhat node ``` 1. Back in the original terminal, set the HARDHAT_NETWORK environment variable to localhost and re-run the script ```bash export HARDHAT_NETWORK=localhost npx hardhat run scripts/sample-script.js ``` The output of the script should be about the same, but you'll see some information about the transaction in the output of the hardhat node if you look at the other terminal. ## Challenge 2 1. Open `scripts/sample-script.js` again in your editor. After deploying the contract, add some code to call the `awardItem` function. ```js const accounts = await hre.ethers.getSigners() const player = accounts[0].address const cid = 'a-fake-cid' const tx = await gameItem.awardItem(player, `ipfs://${cid}`) const receipt = await tx.wait() for (const event of receipt.events) { if (event.event !== 'Transfer') { continue } console.log('token id: ', event.args.tokenId.toString()) console.log('owner: ', event.args.to) } const uri = await gameItem.tokenURI(1) console.log('token uri:', uri) ``` 2. Run the script ```bash npx hardhat run scripts/sample-script.js ``` ## Challenge 3 1. Install nft.storage client ```bash npm install nft.storage ``` 2. Open `scripts/sample-script.js` again in your editor. Import the client package and File constructor, plus the built in `readFile` for node.js ```js const { readFile } = require('fs/promises') const { NFTStorage, File } = require('nft.storage') ``` 3. Make a new function to load an image file and store it ```js async function storeNFTData() { const apiKey = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJnaXRodWJ8Njc4NzE1IiwiaXNzIjoibmZ0LXN0b3JhZ2UiLCJpYXQiOjE2MTYwNzM2MjMxMTksIm5hbWUiOiJkZWZhdWx0In0.RJj_mR2zwTJ1_4gpAapGdkQcw3gSUz1SMmIHgr10Xng' const client = new NFTStorage({ token: apiKey }) const filename = '../files/nft.jpg' const data = await readFile(filename) const file = new File([data], 'nft.jpg', { type: 'image/jpeg' }) console.log('sending data to nft.storage...') const metadata = await client.store({ name: 'Encode Club Demo NFT', description: 'Hello Encode Club!', image: file }) console.log('stored NFT data! metadata URL:', metadata.url) return metadata.url } ``` 4. Call the function to get the metadata url before creating a token In the `main` function: ```js const metadataURI = await storeNFTData() const tx = await gameItem.awardItem(player, metadataURI) ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully