NFT Trader
Ask or search…
K

TradeClient

Discover how the TradeClient class works

Index

How to instantiate an object of the TradeClient class?

The TradeClient class provides access to the trading features of the platform. An instance object of this class allows performing the operations described in the Concepts section and managing the lifecycle of a Trade. In summary, through the TradeClient class, the developer can allow users of their platform to create, cancel, or finalize a trade. Let's proceed with an example of instantiating an object of this class.
The code snippets are presented in a context where React is used, but any framework for building a Single Page Application (SPA) is suitable.
import { TradeClient } from "@nfttrader-io/sdk"
import { useWeb3React } from "@web3-react/core"
import Network from "@nfttrader-io/sdk/dist/types/general/network"
import { useNetworkId } from "@networkId"
const MyComponent = () => {
const tradeClientRef = useRef<TradeClient | null>(null)
const { library } = useWeb3React()
const currentNetworkId = useNetworkId() //this is a fantasy hook :)
useEffect(() => {
tradeClientRef.current = new TradeClient({
apiKey: "<YOUR_API_KEY>",
network: currentNetworkId as Network,
web3Provider: library.provider //Eg. window.ethereum
})
return () => {}
}, [])
return <></>
}
export default MyComponent
Once the object is initialized, all the trading functionalities provided by the SDK will be accessible. In the above example, some aspects of this object instance can be noted. The parameters provided for the instance are as follows:

apiKey

It is the key to request in order to interact with the NFT Trader platform. You can request it here.

network

It is the network in which you want to use the SDK. It specifies on which blockchain the operations will be performed. This parameter is of type Network, and its characteristics are described here.

web3Provider

It is the provider currently used for interacting with the blockchain. It depends on the wallet you are using. For example, when using MetaMask, the window.ethereum provider can be used as a value for this parameter.

Create a Trade

In order to create a Trade, the TradeClient class provides the createTrade() method. This method takes in several parameters that we will see in the example below. We will then look in detail at how to correctly configure these parameters. For the moment, let's focus on the main operations described in this pseudocode.
//import....
const MyComponent = () => {
const tradeClientRef = useRef<TradeClient | null>(null)
const createTrade = () => {
const {current : sdk} = tradeClientRef
const maker = getMaker() //imaginary method to get the maker
const taker = getTaker() //imaginary method to get the taker
const end = getEnd() //imaginary method to get the duration of the deal
const fees = getFees() //imaginary method to get the fees
sdk.createTrade(maker, taker, end, fees)
.then((response : Trade) => {
//do whatever you want
})
.catch(error => {
//handle the error
})
}
useEffect(() => {
createTrade()
}, [])
return <></>
}
export default MyComponent
As described in the example, the createTrade() method allows creating a trade within the system. This operation will prompt the user to sign with their own wallet. The message to be signed and all the logic related to it are already encapsulated within the SDK, so there will be no need to manage them directly.

Parameters

On the other hand, the parameters of the createTrade() method must be composed correctly. Below we will explain how to perform this operation and provide an explanation for each required parameter.
First of all, let's analyze the signature of the createTrade() method.
/**
* Create the trade
*
* @param maker - The maker of the trade
* @param taker - The taker (counterparty) of the trade
* @param end - The number of the days representing the validity of the trade
* @param fees - The array of fees to apply on the trade
* @param post - The post object containing the information related to the post and the reply accepted
* @param post.postId - The post id related to this trade
* @param post.replyId - The reply id related to the offer accepted to initialize the trade
*/
public async createTrade(
maker: CreateTradePeer,
taker: CreateTradePeer<WithAddress>,
end = 0,
fees?: Array<Fee>,
post?: {
postId: string
replyId: string
}
): Promise<Trade> {...}
maker
The maker parameter is of type CreateTradePeer. Its structure is described here. The maker is the one who initiates the trading operation.
taker
The taker parameter is of type CreateTradePeer<WithAddress>. Its structure is described here. The taker is the counterpart specified in the maker.
end
The end parameter is of type number and indicates the trade duration in days.
fees
The fees parameter is of type Array<Fee> and indicates the array of fees that will be paid when the taker finalizes the transaction. The structure of the Fee object is described here. However, this parameter is optional, as it may not be necessary to set a commission.
post
The parameter post is an object in which two identifiers postId and replyId must be specified. These two parameters are necessary when the trading operation is initialized from a Post. Posts are covered in the Social section, which you can find here. This parameter is optional since a Trade can also be initialized without a direct link to a Post.

Cancel a Trade

To delete a Trade previously created with the creation operation described here, you can proceed by using the cancelTrade() method, which takes a series of parameters as input. Let's analyze in the following pseudocode how to cancel a trade.
//import....
const MyComponent = () => {
const tradeClientRef = useRef<TradeClient | null>(null)
//after the initialization of the TradeClient object you can
const cancelTrade = (tradeId : string) => {
const {current : sdk} = tradeClientRef
sdk.cancelTrade(tradeId)
.then(() => {
//do whatever you want
})
.catch(error => {
//handle the error
})
}
useEffect(() => {
cancelTrade("1234") //cancel the trade with the id "1234"
}, [])
return <></>
}
export default MyComponent
The call to the cancelTrade() method causes the user to directly interface with their wallet to initialize the transaction. Once the transaction is mined on the blockchain, the trade is canceled and therefore is no longer valid.
However, there is a latency during which the trade, before being canceled, persists within the platform's system. This latency is due to the synchronization of transaction data within the database. It should be noted that in any case, once the transaction is validated by the blockchain, the trade is no longer valid.
Parameters
Let's analyze the signature of the cancelTrade() method to understand which parameters this method requires to function properly.
/**
* Cancel the trade specified
*
* @param tradeId - The id of the trade
* @param gasLimit - the gas limit of the transaction
* @param gasPrice - the gas price of the transaction
*/
public async cancelTrade(
tradeId: string,
gasLimit: number = 2000000,
gasPrice: Maybe<string> = null
) {...}
tradeId
The tradeId parameter is of type string and is used to specify the trade to be canceled.
gasLimit
The gasLimit parameter is of type number and specifies the gas limit available to make the transaction on the blockchain.
gasPrice
The gasPrice parameter is of type Maybe<string> and specifies the price in wei per unit of gas for this transaction.

Finalize a Trade

To finalize a trade, you will need to use the execTrade() method. Let's analyze the pseudocode below to understand how to use it correctly.
//import....
const MyComponent = () => {
const tradeClientRef = useRef<TradeClient | null>(null)
//after the initialization of the TradeClient object you can
const execTrade = (tradeId : string) => {
const {current : sdk} = tradeClientRef
sdk.execTrade(tradeId)
.then(() => {
//do whatever you want
})
.catch(error => {
//handle the error
})
}
useEffect(() => {
execTrade("1234") //finalize the trade with the id "2345"
}, [])
return <></>
}
export default MyComponent
The finalization of the Trade is an operation that can be executed exclusively by the taker of the transaction specified by the maker during the creation of the deal. Here is the method signature in the following example.
Parameters
/**
* Execute the trade and finalize the order
*
* @param tradeId - The id of the trade
*/
public async execTrade(tradeId: string) {...}
The only required parameter for this operation is the tradeId, of type string, which specifies the trade to be finalized.

Get information about a single Trade

To obtain information on a single trade, the TradeClient object makes available the getTradeOrder() method. Let's analyze the following pseudocode to understand how to use the method.
//import....
const MyComponent = () => {
const tradeClientRef = useRef<TradeClient | null>(null)
//after the initialization of the TradeClient object you can
const getTrade = (tradeId : string) => {
const {current : sdk} = tradeClientRef
sdk.getTradeOrder(tradeId)
.then((order : Maybe<TradeDetail>) => {
//do whatever you want
})
.catch(error => {
//handle the error
})
}
useEffect(() => {
getTrade("1234") //get the trade info with the id "2345"
}, [])
return <></>
}
export default MyComponent
The method call returns to the client an object of type Maybe<TradeDetail>, with the corresponding trade-related information. You can find here the information regarding the type of object returned by the SDK.
Parameters
Below is the signature of the method to understand which type of parameter can be passed to the function.
/**
* Get the order specified by the tradeId provided as a parameter
*
* @param tradeId
* @returns promiseOrder
*/
public async getTradeOrder(tradeId: string): Promise<Maybe<TradeDetail>> {
tradeId
The tradeId parameter is of type string and is used to specify the trade to be canceled.

Get global Trade history information

It is possible to obtain a list of trades executed on the platform using the getGlobalTradesList() method. Let's analyze the following pseudocode to understand how to implement it within an application.
//import....
const MyComponent = () => {
const tradeClientRef = useRef<TradeClient | null>(null)
//after the initialization of the TradeClient object you can
const getTradesHistory = () => {
const {current : sdk} = tradeClientRef
const currentNetworkId = getCurrentNetworkId() //imaginary method to get the current network id
const status = getStatus() //imaginary method to get the status of the trades we want to obtain (0 means open, 1 completed, 2 canceled)
const skip = getSkip() //imaginary method to handle the pagination
const take = getTake() //imaginary method to handle the pagination
const from = getFrom() //imaginary method to get the date YYYY-MM-DD
const to = getTo() //imaginary method to get the date YYYY-MM-DD
const search = getSearch() //imaginary method to get the search query string (address)
const params: [
network: string,
status: number,
skip: number,
take: number,
from?: "null",
to?: "null",
search?: string
] = [currentNetworkId, status, skip, take, from, to, search]
sdk.getGlobalTradesList(...params)
.then((response : GetGlobalTradesListResponse) => {
//do whatever you want
})
.catch(error => {})
}
useEffect(() => {
getTradesHistory() //get the trades history
}, [])
return <></>
}
export default MyComponent
The method returns an object of class GetGlobalTradesListResponse. The structure of the object is described in the respective section.
Parameters
Let's analyze the parameters of the function starting from the method signature.
/**
* Get the global trades list
*
* @param networkId
* @param status
* @param skip
* @param take
* @param from
* @param to
* @param searchAddress
* @returns history
*/
public async getGlobalTradesList(
networkId: string,
status: number,
skip: number,
take: number,
from?: string | "null",
to?: string | "null",
searchAddress?: string
): Promise<GetGlobalTradesListResponse> {...}
networkId
The networkId field is of type string and is used to obtain the specific list of trades that occurred on a particular blockchain. The list of possible networkIds is available here.
status
The status field is of type number and is used to obtain the specific list of trades with a certain status. The value 0 indicates open trades, the value 1 indicates completed trades, and finally, the value 2 indicates cancelled trades.
skip
The skip field is of type number and is used to manage pagination. It is associated with the take parameter, which is described below.
take
The take field is of type number and is used to handle pagination.
from
The from field is of type string or "null" and is used to retrieve trades starting from a specified date. The value to be specified is in the format YYYY-MM-DD. Optionally, the magic word "null" can be used to specify that this parameter should not be considered.
to
The field to is of type string or "null" and is used to obtain trades up to a specific date. The value to be specified is in the format YYYY-MM-DD. Optionally, the magic word "null" can be used to specify that this parameter is not to be considered.
searchAddress
The searchAddress field is of type string and is used to obtain trades given a specific address or username as input. This value refers to both the maker and taker of the trade.

Get Trade history information for a single user

It is possible to obtain a list of trades executed on the platform by a single user using the getGlobalTradesList() method. Let's analyze the following pseudocode to understand how to implement it within an application.
//import....
const MyComponent = () => {
const tradeClientRef = useRef<TradeClient | null>(null)
//after the initialization of the TradeClient object you can
const getUserTradesHistory = (address : string) => {
const {current : sdk} = tradeClientRef
const currentNetworkId = getCurrentNetworkId() //imaginary method to get the current network id
const status = getStatus() //imaginary method to get the status of the trades we want to obtain (0 means open, 1 completed, 2 canceled)
const skip = getSkip() //imaginary method to handle the pagination
const take = getTake() //imaginary method to handle the pagination
const from = getFrom() //imaginary method to get the date YYYY-MM-DD
const to = getTo() //imaginary method to get the date YYYY-MM-DD
const search = getSearch() //imaginary method to get the search query string (address)
const params: [
network: string,
address: string,
status: number,
skip: number,
take: number,
from?: "null",
to?: "null",
search?: string
] = [currentNetworkId, address, status, skip, take, from, to, search]
sdk.getUserTradesList(...params)
.then((response : GetUserTradesListResponse) => {
//do whatever you want
})
.catch(error => {})
}
useEffect(() => {
getUserTradesHistory("0xFa6262584101f1160B072F5FBb73dC7BA7C500FC") //get the trades history of the user 0xFa6262584101f1160B072F5FBb73dC7BA7C500FC
}, [])
return <></>
}
export default MyComponent
The method returns an object of class GetUserTradesListResponse. The structure of the object is described in the respective section.
Parameters
Let's analyze the parameters of the function starting from the method signature.
/**
* Get the user trades list
*
* @param networkId
* @param address
* @param status
* @param skip
* @param take
* @param from
* @param to
* @param searchAddress
* @returns
*/
public async getUserTradesList(
networkId: string,
address: string,
status: number,
skip: number,
take: number,
from?: string | "null",
to?: string | "null",
searchAddress?: string
): Promise<GetUserTradesListResponse> {...}
networkId
The networkId field is of type string and is used to obtain the specific list of trades that occurred on a particular blockchain. The list of possible networkIds is available here.
address
The address field is of type string and is used to obtain the specific list of trades with a certain address.
status
The status field is of type number and is used to obtain the specific list of trades with a certain status. The value 0 indicates open trades, the value 1 indicates completed trades, and finally, the value 2 indicates cancelled trades.
skip
The skip field is of type number and is used to manage pagination. It is associated with the take parameter, which is described below.
take
The take field is of type number and is used to handle pagination.
from
The from field is of type string or "null" and is used to retrieve trades starting from a specified date. The value to be specified is in the format YYYY-MM-DD. Optionally, the magic word "null" can be used to specify that this parameter should not be considered.
to
The field to is of type string or "null" and is used to obtain trades up to a specific date. The value to be specified is in the format YYYY-MM-DD. Optionally, the magic word "null" can be used to specify that this parameter is not to be considered.
searchAddress
The searchAddress field is of type string and is used to obtain trades given a specific address or username as input in which the user address is involved. This value refers to both the maker and taker of the trade.

Events

The TradeClient class provides a series of utility methods for TypeScript to intercept certain events. The most common method for listening to an event is to use the on() method. Conversely, the off() method is used to remove the object from listening to a specific event.
The list of available events is as follows:
`cancelTradeTransactionCreated` //fired when the cancel tx is submitted to the chain
`cancelTradeTransactionMined` //fired when the cancel tx is mined on the chain
`cancelTradeTransactionError` //fired when the cancel tx goes in error
`cancelTradeError` //fired when the cancel operation goes in error
`execTradeTransactionCreated` //fired when the exec trade tx is submitted to the chain
`execTradeTransactionMined` //fired when the exec trade tx is mined on the chain
`execTradeTransactionError` //fired when the exec tx goes in error
`execTradeError` //fired when the exec operation goes in error
Here is an example implementation of the on() and off() methods.
const sdk = tradeClientRef.current
sdk.on("cancelTradeTransactionCreated", () => {
showModal()
})
sdk.on("cancelTradeTransactionMined", () => {
hideModal()
})
sdk.on("cancelTradeTransactionError", () => {
showError()
})
sdk.cancelTrade(tradeId)
.then(() => {
//do whatever you want
sdk.off("cancelTradeTransactionCreated")
sdk.off("cancelTradeTransactionMined")
sdk.off("cancelTradeTransactionError")
})
.catch((error) => {
//do whatever you want
})
In the above example, the on() method is called to intercept the various stages of a transaction's life in order to display a hypothetical modal window to keep the user updated on the status of the operation.

on()

The method on() is characterized by the following signature.
/**
* Append a callback function from the event queue. Used for intercepting the event during the closing/canceling of the deal and for the changing of the taker.
*
* @param eventName - The name of the event.
* @param callback - The callback function to execute once the event is fired.
*/
public on<EventName extends keyof TradeClientEventsMap>(
eventName: EventName,
callback: TradeClientEventsMap[EventName]
) {...}
eventName
The eventName parameter is of type EventName and its structure is defined in this section. This parameter is used to specify the event for which you want to listen for an update.
callback
The callback parameter is of type TradeClientEventsMap[EventName] and represents the callback function that is invoked every time the specified event conditions occur.

off()

Similarly, the off() method is characterized by the following signature.
/**
* Remove a callback function from the event queue.
*
* @param eventName - The name of the event.
* @param callback - The callback function to execute once the event is fired.
*/
public off<EventName extends keyof TradeClientEventsMap>(
eventName: EventName,
callback?: TradeClientEventsMap[EventName] | null
) {...}
eventName
The eventName parameter is of type EventName and its structure is defined in this section. This parameter is used to specify the event for which you want to remove the listener from the update.
callback
The callback parameter is of type TradeClientEventsMap[EventName] or null and represents the callback function that is invoked every time the conditions of the specified event occur. Specifying the reference of the function is used to remove the specific listener, otherwise providing a null value, all the actions previously specified with the on() event are removed.