简体   繁体   中英

How to create a transaction using web3 or ethers.js without setting private_key

What i am trying to do:

Building a small app that allows a user to purchase a service for a set amount of tokens. For example, 100 tokens for service A, 500 tokens for service B. This will be for a custom token on the harmony blockchain.

What i know: I already know how to connect to metamask and get the users address. Signer and provider are available to me.

What confuses me: Examples and documentation all refer to a private_key and creating a wallet, i don't need to do that, i need to use the users existing wallet.

What i need to do:

  1. Prompt a transaction in the user wallet (harmony one or metamask) for a set amount of tokens.

  2. Check if the user has required balance (seems trivial knowing i can read their balance).

  3. Make the transaction. Also seems ok after reading the docs.

  4. Get a receipt, then call a callback/my code. Again, seems ok after reading the docs.

All pretty straight forward, but again - every document i read always refers to setting a private key - surely i don't need to do this?

A transaction always needs to be signed by a private key generating the sender address. Otherwise it's rejected by the network.

Examples and documentation all refer to a private_key and creating a wallet, i don't need to do that, i need to use the users existing wallet.

every document i read always refers to setting a private key - surely i don't need to do this?

A backend approach is to import the private key to the app and use it to sign the transaction.

However, there's also a frontend approach: Send a request to a wallet browser extension to sign the transaction and broadcast it to the network. The wallet extension then pops up a window and lets the user chose whether they want to sign the transaction (with their private key, not shared with the app) and broadcast it - or not.

You can find an example of such request in the MetaMask docs page .

An advantage of this approach is that your app doesn't need to ask for the user's private key. A disadvantage is that if the user haven't installed a browser wallet compatible with your app, they can't send the transaction (or at least not so easily).


Note: I'm not familiar with the Harmony wallet, but I'm assuming it works in a similar way as MetaMask - because Harmony is an EVM-compatible network, and MetaMask only supports EVM-compatible networks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM