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

发布于 2025-01-11 07:00:01 字数 1113 浏览 0 评论 0原文

我在 opensea 上铸造了一些 NFT。这些位于 Polygon 孟买网络上。现在我想使用alchemy web3将这些token转移到其他地址。这是我正在使用的代码。

注意:这应该在 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("
              

I have minted some NFTs on opensea. These are on Polygon Mumbai network. Now I want to transfer these to token to other addresses using 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.

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();

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

画离情绘悲伤 2025-01-18 07:00:01

假设您的浏览器中安装了 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();

Assumed that you have Metamask installed in your browser, and that the NFT smart contract follows ERC721 Standard

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();
少钕鈤記 2025-01-18 07:00:01

遇到同样的问题,因为没有转移 NFT 代币的示例。
有一个很好解释的 3 部分示例 在以太坊网站上铸造 NFT。

在第一部分中, 步骤10,解释了如何编写合约,并提到了合约对象扩展中现有的方法:

在导入语句之后,我们有了自定义的 NFT 智能合约,它非常短——它只包含一个计数器、一个构造函数和一个函数!这要归功于我们继承的 OpenZeppelin 合约,它实现了我们创建 NFT 所需的大部分方法,例如,ownerOf 返回 NFT 的所有者,以及 transferFrom,它转移 NFT 的所有权NFT 从一个账户转移到另一个账户。

因此,利用这些信息,我使用我的 Metamask 移动应用程序在两个地址之间进行了 NFT 转账交易。然后我通过 etherscan API 搜索了该交易的 JSON。

通过这种方式,我能够使用 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)

    })
}

Had the same problem, because there is no example on transferring NFT token.
There is a well explained 3-parts-example on ethereum website to mint an 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:

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! 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.

So, with these informations, I made an NFT transfer transaction between two addresses with my metamask mobile app. Then I searched the JSON of this transaction through etherscan API.

In this way, I was able to transfer tokens to other addresses using alchemy web3 with this script:

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)

    })
}
染年凉城似染瑾 2025-01-18 07:00:01

我也有同样的问题。我需要在node.js后端传输NFT。
我使用网络提供商来使用 Moralis NetworkWeb3Connector

这是我的存储库例如:
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);
  }

您可以在
中获取速度节点api密钥
Moralis仪表板>网络> Eth Rinkeby(就我而言)>设置

屏幕截图

I Had the same problem. I need to transfer NFT in node.js back-end.
I use network provider to use Moralis NetworkWeb3Connector.

here's my repository for example:
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
Moralis dashboad > Networks > Eth Rinkeby(in my case) > Settings

screenshot

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文