123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102 |
- import erc721ABI from './erc721ABI.json'
- import {
- ethers,
- ContractTransactionResponse,
- ContractTransactionReceipt,
- } from 'ethers'
- import WrappedContract from './base'
- interface NFTTokenURI {
- id: number
- uri: string
- }
- export default class Erc72TokenContract extends WrappedContract {
- constructor(address: string, provider: ethers.Signer) {
- super(erc721ABI, address, provider)
- }
- getInstance(): ethers.Contract {
- return new ethers.Contract(this.address, this.ABI as any, this.provider)
- }
- async balanceOf(address: string): Promise<number> {
- const contract = this.getInstance()
- const bn = await contract.balanceOf(address)
- return parseInt(bn)
- }
- async tokenOfOwnerByIndex(address: string, index: number): Promise<number> {
- const contract = this.getInstance()
- const bn = await contract.tokenOfOwnerByIndex(address, index)
- return parseInt(bn)
- }
- async tokenURI(tokenId: number): Promise<string> {
- const contract = this.getInstance()
- return await contract.tokenURI(tokenId)
- }
- async safeTransferFrom(
- addressFrom: string,
- addressTo: string,
- tokenId: number
- ): Promise<ContractTransactionReceipt> {
- const contract = this.getInstance()
- const method = contract['safeTransferFrom(address,address,uint256)']
- const tx: ContractTransactionResponse = await method(
- addressFrom,
- addressTo,
- tokenId
- )
- const txwait = await tx.wait()
- if (!txwait) {
- throw new Error('Transaction failed')
- }
- return txwait
- }
- async approve(
- addressTo: string,
- tokenId: number
- ): Promise<ContractTransactionReceipt> {
- const contract = this.getInstance()
- const tx: ContractTransactionResponse = await contract.approve(
- addressTo,
- tokenId
- )
- const txwait = await tx.wait()
- if (!txwait) {
- throw new Error('Transaction failed')
- }
- return txwait
- }
- async getApproved(tokenId: number): Promise<string> {
- const contract = this.getInstance()
- return await contract.getApproved(tokenId)
- }
- // other
- async tokenIdsOf(address: string): Promise<number[]> {
- const count = await this.balanceOf(address)
- const list: number[] = []
- for (let i = 0; i < count; i++) {
- list[i] = await this.tokenOfOwnerByIndex(address, i)
- }
- return list
- }
- async tokenURIListOf(address: string): Promise<NFTTokenURI[]> {
- const ids = await this.tokenIdsOf(address)
- const list: NFTTokenURI[] = []
- for (let i = 0; i < ids.length; i++) {
- const uri = await this.tokenURI(ids[i])
- list[i] = {
- id: ids[i],
- uri,
- }
- }
- return list
- }
- }
|