简体   繁体   English

如何使用炼金术发送已经铸造的 NFT

[英]How to send already minted NFT using alchemy

I have minted some NFTs on opensea.我在 opensea 上铸造了一些 NFT。 These are on Polygon Mumbai network.这些在 Polygon Mumbai 网络上。 Now I want to transfer these to token to other addresses using alchemy web3.现在我想使用 alchemy web3 将这些令牌转移到其他地址。 Here is the code I am using.这是我正在使用的代码。

Note : This is supposed to run in nodejs restful API, so there is no wallet available that why I am manually signing the transaction.注意:这应该在 nodejs restful API 中运行,所以没有可用的钱包,这就是我手动签署交易的原因。

async function main() {
  require('dotenv').config();
  const { API_URL,API_URL_TEST, PRIVATE_KEY } = process.env;
  const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
  const web3 = createAlchemyWeb3(API_URL_TEST);
  const myAddress = '*************************'
  const nonce = await web3.eth.getTransactionCount(myAddress, 'latest');
  const transaction = { //I believe transaction object is not correct, and I dont know what to put here
      'asset': {
        'tokenId': '******************************',//NFT token id in opensea
      },
      'gas': 53000,
      'to': '***********************', //metamask address of the user which I want to send the NFT
      'quantity': 1,
      'nonce': nonce,

    }
 
  const signedTx = await web3.eth.accounts.signTransaction(transaction, PRIVATE_KEY);
  web3.eth.sendSignedTransaction(signedTx.rawTransaction, function(error, hash) {
  if (!error) {
    console.log("🎉 The hash of your transaction is: ", hash, "\n Check Alchemy's Mempool to view the status of your transaction!");
  } else {
    console.log("❗Something went wrong while submitting your transaction:", error)
  }
 });
}
main();

Assumed that you have Metamask installed in your browser, and that the NFT smart contract follows ERC721 Standard假设您在浏览器中安装了 Metamask,并且 NFT 智能合约遵循ERC721 标准

const { API_URL,API_URL_TEST, PRIVATE_KEY } = process.env;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const {abi} = YOUR_CONTRACT_ABI

const contract_address = CONTRACT ADDRESS
require('dotenv').config();


async function main() {
  const web3 = createAlchemyWeb3(API_URL_TEST);  
 web3.eth.getAccounts().then(accounts => {
    const account = account[0]
    const nameContract = web3.eth.Contract(abi, contract_address);
    nameContract.methods.transfer(account, ADDRESS_OF_WALLET_YOU_WANT_TO_SEND_TO, TOKEN_ID).send();
 })
.catch(e => console.log(e));
}
main();

Had the same problem, because there is no example on transferring NFT token.有同样的问题,因为没有转移 NFT 代币的例子。 There is a well explained 3-parts-example on ethereum website to mint an NFT. 以太坊网站上有一个很好解释的 3 部分示例来铸造 NFT。

In the first part, step 10 , it explains how to write a contract and also mentions the existing methods in the contract object extended:在第一部分第 10 步中,它解释了如何编写合约,还提到了扩展的合约对象中的现有方法:

After our import statements, we have our custom NFT smart contract, which is surprisingly short — it only contains a counter, a constructor, and single function!在我们的 import 语句之后,我们有我们的自定义 NFT 智能合约,它非常短——它只包含一个计数器、一个构造函数和一个函数! This is thanks to our inherited OpenZeppelin contracts, which implement most of the methods we need to create an NFT, such as ownerOf which returns the owner of the NFT, and transferFrom , which transfers ownership of the NFT from one account to another .这要归功于我们继承的 OpenZeppelin 合约,它实现了我们创建 NFT 所需的大部分方法,例如 ownerOf 返回 NFT 的所有者,以及transferFrom将 NFT 的所有权从一个账户转移到另一个账户

So, with these informations, I made an NFT transfer transaction between two addresses with my metamask mobile app.因此,有了这些信息,我使用我的 metamask 移动应用程序在两个地址之间进行了 NFT 转账交易。 Then I searched the JSON of this transaction through etherscan API .然后我通过etherscan API搜索了这个交易的 JSON。

In this way, I was able to transfer tokens to other addresses using alchemy web3 with this script:通过这种方式,我能够通过以下脚本使用 alchemy web3 将代币转移到其他地址:

require("dotenv").config()
const API_URL = process.env.API_URL; //the alchemy app url
const PUBLIC_KEY = process.env.PUBLIC_KEY; //my metamask public key
const PRIVATE_KEY = process.env.PRIVATE_KEY;//my metamask private key
const {createAlchemyWeb3} = require("@alch/alchemy-web3")
const web3 = createAlchemyWeb3(API_URL)

const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json")//this is the contract created from ethereum example site

const contractAddress = "" // put here the contract address

const nftContract = new web3.eth.Contract(contract.abi, contractAddress)


/**
 * 
 * @param tokenID the token id we want to exchange
 * @param to the metamask address will own the NFT
 * @returns {Promise<void>}
 */
async function exchange(tokenID, to) {
    const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY,         'latest');
//the transaction
const tx = {
    'from': PUBLIC_KEY,
    'to': contractAddress,
    'nonce': nonce,
    'gas': 500000,
    'input': nftContract.methods.safeTransferFrom(PUBLIC_KEY, to, tokenID).encodeABI() //I could use also transferFrom
};
const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY)

signPromise

    .then((signedTx) => {

        web3.eth.sendSignedTransaction(
            signedTx.rawTransaction,

            function (err, hash) {

                if (!err) {

                    console.log(
                        "The hash of your transaction is: ",

                        hash,

                        "\nCheck Alchemy's Mempool to view the status of your transaction!"
                    )

                } else {

                    console.log(
                        "Something went wrong when submitting your transaction:",

                        err
                    )

                }

            }
        )

    })

    .catch((err) => {

        console.log(" Promise failed:", err)

    })
}

I Had the same problem.我有同样的问题。 I need to transfer NFT in node.js back-end.我需要在 node.js 后端传输 NFT。
I use network provider to use Moralis NetworkWeb3Connector .我使用网络提供商来使用 Moralis NetworkWeb3Connector

here's my repository for example: https://github.com/HanJaeJoon/Web3API/blob/2e30e89e38b7b1f947f4977a0fe613c882099fbc/views/index.ejs#L259-L275这是我的存储库,例如: https ://github.com/HanJaeJoon/Web3API/blob/2e30e89e38b7b1f947f4977a0fe613c882099fbc/views/index.ejs#L259-L275

  await Moralis.start({
    serverUrl,
    appId,
    masterKey,
  });

  await Moralis.enableWeb3({
    // rinkeby
    chainId: 0x4,
    privateKey: process.env.PRIVATE_KEY,
    provider: 'network',
    speedyNodeApiKey: process.env.MORALIS_SPEEDY_NODE_API_KEY,
  });

  const options = {
    type,
    receiver,
    contractAddress,
    tokenId,
    amount: 1,
  };

  try {
    await Moralis.transfer(options);
  } catch (error) {
    console.log(error);
  }

you can get speed node api key in您可以获取速度节点 api 密钥
Moralis dashboad > Networks > Eth Rinkeby(in my case) > Settings Moralis 仪表板 > 网络 > Eth Rinkeby(在我的情况下)> 设置

screenshot截屏

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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