Ethereum's missing NFT swap library for web3 developers. Written in TypeScript. Powered by 0x.

Overview

NFT Swap Banner

NFT Swap SDK

_The missing NFT swap SDK for Ethereum and EVM compatible chains, powered by the 0x protocol, written in TypeScript for web3 developers.

Overview

tl;dr: NFT Swap SDK is the easiest, most-powerful NFT swap library. Supports Ethereum and EVM-compatible chains (Polygon, Avalanche, BSC, etc..). Works in both browser and node.js. Written in TypeScript, built using the 0x protocol. With this library, you can build support for NFT marketplaces or over-the-counter (OTC) exchange.

The NFT Swap SDK developed by Trader.xyz offers swap support for ERC20s, ERC721s, and ERC1155s. Exchange NFTs for NFTs, NFTs for ERC20 tokens, or bundles of NFTs and tokens. This library provides the ultimate swap flexibility combined with a simple API surface area so you can be productive immediately and focus on building your web3 app.

This library is powered and secured by the 0x v3 protocol. The 0x v3 protocol has been in production for multiple years securing billions of dollars with of trades.

Goals

We want to share all underlying technology trader.xyz uses with the community. While we won't be open-sourcing our frontend, as we think design and UX is our differentiator, we believe in open-sourcing and freely sharing all underlying technology.

Our end goal is every piece of tech you see trader.xyz use (protocol, swap libraries, open-source orderbook, order monitor, high-performance NFT indexer, property-based orders, specific React hooks, and NFT aggregation) end up open-source. This library is the first step to achieving our goal.

Installation

You can install the SDK with yarn:

yarn add @traderxyz/nft-swap-sdk

or npm:

npm install @traderxyz/nft-swap-sdk

Configuration

To use the SDK, create a new NftSwap instance.

import { NftSwap } from '@traderxyz/nft-swap-sdk';

// From your app, provide NftSwap the web3 provider or signer, and the chainId to instantiate
const nftSwapSdk = new NftSwap(providerOrSigner, chainId);

Now you're setup and ready to use the SDK in your program. Check out the examples for how to swap with the library.

Examples

Example 1: NFT <> NFT swap

In this first example, we're going to do a 1:1 NFT swap. We're going to swap User A's CryptoPunk NFT for User B's Bored Ape NFT.

Terminology: maker: Since User A will initiate the trade, we'll refer to User A as the maker of the trade.

Terminology: taker: Since User B will be filling and completing the trade created by User A, we'll refer to User B as the taker of the trade.

// Setup the sample data...
const CHAIN_ID = 1; // Chain 1 corresponds to Mainnet. Visit https://chainid.network/ for a complete list of chain ids

const CRYPTOPUNK_420 = {
  tokenAddress: '0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb', // CryptoPunk contract address
  tokenId: '420', // Token Id of the CryptoPunk we want to swap
  type: 'ERC721', // Must be one of 'ERC20', 'ERC721', or 'ERC1155'
};

const BORED_APE_69 = {
  tokenAddress: '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D', // BAYC contract address
  tokenId: '69', // Token Id of the BoredApe we want to swap
  type: 'ERC721',
};

// User A Trade Data
const walletAddressUserA = '0x1eeD19957E0a81AED9a80f09a3CCEaD83Ea6D86b';
const assetsToSwapUserA = [CRYPTOPUNK_420];

// User B Trade Data
const walletAddressUserB = '0x44beA2b43600eE240AB6Cb90696048CeF32aBf1D';
const assetsToSwapUserB = [BORED_APE_69];

// ............................
// Part 1 of the trade -- User A (the 'maker') initiates an order
// ............................

// Initiate the SDK for User A.
// Pass the user's wallet signer (available via the user's wallet provider) to the Swap SDK
const nftSwapSdk = new NftSwap(signerUserA, CHAIN_ID);

// Check if we need to approve the NFT for swapping
const approvalStatusForUserA = await nftSwapSdk.loadApprovalStatus(
  assetsToSwapUserA[0],
  walletAddressUserA
);
// If we do need to approve User A's CryptoPunk for swapping, let's do that now
if (!approvalStatusForUserA.contractApproved) {
  const approvalTx = await nftSwapSdk.approveTokenOrNftByAsset(
    assetsToSwapUserA[0],
    makerAddress
  );
  const approvalTxReceipt = await approvalTx.wait();
  console.log(
    `Approved ${assetsToSwapUserA[0].tokenAddress} contract to swap with 0x (txHash: ${approvalTxReceipt.transactionHash})`
  );
}

// Create the order (Remember, User A initiates the trade, so User A creates the order)
const order = nftSwapSdk.buildOrder(
  assetsToSwapUserA,
  assetsToSwapUserB,
  walletAddressUserA
);
// Sign the order (User A signs since they are initiating the trade)
const signedOrder = await nftSwapSdk.signOrder(order, takerAddress);
// Part 1 Complete. User A is now done. Now we send the `signedOrder` to User B to complete the trade.

// ............................
// Part 2 of the trade -- User B (the 'taker') accepts and fills order from User A and completes trade
// ............................
// Initiate the SDK for User B.
// Pass the user's wallet signer (available via the user's wallet provider) to the Swap SDK
const nftSwapSdk = new NftSwap(signerUserB, CHAIN_ID);

// Check if we need to approve the NFT for swapping
const approvalStatusForUserB = await nftSwapSdk.loadApprovalStatus(
  assetsToSwapUserB[0],
  walletAddressUserB
);
// If we do need to approve NFT for swapping, let's do that now
if (!approvalStatusForUserB.contractApproved) {
  const approvalTx = await nftSwapSdk.approveTokenOrNftByAsset(
    assetsToSwapUserB[0],
    walletAddressUserB
  );
  const approvalTxReceipt = await approvalTx.wait();
  console.log(
    `Approved ${assetsToSwapUserB[0].tokenAddress} contract to swap with 0x. TxHash: ${approvalTxReceipt.transactionHash})`
  );
}
// The final step is the taker (User B) submitting the order.
// The taker approves the trade transaction and it will be submitted on the blockchain for settlement.
// Once the transaction is confirmed, the trade will be settled and cannot be reversed.
const fillTx = await nftSwapSdk.fillSignedOrder(signedOrder);
const fillTxReceipt = await nftSwapSdk.awaitTransactionHash(fillTx);
console.log(`πŸŽ‰ πŸ₯³ Order filled. TxHash: ${fillTxReceipt.transactionHash}`);

Example 2: Swap bundles -- Bundle of mixed ERC721s and ERC20 <> Bundle of ERC20s

Here we show an example of what the swap library is capable of. We can even swap arbitrary ERC tokens in bundles. We call it a bundle when we have more than one item that a party will swap. Bundles can have different ERC types within the same bundle.

In other words, we can swap [ERC721, ERC1155, ERC20] <> [ERC721, ERC1155, ERC20]. There's really no limit to what we can swap.

More concrete example: We can swap [2 CryptoPunks and 1,000 DAI] for [420 WETH and 694,200 USDC]. In this case we'd be swapping an ERC721 and an ERC20 (Punk NFT and DAI, respectively) for two ERC20s (WETH and USDC).

This is just one example. In reality, you can swap as many things as you'd like, any way you'd like. The underlying 0x protocol is extremely flexible, and the NFT swap library abstracts all the complexity away so you don't have to worry about protocol nuances.

// Setup the sample data for the swap...
const CHAIN_ID = 1; // Mainnet

const CRYPTOPUNK_420 = {
  tokenAddress: '0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb',
  tokenId: '420',
  type: 'ERC721',
};

const CRYPTOPUNK_421 = {
  tokenAddress: '0xb47e3cd837ddf8e4c57f05d70ab865de6e193bbb',
  tokenId: '421',
  type: 'ERC721',
};

const ONE_THOUSAND_DAI = {
  tokenAddress: '0x6b175474e89094c44da98b954eedeac495271d0f', // DAI contract address
  amount: '1000000000000000000000', // 1,000 DAI (DAI is 18 digits) -- amount to swap
  type: 'ERC20',
};

const SIXTY_NINE_USDC = {
  tokenAddress: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48', // USDC contract address
  amount: '69000000', // 69 USDC (USDC is 6 digits)
  type: 'ERC20',
};

const FOUR_THOUSAND_TWENTY_WETH = {
  tokenAddress: '0x6b175474e89094c44da98b954eedeac495271d0f', // WETH contract address
  amount: '420000000000000000000', // 420 Wrapped-ETH (WETH is 18 digits)
  type: 'ERC20',
};

// User A Trade Data
const walletAddressUserA = '0x1eeD19957E0a81AED9a80f09a3CCEaD83Ea6D86b';
const assetsToSwapUserA = [CRYPTOPUNK_420, CRYPTOPUNK_421, ONE_THOUSAND_DAI];

// User B Trade Data
const walletAddressUserB = '0x44beA2b43600eE240AB6Cb90696048CeF32aBf1D';
const assetsToSwapUserB = [SIXTY_NINE_USDC, FOUR_THOUSAND_TWENTY_WETH];

// ............................
// Part 1 of the trade -- User A (the 'maker') initiates an order
// ............................
const nftSwapSdk = new NftSwap(signerUserA, CHAIN_ID);
// Note: For brevity, we assume all assets are approved for swap in this example.
// See previous example on how to approve an asset.

const order = nftSwapSdk.buildOrder(
  assetsToSwapUserA,
  assetsToSwapUserB,
  walletAddressUserA
);
const signedOrder = await nftSwapSdk.signOrder(order, takerAddress);

// ............................
// Part 2 of the trade -- User B (the 'taker') accepts and fills order from User A and completes trade
// ............................
const nftSwapSdk = new NftSwap(signerUserB, CHAIN_ID);

const fillTx = await nftSwapSdk.fillSignedOrder(signedOrder);
const fillTxReceipt = await nftSwapSdk.awaitTransactionHash(fillTx);
console.log(`πŸŽ‰ πŸ₯³ Order filled. TxHash: ${fillTxReceipt.transactionHash}`);

// Not so bad, right? We can arbitrarily add more assets to our swap without introducing additional complexity!

Example 3: React Hooks + Swap SDK

In this example, we'll leverage the amazing web3-react React Hook library.

const App = () => {
  const { library, chainId } = useWeb3React();

  const [swapSdk, setSwapSdk] = useState(null);
  useEffect(() => {
    const sdk = new NftSwap(library.getSigner(), chainId);
    setSwapSdk(sdk);
  }, [library, chainId])

  // Use the SDK however you'd like in the app...
  const handleClick = useCallback(() => {
    if (!swapSdk) {
      return;
    }
    swapSdk.buildOrder(...)
  }, [swapSdk])

  // ...
}

FAQ

  • Which ERCs does this library support

    • ERC20, ERC721, and ERC1155
  • What EVM chains are currently supported?

    • Mainnet (1)
    • Kovan (42)
    • Rinkeby (4)
    • Polygon (137)
    • Binance Smart Chain (56)
    • Avalance (43114)
  • What protocol does this library?

    • trader.xyz and trader.xyz libraries are powered by 0x v3 Protocol. This protocol is mature and lindy, and has been extremely well-audited.
    • Check out the 0x v3 spec here
    • Check out the 0x v3 Consensys audit here
  • Are there any protocol fees to execute swaps?

    • No
  • How do I get the user's signer object?

    • Generally you can get it from the user's web3 wallet provider, by something like this: provider.getSigner().
    • See this ethers guide (control-f for getSigner).
    • In web3-react you can do:
      • const { library } = useWeb3React();
      • const signer = library.getSigner();
  • How do I store a SignedOrder

    • That's up to you. This library has no opinions on how to store orders. You can throw them in a centralized SQL database, save them to localstorage, use a decentralized messaging solution -- it's really up to you and your app concerns. You can even serialize and compress an order to fit in a tweet or shareable URL! 🀯

Roadmap

We're currently working on the following features for the next iteration of this library

  • Persistent data store of orders (off-the-shelf storage in trader.xyz's public order storage server). Think of it as a public good
  • Property-based orders
  • Order validation
  • Live order status
  • Order event streaming via websockets

If you have feature requests, reach out in our Discord.

We want to make this library a one-stop shop for all your NFT swapping needs.

  • We're also moving off of @0x/* libraries due to the payload size of these packages.
Comments
  • verifyOrderSignature always returns false !

    verifyOrderSignature always returns false !

    Hey Guys.

    trying to verify an order on Polygon swapSDK v3

    I am passing 0x0c58c1170f1ded633862a1166f52107490a9c594 as the exchange contract address. Chain ID as 137

    I keep getting false even though the swap goes through. seems to be an issue.

    opened by rahuldamodar94 3
  • call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method=

    call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="getApproved(uint256)", data="0x", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.7.0)

    I'm trying to create a transaction "ERC20 Example", but I'm encountering this problem: call revert exception [ See: https://links.ethers.org/v5-errors-CALL_EXCEPTION ] (method="getApproved(uint256)", data="0x", errorArgs=null, errorName=null, errorSignature=null, reason=null, code=CALL_EXCEPTION, version=abi/5.7.0) image This error is thrown by this function nftSwapSdk.loadApprovalStatus()

    opened by zqdevelopment 2
  • Add Ubiq support to 0x v4. Chain ID 8

    Add Ubiq support to 0x v4. Chain ID 8

    Deployed and configured the following.

    deploying "InitialMigration" (tx: 0x67ae19bfa08cc0328e1b9d8a5488cf8ef0997aa9de27dd477c3cd10c38aaa120)...: deployed at 0x5b957E61FF15863c29B69da1c1172baBB044c728 with 620174 gas
    deploying "ZeroEx" (tx: 0xa124fd7dbb970e4aa849a69b710103cac00a85830052e9d6937678ab663e5503)...: deployed at 0x19aaD856cE8c4C7e813233b21d56dA97796cC052 with 755195 gas
    deploying "ERC721OrdersFeature" (tx: 0x7d66b56f180a5c664e027a8e623820463d568fdcaac6db3f2396b182989c9ddf)...: deployed at 0x7AE76139C07099FD77F5100af73871ec367Ca808 with 4728224 gas
    deploying "ERC1155OrdersFeature" (tx: 0x44e098dbc98c4295526de1064ace1c7a557100ac52f0b98824ef01c488404f6f)...: deployed at 0x5e850FC7104d1843957627c5028020faB1fd09dD with 4313656 gas
    deploying "OtcOrdersFeature" (tx: 0x622222b8c1e23181ed8672501c3dec941abf8c85095a724e6373ea7253beacf9)...: deployed at 0x27548434B9b5dF3EF60fb1ec289CaABBA6B4fe2A with 2524104 gas
    deploying "ERC165Feature" (tx: 0x53f1151d456cbdc1e957babda3952105096e537015a19d4efb8d8c52464b6774)...: deployed at 0x71d56d94261086bFfa3D5f97c2043cD7E1a87afb with 210133 gas
    deploying "SimpleFunctionRegistryFeature" (tx: 0x50976cb462af877eaf96a6e1eb1bec7ae6d96e22d7ff4091c5673eb481b89e74)...: deployed at 0xC1Ab827a823d17D9db77fdF4D61809F0391B9050 with 773300 gas
    deploying "OwnableFeature" (tx: 0x42eb9017396e78baccec288b68a8c444ab5632ec0d216762d511d92fa88e0270)...: deployed at 0x3956FB6BDFcb81c12b3B965DEC05B4012f4Be6DD with 758315 gas
    
    executing InitialMigration.initializeZeroEx (tx: 0x1568e6e62c8d2d7662d33def2f1677281ad0b87b56e057aeaf6204bd7436600a) ...: performed with 445304 gas
    executing ERC165Feature extend (tx: 0x376aeeab485ad5ee1e7de6109c6218aea370dcf7f4520501878248a0a6881091)
    executing ERC721OrdersFeature migrate (tx: 0x83223933804071f3bdbc942740373221a28f896426cf0fcf1ed40a2d908b41c1)
    executing ERC1155OrdersFeature migrate (tx: 0x88a4a6933104274f8ba5a3830fc3cb500106d1f8f844d207bdb801dc389468ef)
    executing OtcOrdersFeature migrate (tx: 0xaacb1d507a6e1a426f50a275ce6da09b038bd7c942066a736122c33cadbe643d)
    

    Waiting for https://sourcify.dev to be up to Verify the contract source there.

    Thanks!

    opened by jyap808 2
  • Fixes V3 verifyOrderSignature signature to validate correctly

    Fixes V3 verifyOrderSignature signature to validate correctly

    Sometimes (just due to how signatures are derived between 0x orders and other standards), signatures would not validate successfully when calling verifyOrderSignature. This fixes that to use a standard way of deriving a signature that can be passed to verify the typed data (since you can't pass a 0x order signature directly to a verifyTypedData signature)

    opened by johnrjj 2
  • Order updates

    Order updates

    I know the WebSockets are still a work in progress, but someone here might know how to answer this: is the 0x WebSocket API only streaming ERC20 to ERC20 order updates? Could I possibly hook into that to stream NFT order events?

    Thank you!

    opened by koin-marian 1
  • Problem posting NFT for sale

    Problem posting NFT for sale

    I am getting this when trying to post a sell order for an ERC1155 token on Ropsten network:

    "Error looking up maker balance and approval data. Order may be using incorrect/bad token 0xd526a2c6d167b3c8b7145c7279c179426d61e1a9, chainId: 3."

    The contract address is correct, so is the chain id. I am also setting the approval successfully beforehand on the same contract with the same SDK and that works and I can see the transaction on etherscan. I am also able to check the balance for my wallet through web3 with no issue.

    opened by koin-marian 1
  • Impossible to create ETH β†’ NFT order with

    Impossible to create ETH β†’ NFT order with "buildOrder" method

    It is possible to create an NFT β†’ ETH order, but it is impossible to create ETH β†’ NFT.

    A transaction ERC-20 β†’ NFT fails with an error "cannot estimate gas", although a transaction ERC-20 (native token) β†’ NFT passes successfully.

    opened by ErnestMironov 1
  • Adds support to batch buy NFTs

    Adds support to batch buy NFTs

    e.g. shopping cart functionality, buy multiple ERC721 or ERC1155s in one tx

    const fillTx = await nftSwap.batchBuyNfts([
      signedNftSellOrder1,
      signedNftSellOrder2,
    ]);
    
    opened by johnrjj 1
  • Orderbook Allowance Error

    Orderbook Allowance Error

    I've using the sdk for a couple of days.

    Today I started to get an error after call the "postOrder" method:

    {errorCode: "INSUFFICIENT_MAKER_ALLOWANCE",…} errorCode: "INSUFFICIENT_MAKER_ALLOWANCE" errorMessage: "Maker does not have sufficient allowance of 0xc778417e063141139fce010982780140aa0cd5ab (ERC20)"

    opened by aecdanjundex 1
  • Adds support for integrator attribution

    Adds support for integrator attribution

    Adds support for integrator attribution, so dune dashboards etc can attribute volume to an integrator.

    Opt-in by default, of course

    Uses the 256bit nonce, divides it into a [128bit attribution][128bit random nonce for order], and that will be the canonical 0x v4 standard schema for nonces.

    To add an app identifier to your app, instantiate the sdk with a unique positive integer (up to 2**126 -1)

    const nftSwap = new NftSwapV4(
      provider,
      signer,
      chainId,
      { appId: '69420' },
    )
    
    opened by johnrjj 1
  • Adds unit tests for invalid orders attempting to post to orderbook

    Adds unit tests for invalid orders attempting to post to orderbook

    Open orderbook now rejects order unless they meet certain criteria of validity (e.g. maker has sufficient balance of maker asset, maker approval in order, tokens are valid, signature valid). This adds tests around those invalid orders to ensure the orderbook is providing the correct error codes to the end-user SDK.

    opened by johnrjj 1
  • Does orderbook have support for celo?

    Does orderbook have support for celo?

    I have been working with nft swap sdk for polygon and it works like a charm however i also wanted to extend my product to be available on celo and was wondering if 0x can add support for it?

    opened by saharshkhicha18 0
  • V4 | The buyer cannot select the quantity purchased from the order

    V4 | The buyer cannot select the quantity purchased from the order

    Hello everyone!

    I noticed that the user, when he bought an ERC1155 against an ERC20 could not choose the quantity bought; If the offer is 5 ETH against 5 ERC1155, it is impossible from the SDK to buy 1 ERC1155 for 1 ETH.

    I have fork your project and create a fix, not being allowed to make a PR, here is a screen of the patch :

    (src/sdk/v4/NftSwapV4.ts): https://prnt.sc/c1G4i5T-Z13m (src/sdk/v4/types.ts) : https://prnt.sc/B4Fw-ZR2Zd2w

    opened by boulinb 1
  • V3 fillSignedOrder - MetaMask - RPC Error when signing

    V3 fillSignedOrder - MetaMask - RPC Error when signing

    Hi,

    I'm working with V3 on Polygon and getting a Metamask internal error when using fillSignedOrder.

    Before filling I verify the order signature is correct and that it passes.

    Does anyone know what could be causing the following issue when using fillSignedOrder results in:

    MetaMask - RPC Error: Internal JSON-RPC error.
    code: -32603
    data: 
        code: 3
        data: "0x4678472b43693c6356dfe50fa860e046b18bfc620c5c855517bfab74eebfdcb898531f4a00000000000000000000000000000000000000000000000000......."
        message:  "execution reverted"
    message: "Internal JSON-RPC error."
    
    
    opened by jinsley8 4
  • V3 BuildOrder - Not setting makerFeeAssetData & takerFeeAssetData on Polygon

    V3 BuildOrder - Not setting makerFeeAssetData & takerFeeAssetData on Polygon

    I have a buildOrder setup on Polygon but it is not including makerFeeAssetData & takerFeeAssetData. I'm using WETH contract on polygon 0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619.

    // My setup is similar to this...
    const CHAIN_ID = 137; // Polygon Mainnet
    
    const ASSET_420 = {
      tokenAddress: '0xb4....',
      tokenId: '420',
      type: 'ERC721',
    };
    
    const ASSET_421 = {
      tokenAddress: '0xb4...',
      tokenId: '421',
      type: 'ERC721',
    };
    
    const ONE_WETH = {
      tokenAddress: '0x7ceB23fD6bC0adD59E62ac25578270cFf1b9f619', // WETH contract address
      amount: '100000000000000000', // Wrapped-ETH (WETH is 18 digits)
      type: 'ERC20',
    };
    
    // User A Trade Data
    const walletAddressUserA = '0x1e....';
    const assetsToSwapUserA = [ASSET_420];
    
    // User B Trade Data
    const walletAddressUserB = '0x44....';
    const assetsToSwapUserB = [ASSET_421, ONE_WETH];
    
    // ............................
    // Part 1 of the trade -- User A (the 'maker') initiates an order
    // ............................
    const nftSwapSdk = new NftSwap(provider, signerUserA, CHAIN_ID);
    
    const order = nftSwapSdk.buildOrder(
      assetsToSwapUserA,
      assetsToSwapUserB,
      walletAddressUserA, {
                  takerAddress: walletAddressUserB,
                  expiration: Math.floor(Date.now() / 1000 + 3600 * 24 * 2), // 2 days
                  chainId: CHAIN_ID,
                  feeRecipientAddress: process.env.NEXT_PUBLIC_FEE_RECIPIENT_ADDRESS,
                  makerFee: ethers.utils.parseUnits('0.005', 'ether'), // 0.005 WETH
                  takerFee: ethers.utils.parseUnits('0.005', 'ether'), // 0.005 WETH
              }
    );
    const signedOrder = await nftSwapSdk.signOrder(order, walletAddressUserB);
    

    The signature request will show:

    makerAddress: 0x0a...
    takerAddress: 0x41...
    feeRecipientAddress: 0xe7...
    senderAddress: 0x0000000000000000000000000000000000000000
    makerAssetAmount: 1
    takerAssetAmount: 2
    makerFee: 5000000000000000
    takerFee: 5000000000000000
    expirationTimeSeconds: 1666461
    salt: 1666...
    makerAssetData: 0x0257179....92
    takerAssetData: 0x0257179....96
    makerFeeAssetData: 0x
    takerFeeAssetData: 0x
    

    Should I be including makerFeeAssetData and takerFeeAssetData in the buildOrder orderConfig?

    If so how can I encode that data to bytes? to include the values in the orderConfig?

    opened by jinsley8 0
  • BuildOrderAdditionalConfig in V3 is not documented

    BuildOrderAdditionalConfig in V3 is not documented

    1. It seems V4 doesn't support NFT < - > NF swap, so I have to use SwapSDK V3 if I need to do NFT <-> NFT?

    2. For V3, it seems the way to specify the fee components will be passing a BuildOrderAdditionalConfig to buildOrder function. However I cannot see any example / doc about how to use this parameter. can anyone share some experiences with the fee configuration ? any help will be much appreciated. thanks

    opened by rico-bee 3
Releases(v0.29.0)
  • v0.29.0(Sep 5, 2022)

    Previously you could provide the Goerli 0x v4 exchange contract address to use the NFT Swap SDK.

    This release enables Goerli to automagically work without knowing any contract addresses, just bring a Goerli RPC and the SDK will work. Also enables managed orderbook service support for Goerli.

    Source code(tar.gz)
    Source code(zip)
  • v0.26.0(May 19, 2022)

    Adds support for buying multiple NFTs in single transaction using the SDK.

    Docs: https://docs.swapsdk.xyz/readme/batch-buy-nfts

    Build shopping cart functionality in your NFT marketplace!

    Usage:

    const fillTx = await nftSwap.batchBuyNfts([
      signedOrder_1,
      signedOrder_2,
    ])
    
    Source code(tar.gz)
    Source code(zip)
  • v0.25.0(May 12, 2022)

    Adds support for Polygon Mumbai testnet (chain 80001)

    • Adds 0x v4 Polygon Mumbai testnet deployment address for the ExchangeProxy
    • Enables support on the open orderbook for Polygon Mumbai orders and order watching
    Source code(tar.gz)
    Source code(zip)
  • v0.24.0(Apr 27, 2022)

    Adds more search filtering options for the public orderbook. Notably, passing in arrays for token addresses and ids, as well as chains is now supported.

    interface SearchOrdersParams {
      nftTokenId: string | string[];
      erc20Token: string | string[];
      nftToken: string | string[];
      nftType: 'ERC721' | 'ERC1155';
      chainId: string | number | string[] | number[];
      maker: string;
      taker: string;
      nonce: string | string[];
      offset: string | number;
      limit: string | number;
      sellOrBuyNft: 'sell' | 'buy';
      direction: '0' | '1';
      // Defaults to only 'open' orders
      status: 'open' | 'filled' | 'expired' | 'cancelled' | 'all';
      visibility: 'public' | 'private';
      valid: 'valid' | 'all';
    }
    
    Source code(tar.gz)
    Source code(zip)
  • v0.23.0(Apr 21, 2022)

    Adds support for integrator attribution, so integrator fill volume can show up in dune dashboards

    Opt-in by default, of course

    Uses the 256bit nonce, divides it into a [128bit attribution][128bit random nonce for order], and that will be the canonical 0x v4 standard schema for nonces.

    To add an app identifier to your app, instantiate the sdk with an appId that is an unique positive integer (up to 2**126 -1)

    const nftSwapSdk = new NftSwapV4(
      provider,
      signer,
      chainId,
      { appId: '69420' },
    )
    
    Source code(tar.gz)
    Source code(zip)
  • v0.22.0(Apr 14, 2022)

  • v0.21.0(Apr 8, 2022)

    Not a breaking change. Just adds proper support in buildOrder() for passing expiry a unix timestamp directly (e.g. 1897016400). expiry still also supports a Date().

    Source code(tar.gz)
    Source code(zip)
  • v0.20.0(Apr 7, 2022)

  • v0.19.0(Apr 3, 2022)

    Adds a bunch of useful utility/helper functions for working with 0x v4 assets and orders.

    Changeset:

    • Adds typedoc documentation for all public functions in NftSwapV4 class
    • getMakerAsset function added
    • getTakerAsset function added
    • validateSignature function added
    • fetchBalanceForAsset function added
    • checkOrderCanBeFilledMakerSide function added
    • checkOrderCanBeFilledTakerSide function added
    • getErc20TotalIncludingFees function added
    • Adds tests for all convenience functions
    Source code(tar.gz)
    Source code(zip)
  • v0.18.0(Mar 25, 2022)

    • Updates to TypeChain v8
    • Handle buying NFT with ETH (or native token) better (bugfix-ish)
    • Better order building guard rails (e.g. an NFT sell [i.e. NFT as the taker asset] order cannot use ETH.
    Source code(tar.gz)
    Source code(zip)
  • v0.16.2(Mar 19, 2022)

  • v0.16.1(Mar 18, 2022)

  • v0.16.0(Mar 14, 2022)

    πŸŽ‰ Enables multichain support for 0x v4. πŸŽ‰

    Swap SDK v4 now supports Ethereum Mainnet, Polygon, Optimism, BSC, Fantom, and Celo, and Ropsten Testnet.

    Arbitrum support coming soon.

    Note: No breaking changes; Just wanted to increment to pin the multichain contract versions.

    PRs: https://github.com/trader-xyz/nft-swap-sdk/pull/36

    Source code(tar.gz)
    Source code(zip)
  • v0.15.2(Mar 12, 2022)

    Previously there would be a mismatch between 0x order signature and the type data signature (and the verifyOrderSignature would return false despite an order signature being valid). Now we use ethers to standardize the signature type and compare signatures from there, so any kind of signature passed should work. Special thanks to @rahuldamodar94 for reporting.

    Source code(tar.gz)
    Source code(zip)
  • v0.15.0(Mar 1, 2022)

    Feature request: https://github.com/trader-xyz/nft-swap-sdk/issues/31 PR: https://github.com/trader-xyz/nft-swap-sdk/pull/32

    Note: This is technically a breaking change because some types were renamed. If you have types that suddenly don't work, add V3 or V4 to the end of them. This release specifies the SDK version of these types since we have two versions (v3 and v4) in the codebase at one time. (e.g. SwappableAsset -> SwappableAssetV4)

    Source code(tar.gz)
    Source code(zip)
  • v0.14.0(Feb 28, 2022)

  • v0.13.0(Feb 28, 2022)

    Overview

    Adds official hosted orderbook support for all supported 0x v4 chains.

    Save Order

    To save an order to the hosted orderbook:

    await nftSwapSdk.saveOrder(signedOrder);
    

    Fetch orders

    // Search the orderbook for all offers to sell this NFT (CryptoCoven #9757)
    const orders = await nftSwap.getOrders({
      nftToken: "0x5180db8f5c931aae63c74266b211f580155ecac8",
      nftTokenId: "9757",
      sellOrBuyNft: "sell", // Only show asks (sells) for this NFT (excludes asks)
    });
     
    // Or search by unique nonce
    const orders = await nftSwap.getOrders({
      nonce: "0x31f42841c2db5173425b5223809cf3a38fede360",
    });
    

    https://docs.swapsdk.xyz/0x-v4/hosted-orderbook (Comprehensive docs forthcoming)

    Relevant links:

    All orders: https://api.trader.xyz/orderbook/orders Status page: https://status.trader.xyz Example from ETHDenver workshop: https://slides.com/johnj/nft-workshop#/40/0/6

    Source code(tar.gz)
    Source code(zip)
  • v0.12.0(Feb 5, 2022)

    πŸ“’ tl;dr: No approvals required when a user accepts a bid on their NFT -- a first for NFT marketplaces and swaps! πŸ“’

    🀝 If a user receives a bid on their NFT, they can accept the bid without needing to approve the NFT for transfer/swap first.

    Simply call fillBuyNftOrderWithoutApproval instead of fillSignedOrder with the Swap SDK.

    This provides the most seamless UX for accepting NFT bids on Ethereum, no more two-step process, and saves users money. πŸ€‘

    More info here

    Note: This only works on NFT Buy orders (e.g. maker offers to buy NFT, taker can fill [by selling their NFT], without approval)

    Source code(tar.gz)
    Source code(zip)
  • v0.11.0(Feb 5, 2022)

    Adds configurable fee support to NFT Swap SDK.

    Fees unlock all sorts of use cases:

    • Monetize applications,
    • Royalties for creators or DAOs
    • Reward users
    • Send payouts to a contract that implements custom fee disbursement logic

    πŸ”₯ Under 120k gas for a NFT swap with one fee, the cheapest on the EVM πŸ”₯

    Fees can be specified by:

    interface Fee {
        recipient: string // The address to send the fee to
        amount: string // The amount (based in the same erc20Token) to charge for fee
        feeData?: string | undefined; // optional feeData callback
    }
    

    Important notes:

    • Buyer of the NFT pays the fee(s)
    • Fees are in addition to the erc20TokenAmount that the buyer is paying for the NFT itself
    • Can support multiple fees
    const MAKER_ASSET: SwappableAsset = {
      type: 'ERC721',
      tokenAddress: TEST_NFT_CONTRACT_ADDRESS,
      tokenId: '11045',
    };
    
    const TAKER_ASSET: SwappableAsset = {
      type: 'ERC20',
      tokenAddress: USDC_TOKEN_ADDRESS,
      amount: '420000000000000', // 4200 USDC
    };
    
    const v4Erc721Order = nftSwap.buildOrder(
      MAKER_ASSET,
      TAKER_ASSET,
      MAKER_WALLET_ADDRESS,
      {
        fees: [
          {
            amount: '6900000000000', // 69 USDC fee
            recipient: '0xaaa1388cD71e88Ae3D8432f16bed3c603a58aD34', // your DAO treasury 
          },
        ],
      }
    );
    

    Docs here: https://0x.org/docs/guides/0x-v4-nft-features-overview#fees

    Spec: For each Fee specified in an order, the buyer of the NFT will pay the fee recipient the given amount of ETH/ERC20 tokens. This is in addition to the erc20TokenAmount that the buyer is paying for the NFT itself. There is an optional callback for each fee:

    Source code(tar.gz)
    Source code(zip)
  • v0.10.0(Feb 5, 2022)

    Adds Collection-based orders to NFT Swap SDK. (Also can be used as 'floor-based' orders).

    πŸ”₯ Under 105k gas πŸ”₯

    These orders can be filled using any NFT from a particular collection.

    The SDK provides a simple API:

    // Maker creates an order for any NFT from a collection (you can think of it as a 'bid')
    // Specifically in this example, the maker will sell 1000 USDC for any NFT in the collection specified
    const v4Erc721Order = nftSwap.buildCollectionBasedOrder(
      // Selling ERC20
      {
        type: "ERC20",
        tokenAddress: USDC_TOKEN_ADDRESS,
        amount: "100000000000000", // 1000 USDC
      },
      // Bidding on any NFT in the collection
      {
        tokenAddress: NFT_CONTRACT_ADDDRESS,
        type: "ERC721", // "ERC721" | "ERC1155"
      },
      makerWalletAddress // Maker wallet address
    )
    
    const signedOrder = await nftSwap.signOrder(v4Erc721Order)
    
    // Later, taker can sell an NFT from the specified collection, filling the bid.
    const fillTx = await nftSwap.fillSignedCollectionOrder(
      signedOrder,
      "11045" // Token ID from the collection to fill order with
    )
    

    https://docs.swapsdk.xyz/0x-v4/collection-based-floor-based-orders

    Source code(tar.gz)
    Source code(zip)
  • v0.9.0(Jan 31, 2022)

    πŸŽ‰ Swap SDK now supports using 0x v4 NFT to swap NFTs. πŸŽ‰

    πŸ“„ Docs can be found here: https://docs.swapsdk.xyz/0x-v4

    ✏️ 0x v3 is still the default while 0x v4 rolls out to all chains. To use 0x v4, developers can opt-in by importing the NftSwapV4 class.

    v1.0 release to follow soon, which will include open orderbook APIs and order persistance.

    Source code(tar.gz)
    Source code(zip)
  • v0.8.0(Jan 8, 2022)

  • v0.7.0(Jan 3, 2022)

  • v0.6.1(Dec 27, 2021)

Owner
trader.xyz
a better way to trade with friends
trader.xyz
NFT Marketplace prototype using Typescript, WalletConnect, Metamask, Web3, Solidity, React and Storybook

ERC721 NFT Marketplace Prototype of a NFT Marketplace based on openZeppelin abstract upgradeable ERC721 contracts and Minting/uploading images to IPFS

CryptoMoon 3 Jul 4, 2022
React-NFT-App - NFT-Web-Application built using Third web , ReactJs and use Crypto Punks with API

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Ali Aftab Sheikh 8 Oct 24, 2022
Cheatsheets for experienced React developers getting started with TypeScript

Cheatsheets for experienced React developers getting started with TypeScript

TypeScript Cheatsheets 38.8k Jan 4, 2023
React People lists and connects React developers around the world.

React People React People lists and connects React developers around the world. Progress View the Project page for details on what's planned and what'

Vitor Leonel 15 Aug 23, 2022
_buildspace - web3 Read/Write Solana Blockchain Project

_buildspace - web3 Read/Write Solana Blockchain Project

Benny 2 Aug 28, 2022
Gif Portal build using solana, anchor, web3 and react

Features of the dapp View Popular Dance Moves Gifs Vote for your favorite Gifs Add link of your favorite dance gif on the portal All the data includin

Anshul Goel 5 Oct 27, 2022
Create a Web3 Forum with Polygon

Create a Web3 Forum with Polygon Tutorial Details Today we're going to build together a fullstack decentralized forum that can be used in any dapp. Se

pointer 120 Oct 23, 2022
Tsnip.nvim - Plugin to expand snippets written in Pure TypeScript(Deno)

tsnip.nvim Plugin to expand snippets written in Pure TypeScript(Deno). This plug

yuki yano 18 Oct 21, 2022
How to mint your own NFT token with react

Mint your own basic off chain NFT Description This project teaches you how to mint your own NFT token. Here are some important packages that we will b

null 6 May 17, 2022
Youtube Tutorial showcasing how to create a fullstack NFT mingint dapp.

Emoji Faces NFT Minting dApp This a complete example of fullstack NFT minting dApp. EmojiFaces is built with the purpose of providing an entry point f

codingwithdidem 53 Dec 25, 2022
This is used for minting NFTs and getting metadata , token owner, wallet address assigned to an NFT, just check it out and enjoy

nft-minter A Heroku web server to easily mint non-fungible tokens via an API Example Configuration: Blockchain: Ethereum Testnet: Rinkeby Contract: ER

John Oseni 9 Aug 24, 2022
Ethereum nft marketplace template using react

ethereum-marketplace-template ⭐️ Star us If this boilerplate helps you build Ethereum dapps faster - please star this project, every star makes us ver

Ethereum Boilerplates 73 Dec 17, 2022
This Project is a fork of Ethereum Boilerplate and demonstrates how you can build your own NFT Rarity Ranker.

This Project is a fork of Ethereum Boilerplate and demonstrates how you can build your own NFT Rarity Ranker.

null 88 Dec 20, 2022
This is a proof of concept of an NFT vending machine built using Solana Pay, Metaplex, Phantom Mobile, and Next.js

Solana NFT Vending Machine This is a proof of concept of an NFT vending machine built using Solana Pay, Metaplex, Phantom Mobile, and Next.js. This wa

Matt Rosenzweig 55 Dec 15, 2022
A comments system powered by GitHub Discussions.

A comments system powered by GitHub Discussions. Let visitors leave comments and reactions on your website via GitHub! Heavily inspired by utterances.

giscus 3.7k Dec 30, 2022
(Optional) First challenge on ignite ReactJS powered by Rocketseat

Segundo desafio da trilha de React do Ignite da Rocketseat. O projeto consiste em listar filmes de uma API fake, utilizando o JSON Server. ?? ConteΓΊdo

JosΓ© Eduardo 2 Sep 18, 2022
A serverless Notion-powered blog in React

A serverless Notion-powered blog in React I'm trying to build for fun. If I had to pick a name for this, it'd be COKE.

Arth Tyagi 29 Nov 15, 2022
Isomorphic application written in React

Isomorphic "Quiz Wall" for itsquiz.com Motivation There are a lot of tutorials and boilerplates showing how to write isomorphic ReactJs applications.

WebbyLab 521 Nov 1, 2022
Implementation of WebAuthn API written in React and Express

Simple WebAuthn demo Implementation of WebAuthn API written in React and Express. Demo that shows the future of passwordless authentication. Users reg

Sheikh Salman 6 Dec 12, 2022