-
Notifications
You must be signed in to change notification settings - Fork 9
/
fulfillOffer.ts
89 lines (76 loc) · 2.48 KB
/
fulfillOffer.ts
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
import { AxiosError } from "axios"
import { ethers } from "ethers"
import { apiClient } from "./apiClient"
import { getNetwork } from "./network"
import { seaportContractAddress, seaportInterface } from "./seaport"
import { getWallet } from "./wallet"
const network = getNetwork()
type NFT = {
assetContractAddress: string
tokenId: string
}
type FulfillmentRequest = {
offerHash: string
fulfillerAddress: string
consideration?: NFT
}
const getFulfillmentData = async (request: FulfillmentRequest) => {
let consideration
if (request.consideration) {
consideration = {
asset_contract_address: request.consideration.assetContractAddress,
token_id: request.consideration.tokenId,
}
}
const payload = {
offer: {
hash: request.offerHash,
chain: network.chainName,
protocol_address: seaportContractAddress,
},
fulfiller: {
address: request.fulfillerAddress,
},
consideration,
}
try {
const response = await apiClient.post(`v2/offers/fulfillment_data`, payload)
return response.data.fulfillment_data
} catch (error) {
console.error("request failed to fulfillOffer")
console.error((error as AxiosError).response?.data)
throw error
}
}
const buildTransaction = async (request: FulfillmentRequest) => {
const fulfillmentData = await getFulfillmentData(request)
const transactionData = fulfillmentData.transaction
const fragment = seaportInterface.getFunction(transactionData.function)
const encodedData = seaportInterface.encodeFunctionData(
fragment,
Object.values(transactionData.input_data),
)
const tx: ethers.providers.TransactionRequest = {
to: transactionData.to,
from: request.fulfillerAddress,
value: transactionData.value,
data: encodedData,
}
return tx
}
export const estimateFulfillOfferGas = async (request: FulfillmentRequest) => {
const transaction = await buildTransaction(request)
transaction.maxPriorityFeePerGas = 0 // to make the estimate work if eth is low
const provider = new ethers.providers.JsonRpcProvider(network.rpcUrl)
return await provider.estimateGas(transaction)
}
// Sample of how to actually fulfill an offer
const _fulfillTransaction = async (offerHash: string) => {
const provider = new ethers.providers.JsonRpcProvider(network.rpcUrl)
const wallet = getWallet().connect(provider)
const transaction = await buildTransaction({
offerHash,
fulfillerAddress: wallet.address,
})
return await wallet.sendTransaction(transaction)
}