The MarketProvider follows the same principles as the TzombiesProvider. This page will cover only the specifics for this provider. If you would like to view the full code, it is available on the repository.
const fetchMarketplaceApproval = useCallback(async () => {
if (!account || !fa2) {
setIsApproved(false)
return
}
const arg = new operator_for_all_key(
new Address(process.env.NEXT_PUBLIC_MARKET_ADDRESS!),
new Address(account.address)
)
const approved = await fa2.get_operator_for_all_value(arg)
setIsApproved(!!approved)
}, [account, fa2])
Fetch sales
This one is a bit more tricky. If you remember, the marketplace contract does not (and cannot) check all aspects of valid orders, as it is loosely coupled with the token contract. We need to filter out empty or expired orders.
We have a counter: next_order_id. We'll use it to iterate over the orders.
const fetchListings = useCallback(async () => {
if (!market || !fa2 || !fa2.address) return
const nOrders = await market.get_next_order_id()
const listings: Listing[] = []
const inventories: Map<Address, UserInventory> = new Map()
for (let i = 1; i < nOrders.to_number(); i++) {
const order = await market.get_order_value(new Nat(i))
if (!order) continue
// filter out expired orders
if (new Date(order.expiry) < new Date()) continue
// check how many tokens the seller still has
if (!inventories.has(order.seller)) {
inventories.set(order.seller, await fetchFa2Balance(order.seller))
}
const amount = inventories
.get(order.seller)
?.get(order.token_id.to_number())
const qty = Math.min(order.amount.to_number(), amount ?? 0)
if (qty < 1) continue
listings.push({
saleId: i,
seller: order.seller,
parameters: {
tokenId: order.token_id.to_number(),
amount: qty,
price: order.price.to_big_number().toNumber(),
expiry: order.expiry,
},
})
}
setListings(listings)
}, [fa2, fetchFa2Balance, market])