实现mint操作(参考pancake)
区块链发展越来越好,nft已经火了很久,今天写一下如何用js、web3js、调用合约,实现mint nft。
简单的调用:
//引入一些依赖 (根据需要,有一些是其他功能的)
import useActiveWeb3React from './web3/hooks/useActiveWeb3React';
import { getNftContract } from './web3/utils/contractHelpers';
import React, { useEffect, useState } from 'react';
import { useIntl, getLocale } from 'umi';
import { Web3Provider } from '@ethersproject/providers';
import Web3 from 'web3';
import { injected } from './web3';
import { useWeb3React } from '@web3-react/core';
import { Web3ReactProvider } from '@web3-react/core';
import { setupNetwork } from './web3/wallet';
import { InjectedConnector } from '@web3-react/injected-connector';
import { default as Abi } from './web3/abi/nft.json';
import type { AbiItem } from 'web3-utils';
import BigNumber from 'bignumber.js/bignumber';
import { useCallWithGasPrice } from './web3/hooks/useCallWithGasPrice';const spenderAddress = '合约地址';const abiType = (abi: unknown): AbiItem => abi as AbiItem;//abi文件const contract = new web3.eth.Contract(abiType(Abi), spenderAddress);// 可以获取一些数据const name = await contract.methods.name().call();const symbol = await contract.methods.symbol().call();const owner = await contract.methods.owner().call();// const balanceOf = await contract.methods.balanceOf(account).call();// const isApprovedForAll = await contract.methods// .isApprovedForAll(account, spenderAddress)// .call();// const isApprovedForAll = await contract.methods.isApprovedForAll(account, spenderAddress).call();// mint
await depositContract.mintTo(account, {value: web3.utils.toWei('0.01', 'ether'),gasLimit: DEFAULT_GAS_LIMIT,
});// 以上简单的调用就可以mint
下面是进阶版,使用了一些pancake的代码:
1.配置Web3ReactProvider
import React from 'react';
import { Web3Provider } from '@ethersproject/providers';
import { Web3ReactProvider } from '@web3-react/core';
import App from './app';const Page = () => {const POLLING_INTERVAL = 12000;const getLibrary = (provider): Web3Provider => {const library = new Web3Provider(provider);library.pollingInterval = POLLING_INTERVAL;return library;};return (<Web3ReactProvider getLibrary={getLibrary}><App /></Web3ReactProvider>);
};export default Page;
2.功能页面:
import './app.less';
import { useMemo } from 'react';
import useActiveWeb3React from './web3/hooks/useActiveWeb3React';
import { getNftContract } from './web3/utils/contractHelpers';
import React, { useEffect, useState } from 'react';
import { useIntl, getLocale } from 'umi';
import styles from './app.less';
import { Button, message } from 'antd';
import { Web3Provider } from '@ethersproject/providers';
import { injected } from './web3';
import { useWeb3React } from '@web3-react/core';
import { setupNetwork } from './web3/wallet';
import BigNumber from 'bignumber.js/bignumber';
import { useCallWithGasPrice } from './web3/hooks/useCallWithGasPrice';const DEFAULT_GAS_LIMIT = 380000;const Page = () => {const intl = useIntl();const context = useWeb3React<Web3Provider>();const {connector,library,chainId,account,activate,deactivate,active,error,} = context;useEffect(() => {if (localStorage.getItem('isActivate')) {connect();}}, []);async function connect() {if (typeof window.ethereum === 'undefined') {message.warning({content: intl.formatMessage({ id: 'pass.text.metamask.install' }),style: {marginTop: '10vh',},});} else {try {const hasSetup = await setupNetwork();if (hasSetup) {await activate(injected);localStorage.setItem('isActivate', 'true');}} catch (ex) {console.log(ex);}}}const spenderAddress = '0xbfb6C22b363d06c64bdff5a890Ff73FB6Cb7242F';const BIG_TEN = new BigNumber(10);const useVault = (address: string) => {const { library } = useActiveWeb3React();return useMemo(() => getNftContract(address, library.getSigner()),[address, library],);};const mint = async () => {try {const amount = new BigNumber(1).times(BIG_TEN.pow(18)).toString();handleDeposit(amount);} catch (error) {if (error) {console.info('error', error);}}};const depositContract = useVault(spenderAddress);const { callWithGasPrice } = useCallWithGasPrice();const handleDeposit = async (depositAmount: any) => {const callOptionsETH = {gasLimit: DEFAULT_GAS_LIMIT,value: depositAmount.toString(),};try {const tx = await callWithGasPrice(depositContract,'mintTo',[account],callOptionsETH,);const receipt = await tx.wait();console.info(receipt);if (receipt.status) {message.success({content: intl.formatMessage({ id: 'pass.text.success' }),style: {marginTop: '10vh',},});}} catch (error) {console.info('error', error);message.error({content: intl.formatMessage({ id: 'pass.text.mint.error' }),style: {marginTop: '10vh',},});} finally {}};return (<><div className={styles['wmx-pass-content1']}><div className={styles['wmx-pass-content1-left']}><div className={styles['wmx-pass-content1-left1']}><div className={styles['wmx-pass-content1-left2']}><p className={styles['wmx-pass-content1-price']}>{intl.formatMessage({id: 'pass.text.price',})}</p>{active ? (<ButtonclassName={styles['wmx-pass-content1-button1']}onClick={mint}>Mint</Button>) : (<ButtonclassName={styles['wmx-pass-content1-button']}onClick={connect}>{intl.formatMessage({id: 'pass.text.metamask',})}</Button>)}</div></div></div></div></>);
};export default Page;
3.接下来是一些其他文件:
(省略,先不写了,感兴趣留言)
基本和开源代码一致