Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🔧 bsx/snek offers composition api #6633

Merged
merged 6 commits into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
215 changes: 139 additions & 76 deletions components/bsx/Offer/MyOffer.vue
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</div>
<NeoSelect v-model="selectedStatus">
<option
v-for="option in getUniqType(offers)"
v-for="option in getUniqType()"
:key="option.type"
:value="option.type">
{{ option.value }}
Expand Down Expand Up @@ -70,10 +70,7 @@
:label="$t('myOffer.date')"
sortable>
<p>
{{
new Date(props.row.createdAt) |
formatDistanceToNow({ addSuffix: true })
}}
{{ timeAgo(new Date(props.row.createdAt).getTime()) }}
</p>
</NeoTableColumn>
<template #empty>
Expand All @@ -85,99 +82,165 @@
</div>
</template>

<script lang="ts">
import { Component, Emit, Prop, Watch, mixins } from 'nuxt-property-decorator'
import { formatDistanceToNow } from 'date-fns'

<script setup lang="ts">
import { NeoButton, NeoSelect, NeoTable, NeoTableColumn } from '@kodadot1/brick'
import Identity from '@/components/identity/IdentityIndex.vue'
import Money from '@/components/shared/format/Money.vue'

import { notificationTypes, showNotification } from '@/utils/notification'
import { tokenIdToRoute } from '@/components/unique/utils'

import OfferMixin from '@/utils/mixins/offerMixin'
import PrefixMixin from '@/utils/mixins/prefixMixin'
import { timeAgo } from '@/components/collection/utils/timeAgo'
import { formatBsxBalanceToNumber } from '@/utils/format/balance'
import { AllOfferStatusType } from '@/utils/offerStatus'

import acceptableOfferByCurrentOwner from '@/queries/subsquid/bsx/acceptableOfferByCurrentOwner.graphql'

import { Offer, OfferResponse } from './types'

const components = {
Identity: () => import('@/components/identity/IdentityIndex.vue'),
Money: () => import('@/components/shared/format/Money.vue'),
NeoTable,
NeoTableColumn,
NeoSelect,
NeoButton,
const { howAboutToExecute, initTransactionLoader, isLoading, status } =
useMetaTransaction()
const { $apollo, $consola, $i18n } = useNuxtApp()
const { urlPrefix, client } = usePrefix()
const { accountId, isLogIn } = useAuth()

const offers = ref<Offer[]>([])
const destinationAddress = ref('')
const selectedStatus = ref<AllOfferStatusType>(AllOfferStatusType.ALL)

withDefaults(
defineProps<{
address: string
hideHeading: boolean
}>(),
{
address: '',
hideHeading: false,
}
)

const targetAddress = computed(
() => destinationAddress.value || accountId.value
)

const getUniqType = () => {
const statusSet = new Set(offers.value.map((offer) => offer.status))
const singleEventList = Array.from(statusSet).map((type) => ({
type: type as AllOfferStatusType,
value: AllOfferStatusType[type],
}))

return [{ type: AllOfferStatusType.ALL, value: 'All' }, ...singleEventList]
}

@Component({
components,
filters: { formatDistanceToNow },
})
export default class MyOffer extends mixins(PrefixMixin, OfferMixin) {
public offers: Offer[] = []
public destinationAddress = ''
@Prop({ type: String, default: '' }) public address!: string
@Prop({ type: Boolean, default: false }) public hideHeading!: boolean

get targetAddress() {
return this.destinationAddress || this.accountId
const fetchMyOffers = async () => {
if (!targetAddress.value) {
return
}

mounted() {
if (this.targetAddress) {
this.$apollo.addSmartQuery<OfferResponse>('offers', {
client: this.urlPrefix,
query: acceptableOfferByCurrentOwner,
variables: { id: this.targetAddress },
manual: true,
result: ({ data }) => this.setResponse(data),
pollInterval: 10000,
})
}
try {
const { data } = await $apollo.query<OfferResponse>({
client: client.value,
query: acceptableOfferByCurrentOwner,
variables: {
id: targetAddress.value,
},
})
offers.value = data.offers
} catch (e) {
$consola.error(e)
}
}

public onClick = async (offer: Offer, withdraw: boolean) => {
const { caller, nft } = offer
const { id: collectionId, item } = tokenIdToRoute(nft.id)
this.isLoading = true
await this.submit(caller, item, collectionId, withdraw, this.fetchMyOffers)
watchEffect(async () => await fetchMyOffers())

// doesn't need emit?
// const emit = defineEmits(['offersIncoming'])
// const offersIncoming = (response: OfferResponse) => {
// emit('offersIncoming', (offers.value = response.offers))
// }

const submit = async (
maker: string,
nftId: string,
collectionId: string,
withdraw: boolean,
onSuccess?: () => void
) => {
try {
const { apiInstance } = useApi()
const api = await apiInstance.value
initTransactionLoader()
const cb = !withdraw
? api.tx.marketplace.acceptOffer
: api.tx.marketplace.withdrawOffer
const args = [collectionId, nftId, maker]

await howAboutToExecute(accountId.value, cb, args, (blockNumber) => {
const msg = !withdraw
? $i18n.t('offer.accept')
: $i18n.t('offer.withdraw')
showNotification(
`[OFFER] Since block ${blockNumber}, ${msg}`,
notificationTypes.success
)
onSuccess && onSuccess()
})
} catch (e: any) {
showNotification(`[OFFER::ERR] ${e}`, notificationTypes.warn)
$consola.error(e)
isLoading.value = false
}
}

@Emit('offersIncoming')
protected setResponse(response: OfferResponse) {
this.offers = response.offers
}
const onClick = async (offer: Offer, withdraw: boolean) => {
const { caller, nft } = offer
const { id: collectionId, item } = tokenIdToRoute(nft.id)
isLoading.value = true
await submit(caller, item, collectionId, withdraw, fetchMyOffers)
}

protected async fetchMyOffers() {
if (!this.targetAddress) {
return
}

try {
const { data } = await this.$apollo.query<OfferResponse>({
client: this.urlPrefix,
query: acceptableOfferByCurrentOwner,
variables: {
id: this.targetAddress,
},
})
this.setResponse(data)
} catch (e) {
this.$consola.error(e)
}
const displayOffers = (offers: Offer[]) => {
let filterOffers: Offer[]
if (selectedStatus.value === AllOfferStatusType.ALL) {
filterOffers = offers.concat()
} else {
filterOffers = offers.filter(
(offer) => offer.status === selectedStatus.value
)
}

@Watch('accountId', { immediate: true })
onAccountChange() {
this.fetchMyOffers()
}
return filterOffers.map((offer) => ({
...offer,
formatPrice: formatBsxBalanceToNumber(offer.price),
expirationBlock: parseInt(offer.expiration),
}))
}

const currentBlock = ref(async () => {
const { apiInstance } = useApi()
const api = await apiInstance.value
const block = await api.rpc.chain.getHeader()
return block.number.toNumber()
})

@Watch('address', { immediate: true })
onAddressChange(value: string) {
this.destinationAddress = value
this.fetchMyOffers()
const calcSecondsToBlock = (block: number): number => {
const secondsForEachBlock = 12
return secondsForEachBlock * (block - currentBlock.value)
}

const calcExpirationTime = (expirationBlock: number): string => {
if (currentBlock.value === 0) {
return 'computing'
}
if (currentBlock.value > expirationBlock) {
return 'expired'
}
return formatSecondsToDuration(calcSecondsToBlock(expirationBlock))
}

watch(accountId, () => {
fetchMyOffers()
})
</script>

<style scoped>
Expand Down
Loading