All files Foundation.ts

28.32% Statements 100/353
100% Branches 5/5
14.28% Functions 1/7
28.32% Lines 100/353

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 3541x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 7x 7x 7x 8x 3x 3x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x           1x 1x                                                                                                                                     1x 1x 1x                                                                                                                                                                                                       1x 1x                                                                                                                                                         1x 1x           1x 1x      
import {
  CHAIN_TO_CONTRACT_1155,
  CHAIN_TO_CONTRACT_ADDRESS,
  DUTCH_AUCTION_FRAGMENT,
  FIXED_PRICE_FRAGMENTS,
  MINT_MULTI_TOKEN,
  NFT_MARKET_BASE,
  REFERRAL_ADDRESS,
} from './constants'
import {
  calculateFees,
  getContractType,
  getDutchAuctionData,
  getFixedPriceData,
  getFixedPriceSaleTerms,
  getSaleTermsId,
} from './utils'
import {
  type MintActionParams,
  type TransactionFilter,
  compressJson,
} from '@rabbitholegg/questdk'
import {
  Chains,
  DEFAULT_ACCOUNT,
  formatAmount,
  getMintAmount,
  type MintIntentParams,
  chainIdToViemChain,
} from '@rabbitholegg/questdk-plugin-utils'
import {
  type Address,
  type PublicClient,
  type SimulateContractReturnType,
  type TransactionRequest,
  createPublicClient,
  encodeFunctionData,
  http,
  parseEther,
  zeroAddress,
} from 'viem'
 
export const mint = async (
  mint: MintActionParams,
): Promise<TransactionFilter> => {
  const { chainId, contractAddress, amount, recipient, tokenId } = mint
 
  // 721
  const dropFactoryAddress = CHAIN_TO_CONTRACT_ADDRESS[chainId]
 
  if (!dropFactoryAddress) {
    throw new Error('Invalid chainId')
  }
 
  const contracts = [dropFactoryAddress.toLowerCase()]
 
  if (chainId === Chains.BASE) {
    contracts.push(NFT_MARKET_BASE.toLowerCase())
  }
 
  return compressJson({
    chainId,
    to: {
      $or: contracts,
    },
    input: {
      $or: [
        {
          // 721
          $abi: [...FIXED_PRICE_FRAGMENTS, DUTCH_AUCTION_FRAGMENT],
          count: formatAmount(amount),
          nftContract: contractAddress,
          nftRecipient: recipient,
        },
        {
          // 1155 NFTMarketRouter
          $abi: [MINT_MULTI_TOKEN],
          multiTokenCollection: contractAddress,
          tokenRecipient: recipient,
          tokenQuantities: {
            $some: { tokenId, quantity: formatAmount(amount) },
          },
        },
      ],
    },
  })
}
 
export const getProjectFees = async (
  mint: MintActionParams,
): Promise<bigint> => {
  const fees = await getFees(mint)
  return fees.projectFee + fees.actionFee
}
 
export const getFees = async (
  mint: MintActionParams,
): Promise<{ actionFee: bigint; projectFee: bigint }> => {
  const { chainId, contractAddress, amount } = mint

  const client = createPublicClient({
    chain: chainIdToViemChain(chainId),
    transport: http(),
  }) as PublicClient

  const contractType = await getContractType(client, contractAddress)
  const quantityToMint = getMintAmount(amount)

  if (contractType === '721') {
    const dropFactoryAddress = CHAIN_TO_CONTRACT_ADDRESS[chainId]
    try {
      const fixedPriceResult = await getFixedPriceData(
        client,
        dropFactoryAddress,
        contractAddress,
      )

      if (fixedPriceResult.seller === zeroAddress) {
        const dutchAuctionResult = await getDutchAuctionData(
          client,
          dropFactoryAddress,
          contractAddress,
        )
        return calculateFees(dutchAuctionResult, quantityToMint)
      }

      return calculateFees(fixedPriceResult, quantityToMint)
    } catch (err) {
      console.error(err)
    }
  }

  if (contractType === '1155') {
    const multiTokenAddress = CHAIN_TO_CONTRACT_1155[chainId]
    try {
      const salesTermId = await getSaleTermsId(mint, multiTokenAddress)

      if (salesTermId == null) {
        throw new Error('Sale terms ID not found')
      }

      const saleTerms = await getFixedPriceSaleTerms(
        client,
        salesTermId,
        multiTokenAddress,
      )
      const actionFee = saleTerms.pricePerQuantity * quantityToMint
      const projectFee =
        (saleTerms.creatorRevenuePerQuantity +
          saleTerms.referrerRewardPerQuantity +
          saleTerms.worldCuratorRevenuePerQuantity +
          saleTerms.protocolFeePerQuantity) *
        quantityToMint
      return { actionFee, projectFee }
    } catch {}
  }
  // return fallback if any errors occur
  return {
    actionFee: parseEther('0'),
    projectFee: parseEther('0.0008') * quantityToMint,
  }
}
 
// this function is deprecated
export const getMintIntent = async (
  mint: MintIntentParams,
): Promise<TransactionRequest> => {
  const { chainId, contractAddress, tokenId, amount, recipient } = mint

  const client = createPublicClient({
    chain: chainIdToViemChain(chainId),
    transport: http(),
  }) as PublicClient

  const contractType = await getContractType(client, contractAddress)
  const mintAmount = getMintAmount(amount)

  if (contractType === '721') {
    const dropFactoryAddress = CHAIN_TO_CONTRACT_ADDRESS[chainId]

    if (tokenId) {
      throw new Error('Token ID is not supported for Foundation Mints')
    }

    // check if the mint function is fixed or dutch auction type
    const { seller: fixedPriceSeller } = await getFixedPriceData(
      client,
      dropFactoryAddress,
      contractAddress,
    )
    if (fixedPriceSeller && fixedPriceSeller !== zeroAddress) {
      const mintArgs = [
        contractAddress,
        mintAmount,
        recipient,
        REFERRAL_ADDRESS,
        [],
      ]

      const data = encodeFunctionData({
        abi: FIXED_PRICE_FRAGMENTS,
        functionName: 'mintFromFixedPriceSaleWithEarlyAccessAllowlistV2',
        args: mintArgs,
      })

      return {
        from: recipient,
        to: contractAddress,
        data,
      }
    }

    const { seller: dutchAuctionSeller } = await getDutchAuctionData(
      client,
      dropFactoryAddress,
      contractAddress,
    )
    if (dutchAuctionSeller && dutchAuctionSeller !== zeroAddress) {
      const mintArgs = [contractAddress, mintAmount, recipient]

      const data = encodeFunctionData({
        abi: [DUTCH_AUCTION_FRAGMENT],
        functionName: 'mintFromDutchAuctionV2',
        args: mintArgs,
      })

      return {
        from: recipient,
        to: contractAddress,
        data,
      }
    }
  }

  if (contractType === '1155') {
    const multiTokenAddress = CHAIN_TO_CONTRACT_1155[chainId]
    const salesTermId = await getSaleTermsId(mint, multiTokenAddress)

    if (salesTermId == null) {
      throw new Error('Sale terms ID not found')
    }
    const mintArgs = [
      contractAddress,
      [{ tokenId, quantity: 1n }],
      recipient,
      REFERRAL_ADDRESS,
    ]

    const data = encodeFunctionData({
      abi: [MINT_MULTI_TOKEN],
      functionName: 'mintMultiTokensFromFreeFixedPriceSale',
      args: mintArgs,
    })

    return {
      from: recipient,
      to: contractAddress,
      data,
    }
  }

  // if no results, throw an error
  throw new Error('Invalid mint arguments')
}
 
export const simulateMint = async (
  mint: MintIntentParams,
  value: bigint,
  account?: Address,
  client?: PublicClient,
): Promise<SimulateContractReturnType> => {
  const { chainId, contractAddress, amount, recipient, tokenId } = mint

  const _client =
    client ||
    (createPublicClient({
      chain: chainIdToViemChain(chainId),
      transport: http(),
    }) as PublicClient)

  const contractType = await getContractType(_client, contractAddress)

  const mintAmount = getMintAmount(amount)

  if (contractType === '721') {
    if (tokenId) {
      throw new Error('Token ID is not supported for Foundation Mints')
    }
    const dropFactoryAddress = CHAIN_TO_CONTRACT_ADDRESS[chainId]

    // check if the mint function is fixed type
    const { seller: fixedPriceSeller } = await getFixedPriceData(
      _client,
      dropFactoryAddress,
      contractAddress,
    )
    if (fixedPriceSeller && fixedPriceSeller !== zeroAddress) {
      const result = await _client.simulateContract({
        address: dropFactoryAddress,
        value,
        abi: FIXED_PRICE_FRAGMENTS,
        functionName: 'mintFromFixedPriceSaleWithEarlyAccessAllowlistV2',
        args: [contractAddress, mintAmount, recipient, REFERRAL_ADDRESS, []],
        account: account || DEFAULT_ACCOUNT,
      })
      return result
    }

    // check if the mint function is dutch auction type
    const { seller: dutchAuctionSeller } = await getDutchAuctionData(
      _client,
      dropFactoryAddress,
      contractAddress,
    )
    if (dutchAuctionSeller && dutchAuctionSeller !== zeroAddress) {
      // Not supported due to the way we calculate fees.
      // https://github.com/rabbitholegg/questdk-plugins/pull/445#pullrequestreview-2111167218
      throw new Error('Dutch auction is not supported')
    }

    throw new Error('Invalid mint arguments')
  }

  if (contractType === '1155') {
    // try NFTMarket contract first
    const result = await _client.simulateContract({
      address: NFT_MARKET_BASE,
      value,
      abi: [MINT_MULTI_TOKEN],
      functionName: 'mintMultiTokensFromFreeFixedPriceSale',
      args: [
        contractAddress,
        [[tokenId ?? 1, mintAmount]],
        recipient,
        REFERRAL_ADDRESS,
      ],
      account: account || DEFAULT_ACCOUNT,
    })
    return result
  }
  throw new Error('Invalid contract type')
}
 
export const getSupportedTokenAddresses = async (
  _chainId: number,
): Promise<Address[]> => {
  // Not used for Mint Action
  return []
}
 
export const getSupportedChainIds = async (): Promise<number[]> => {
  return [Chains.ETHEREUM, Chains.BASE]
}