Tech Blog Place App 💻 – 科技博客地点应用程序💻区块链毕设代写

区块链毕设代写本文提供国外最新区块链项目源码下载,包括solidity,eth,fabric等blockchain区块链,Tech Blog Place App 💻 – 科技博客地点应用程序💻区块链毕设代写 是一篇很好的国外资料

Tech Blog Place App 💻

This project demonstrates a basic smart contract. It allows users to send messages to a smart contract, and display it as some kind of a log.

__buildspace

This project is the result from following buildspace’s hands on course “Build a Web3 App on Ethereum with Solidty + Smart Contracts”. It’s a free, high quality course and I personally recommend everyone that wants to start learning how to develop dApps to go and try out!

Directory Structure

. tech-blog-place-dApp/ |__ app/ | |__ src/ |    |-- pages/Index.vue // Main page |    |__ utils/WavePortal.json // contract ABI |   |__ contract/   |-- contracts/   |  |__ WavePortal.sol // Contract source   |-- scripts/   |  |-- run.js   |  |__ deploy.js   |__ test/ 

The deploy.js script will compile and deploy the smart contract using Hardhat.

To deploy to the Goerli testnet, run npm run deploy -- --network goerli

Learning Log

2021-08-26 12:32

Checkpoint – d63bd3b

— Created a smart contract with a local state totalWaves and two methods, one to mutate the state by incrementing it and another to access and return its value.

The mutating method(similar to POST HTTP method, setter methods in Java or methods that requires mut self in Rust) also accesses a global state that every contracts have access to — msg. We accessed the msg.sender variable which holds the address of whoever that sends the transaction.

The global variables exist because when a function in our smart contract is called/invoked, it’s actually the blockchain that does it, and the blockchain sends along the calldata, which is the metadata from the external function call.

Here’s how I picture it:

     (1)                              (2) user ---------------------> blockhain ---------------> contract (addr - 0xfoo)       "pls invoke function            "pls invoke `increment`,        `increment` on contract         and here's what you        with address 0xfoo"             need to know about this                                        transaction (in `msg`)" 

Note: The process in (2) is the one that requires the famous term mining or validating (i think so). Without any stakeholders that validate your transaction, the transaction wouldn’t be made.

Along with sender, there’s also other accessable variables in the msg global variable:

  • data — immutable(you cannot change them), non-persistent(it will be gone after this transaction is done) area where function arguments are stored and behave mostly like memory.
  • gas — Available remaining gas.
  • sig — First for bytes of the calldata that tells which function to be called.
  • value — How much wei(a representation of eth) are you sending me?

The local state is however not persistent. It is created when Hardhat create the contract locally and destroyed after it finished deploying and invoking the two contract methods. In order to make it persistent, we need to deploy the contract on-chain, whether on a testnet or the mainnet.

2021-08-28 13:58

Checkpoint – my repl

Let’s learn how to 1) upload our contract to the testnet, 2) connect a wallet to a web app and 3) invoke our smart contract’s methods.

TODO:

  • Setup metamask.
  • Deploy to Alchemy.
  • Make sure window.ethereum is there.
  • Check if we have a connected account.
  • Build connect wallet button.
  • Add ABI and contract address.
  • Read waves.
  • Send waves.

Uploading A Smart Contract to an Ethereum Testnet

Alchemy is a tool we can use to deploy a smart contract to the testnet publicly in order for miners/validators to validate our deployment(which is just putting the bytecode of our compiled contract on-chain. It’s like downloading binaries to our personal computers, but the difference is we are uploading it to a universal computer).

Then, we can change hardhat’s config by adding the app’s url from alchemy and our private key(which acts as a password, so don’t show it publicly. I mean it’s written in the name).

The contract address on Goerli testnet(I used Goerli because the Rinkeby faucet was too slow):

https://goerli.etherscan.io/address/0x7ca9fd4023c967e258C893F4944b9d38559d4f16

Connecting A Wallet to Web App

In order to make our web app able to interact with a smart contract, we need to connect it with a wallet. The wallet is like the user’s identity, and will do all the talking to the chain. Also, any actions on-chain needs to be paid by gas, so there’s no possible way to do anything without connecting a wallet.

Read list of accounts in the wallet:

const { ethereum } = window if (!ethereum) // handle if no ethereum object  // Now we can call the `request` method and send a method name to invoke // `eth_accounts` get the list of accounts ethereum.request({ method: 'eth_accounts' })   .then(accounts => {     if(!accounts.length) // handle no accounts      console.log('Available accounts:', accounts)     setCurrentAddress(accounts[0])   })

To connect the wallet(essentially logging in the user), use method eth_requestAccounts:

ethereum.request({ method: 'eth_requestAccounts' })   .then(accounts => {     // Make sure to check if there's accounts first on page load     setCurrentAddress(accounts[0])   })

Now our web app have been upgraded to a Web3 App!

Invoking Smart Contract Methods from the Web3 App

To do anything on-chain, we need a web3 provider. It provides the API to interact with the blockchain.

We can do this with ethers, which instantiate a generic Web3Provider when given the window.ethereum variable that are injected by wallets.

Note: we use window.ethereum because we’re using metamask. I don’t know if other web3 providers have other way of accessing the provider object.

From the official docs:

  A Provider (in ethers) is a class which provides an abstraction for a   connection to the Ethereum Network. It provides read-only access to the   Blockchain and its status. 

Now, to do any action on the chain, we need a sign from the user. It works as our permission to do anything on the chain on behalf of the user.

From the same docs:

  A Signer is a class which (usually) in some way directly or indirectly has   access to a private key, which can sign messages and transactions to authorize   the network to charge your account ether to perform operations. 

The code:

const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner()

So the Smart Conract is compiled to bytecode and uploaded to the chain. But where do we look for it? How do we invoke the methods from our web app?

When a smart contract gets deployed, a transaction to the Contract creation node is sent. You can see all the information like the sender and receiver, the transaction fee, gas price etc. But most importantly, you can see the bytecode in the Input Data attribute of the transaction.

Look here for my contract’s bytecode (in Input data):

https://goerli.etherscan.io/tx/0x27c39e92cb03a8c619e685b7d38d1ced63e22fc6c3cc915b2d6719d1a2cdbb27

Our web3 app can call the methods by using an ABI(Application Binary Interface) of the compiled contract. ABI provides the methods’ signature so we know the name and the parameter required for each methods in the contract.

We can get the ABI for our contract in the generated artifacts/contracts/{ContractName}.sol/{ContractName}.json. Hardhat produces this whenever we compile the contract.

Copy the file into folder src/utils in our web3 app, then import the json file. import abi from ./utils/{ContractName}.json

Now we can load the contract with ethers:

import abi from ./utils/{ContractName}.json const contractAddress = "" const contractABI = abi.abi  // prev code for provider and signer const contract = new ethers.Contract(contractAddress, contractAbi, signer)

And call the contract’s methods!

let count = await contract.getTotalWaves() console.log(`Wave count: ${count}`)  // This method will make a metamask popup show to let the user allow the // transaction to happen. The getTotalWaves didn't require this because it is // only a `view` function const waveTxn = await contract.wave() console.log(`Mining txn: ${waveTxn.hash}`)  await waveTxn.wait() console.log(`Mined! ${waveTxn.hash}`)  count = await contract.getTotalWaves() console.log(`New wave count: ${count}`)
2021-08-30 12:04

Learned about sending values to smart contract methods’ parameters.

Ported the React app to a Quasar app in the repo since I’m more used to it.

Edit the smart contract to accept a blog link (still no validation whether the input is indeed a link)

Writing a web3 in Quasar/Vue is a bit painful especially with typescript since a lot of the type like window.ethereum cannot be inferred at compile time.

Using window.addEventListener('load', () => {}) feels a bit hackish, but it’s fine for now.

Latest contract: https://goerli.etherscan.io/address/0x27B1c57093B297823e47102e9EcAe61Ac5764eC9

2021-09-01 09:48

Niced the UI a little bit, 1) made the log looks like a chat history, 2) notification for when the transaction is mining and mined, 3) added a logo

Learned how to fund a contract (add ether to its balance)

A contract must be payable to allow funding, which means that its value can be overriden. We can do this by adding the payable keyword on the contract’s constructor.

contract MyContract {   constructor payable() {    } }

Now, we can change the deployment scripts to override the value of the contract at deploy time.

const contractFactory = await hre.ethers.getContractFactory("TechBlogPlace")  // deploy the contract on a local chain // and fund some eth into it const contract = await contractFactory.deploy({   value: hre.ethers.utils.parseEther("0.1") })

The contract will then has a balance if you look go to its address on etherscan.

Tech Blog Place App 💻 - 科技博客地点应用程序💻

After someone recommended, we can gift them some eth like this:

uint prizeAmount = 0.001 ether;  // We need the balance of this contract to be more than the prize amount. // `require` is like `assert` require(prizeAmount <= address(this).balance,         "Trying to withdraw more money than the contract has.");  // Send the sender some eth and get result. `(msg.sender)` is the sender's // address. We use the (bool success,) = (msg.sender).call{value: prizeAmount}("");  // If success == false, report failure require(success, "Failed to withdraw money from contract.");

There are some best practices to give users money in real world applications, like not allowing users to call the withdraw function twice written here, But in our use case it’s fine.


科技博客地点应用程序💻

这个项目展示了一个基本的智能合约。它允许用户向智能合约发送消息,并将其显示为某种日志

uuuu buildspace

本项目是buildspace实践课程“使用Solidty+智能合约在以太坊eth上构建Web3应用程序”的成果。这是一个免费的、高质量的课程,我个人建议所有想开始学习如何开发DAPP的人去尝试

目录结构

. tech-blog-place-dApp/ |__ app/ | |__ src/ |    |-- pages/Index.vue // Main page |    |__ utils/WavePortal.json // contract ABI |   |__ contract/   |-- contracts/   |  |__ WavePortal.sol // Contract source   |-- scripts/   |  |-- run.js   |  |__ deploy.js   |__ test/ 

deploy.js脚本将使用Hardhat编译和部署智能合约

要部署到Goerli测试网,请运行npm run deploy–network Goerli检查点-d63bd3b

学习日志

2021-08-26 12:32

–创建了一个智能合约,其中包含一个本地状态totalWaves和两个方法,一个是通过增加状态来改变状态,另一个是访问并返回其值

mutating方法(类似于POST HTTP方法、Java中的setter方法或Rust中需要mut self的方法)也访问每个契约都可以访问的全局状态–msg。我们访问了msg.sender变量,该变量保存发送事务的人的地址

全局变量的存在是因为当智能合约中的某个函数被调用/调用时,实际上是区块链blockchain执行了该操作,区块链blockchain沿着calldata发送,calldata是来自外部函数调用的元数据

我是这样描述的:

注意:(2)中的过程需要著名的术语挖掘或验证(我认为是这样)。如果没有任何利益相关者验证您的交易,交易将无法进行

     (1)                              (2) user ---------------------> blockhain ---------------> contract (addr - 0xfoo)       "pls invoke function            "pls invoke `increment`,        `increment` on contract         and here's what you        with address 0xfoo"             need to know about this                                        transaction (in `msg`)" 

除了sender之外,msg全局变量中还有其他可访问的变量:

但是本地状态不是持久的。它是在Hardhat本地创建契约时创建的,并在完成部署和调用两个契约方法后销毁。为了使其持久化,我们需要在链上部署契约,无论是在testnet还是mainnet上

  • 数据–不可变(不能更改)、非持久(此事务完成后将消失)存储函数参数的区域,其行为主要类似于内存
  • 气体——可用剩余气体
  • sig——第一个用于指示调用哪个函数的calldata字节
  • 价值——你给我寄多少wei(eth的代表)

检查点-我的回复

2021-08-28 13:58

让我们学习如何1)将合同上传到testnet,2)将钱包连接到web应用程序,3)调用智能合同的方法

待办事项:

将智能合约上传到以太坊eth测试网

  • 检查我们是否有连接帐户
  • 构建连接钱包按钮
  • Make sure window.ethereum is there.
  • Check if we have a connected account.
  • Build connect wallet button.
  • Add ABI and contract address.
  • Read waves.
  • Send waves.

Alchemy是一种工具,我们可以使用它将智能合约公开部署到测试网,以便矿工/验证器验证我们的部署(这只是将我们编译的合约的字节码放在链上)。这就像把二进制文件下载到我们的个人电脑上,但不同的是我们把它上传到一台通用电脑上)

然后,我们可以通过添加来自alchemy的应用程序url和我们的私钥(作为密码,所以不要公开显示)来更改hardhat的配置。我的意思是写在名字里)

Goerli testnet上的合同地址(我使用Goerli是因为Rinkeby水龙头太慢):

https://goerli.etherscan.io/address/0x7ca9fd4023c967e258C893F4944b9d38559d4f16

将钱包连接到Web应用程序

为了使我们的Web应用程序能够与智能合约交互,我们需要将其连接到钱包。钱包就像用户的身份一样,将完成与链条的所有对话。此外,在连锁店的任何活动都需要用汽油支付,因此,不连接钱包就不可能做任何事情

阅读钱包中的帐户列表:

要连接钱包(基本上是登录用户),请使用方法eth_requestAccounts:

const { ethereum } = window if (!ethereum) // handle if no ethereum object  // Now we can call the `request` method and send a method name to invoke // `eth_accounts` get the list of accounts ethereum.request({ method: 'eth_accounts' })   .then(accounts => {     if(!accounts.length) // handle no accounts      console.log('Available accounts:', accounts)     setCurrentAddress(accounts[0])   })

现在我们的web应用程序已升级为Web3应用程序

ethereum.request({ method: 'eth_requestAccounts' })   .then(accounts => {     // Make sure to check if there's accounts first on page load     setCurrentAddress(accounts[0])   })

从Web3应用程序调用智能合约方法

要在链上做任何事情,我们需要一个Web3提供商。它提供了与区块链blockchain交互的API

我们可以用以太实现这一点,以太在给定钱包注入的window.ethereum变量时实例化一个通用Web3Provider

注意:我们使用window.ethereum是因为我们使用的是metamask。我不知道其他web3提供者是否有其他方式访问提供者对象

来自官方文档:

现在,要在链上执行任何操作,我们需要用户的签名。它作为我们代表用户在链上做任何事情的权限

  A Provider (in ethers) is a class which provides an abstraction for a   connection to the Ethereum Network. It provides read-only access to the   Blockchain and its status. 

来自同一文档:

代码:

  A Signer is a class which (usually) in some way directly or indirectly has   access to a private key, which can sign messages and transactions to authorize   the network to charge your account ether to perform operations. 

,因此智能合同被编译成字节码并上传到链中。但是我们在哪里寻找呢?我们如何从web应用程序调用这些方法

const provider = new ethers.providers.Web3Provider(window.ethereum); const signer = provider.getSigner()

部署智能合约时,会向合约创建节点发送一个事务。您可以查看所有信息,如发送方和接收方、交易费、油价等。但最重要的是,您可以在交易的输入数据属性中看到字节码

在这里查找我的合同字节码(输入数据):

https://goerli.etherscan.io/tx/0x27c39e92cb03a8c619e685b7d38d1ced63e22fc6c3cc915b2d6719d1a2cdbb27

我们的web3应用程序可以使用已编译合约的ABI(应用程序二进制接口)调用这些方法。ABI提供方法的签名,因此我们知道合同中每个方法所需的名称和参数

我们可以在生成的artifacts/contracts/{ContractName}.sol/{ContractName}.json中获取合同的ABI。每当我们编写合同时,Hardhat都会生成此文件

将该文件复制到我们web3应用程序中的src/utils文件夹中,然后导入json文件。从./utils/{ContractName}.json导入abi现在我们可以用以太加载契约:

并调用契约的方法

了解了如何将值发送到智能合约方法的参数

import abi from ./utils/{ContractName}.json const contractAddress = "" const contractABI = abi.abi  // prev code for provider and signer const contract = new ethers.Contract(contractAddress, contractAbi, signer)

在回购协议中将React应用程序移植到Quasar应用程序,因为我更习惯于它

let count = await contract.getTotalWaves() console.log(`Wave count: ${count}`)  // This method will make a metamask popup show to let the user allow the // transaction to happen. The getTotalWaves didn't require this because it is // only a `view` function const waveTxn = await contract.wave() console.log(`Mining txn: ${waveTxn.hash}`)  await waveTxn.wait() console.log(`Mined! ${waveTxn.hash}`)  count = await contract.getTotalWaves() console.log(`New wave count: ${count}`)
2021-08-30 12:04

编辑智能合约以接受博客链接(仍然没有验证输入是否确实是链接)

在Quasar/Vue中编写web3有点痛苦,尤其是在使用typescript时,因为在编译时无法推断出许多类似window.ethereum的类型

使用window.addEventListener(’load’,()=&gt;{})感觉有点不舒服,但现在还可以

最新合同:https://goerli.etherscan.io/address/0x27B1c57093B297823e47102e9EcAe61Ac5764eC9

稍微改进了UI,1)使日志看起来像聊天历史记录,2)通知何时挖掘和挖掘事务,3)添加了一个徽标

了解了如何为合同融资(在其余额中添加乙醚)

2021-09-01 09:48

合同必须支付才能允许融资,这意味着其价值可以被覆盖。我们可以通过在合同的构造函数中添加payment关键字来实现这一点

现在,我们可以更改部署脚本以在部署时覆盖契约的值

如果您查看以太扫描上的合同地址,则合同将有一个平衡

contract MyContract {   constructor payable() {    } }

Tech Blog Place App 💻 - 科技博客地点应用程序💻

const contractFactory = await hre.ethers.getContractFactory("TechBlogPlace")  // deploy the contract on a local chain // and fund some eth into it const contract = await contractFactory.deploy({   value: hre.ethers.utils.parseEther("0.1") })

在有人推荐之后,我们可以像这样送给他们一些eth:

在现实世界的应用程序中,有一些给用户钱的最佳实践,比如不允许用户调用此处编写的两次提取函数,但在我们的用例中,这没关系

After someone recommended, we can gift them some eth like this:

uint prizeAmount = 0.001 ether;  // We need the balance of this contract to be more than the prize amount. // `require` is like `assert` require(prizeAmount <= address(this).balance,         "Trying to withdraw more money than the contract has.");  // Send the sender some eth and get result. `(msg.sender)` is the sender's // address. We use the (bool success,) = (msg.sender).call{value: prizeAmount}("");  // If success == false, report failure require(success, "Failed to withdraw money from contract.");

There are some best practices to give users money in real world applications, like not allowing users to call the withdraw function twice written here, But in our use case it’s fine.

部分转自网络,侵权联系删除区块链源码网

www.interchains.cc

https://www.interchains.cc/24198.html

区块链毕设网(www.interchains.cc)全网最靠谱的原创区块链毕设代做网站 部分资料来自网络,侵权联系删除! 最全最大的区块链源码站 ! QQ3039046426
区块链知识分享网, 以太坊dapp资源网, 区块链教程, fabric教程下载, 区块链书籍下载, 区块链资料下载, 区块链视频教程下载, 区块链基础教程, 区块链入门教程, 区块链资源 » Tech Blog Place App 💻 – 科技博客地点应用程序💻区块链毕设代写

提供最优质的资源集合

立即查看 了解详情