# Introduction to SafeSwap

A Secure Cross-Chain Atomic Swapping Protocol to Enable Native Token Transfers Across Different Blockchains

## What is SafeSwap?

SafeSwap has **redefined interoperability** through secure [cross-chain atomic swaps](/technical/cross-chain-atomic-swaps).&#x20;

{% embed url="<https://www.youtube.com/watch?v=kiDFzEeWPyI>" %}
What is SafeSwap?
{% endembed %}

{% hint style="warning" %}
SafeSwap is not a DEX or Trading Platform. It's a platform and protocol to enable cross-chain 1:1 native token swaps.
{% endhint %}

## Unlocking a Multichain Future

Using atomic swaps, SafeSwap can transform a token into a multichain token, as it enables the secure transfer of native tokens across [diverse blockchains](/technical/supported-blockchains) such as vechain, BNB Chain, Ethereum, Polygon, Base and Optimism.

Unlike most cross-chain solutions out there, with SafeSwap, there's no need to wait for someone else to provide liquidity or to use some wrapped version of your token.

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FdfKmlQLLog4Ihbv5bRQk%2Fimage.png?alt=media&amp;token=cd32902d-d87f-4869-9668-ba47b03e353d" alt=""><figcaption></figcaption></figure>

### The Cross-Chain Atomic Swaps

A [cross-chain atomic swap](/technical/cross-chain-atomic-swaps) is a 1:1 swap of native tokens between different blockchains.

This is done by a smart locking and unlocking mechanism of the native tokens on the chains involved. The swap is fully conducted between a user’s own wallets without any middlemen (peer-to-peer).

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FzkFBbUvBBJVlATPP0gq4%2Fimage.png?alt=media&amp;token=4f0be073-4da2-4ec2-931f-64d6d42da222" alt=""><figcaption></figcaption></figure>

## SafeSwap's Core Features

SafeSwap stands out with its unique set of features designed for seamless, secure and user-friendly cross-chain native token transfers.

Here's why SafeSwap stands out:

* **Cross-Chain Atomic Token Swaps** enable users to swap native tokens directly between different blockchains without relying on wrapped tokens.
* **Peer-to-Peer Transactions**: All swaps take place directly between the user's wallets, eliminating the need for intermediaries, ensuring complete transparency and user control.
* **Tokenomic Integrity**: SafeSwap uses a smart and efficient locking/unlocking to ensure your token supply remains consistent during swaps, preventing any potential token manipulation.
* **Guaranteed Liquidity with Locked Token Pools**: Rather than relying on user-provided liquidity, tokens are placed into a locked token pool by the project owners themselves, ensuring full control, consistent liquidity and zero slippage for users.
* **Enhanced Security with Hashed Time-Locked Contracts (HTLC):** Secure swaps that can only be claimed from the initiating device and browser. [HTLC](/technical/htlc) uses unique codes for each token pool ensure accurate swaps and protect against unauthorized actions.
* **Extra** [**Security Measures**](/technical/security-measures) **for Larger Swaps:** Bigger transactions come with bigger risks, so we up the security for them. Any swap above $10,000 will need at least 5 confirmations before it's executed. This extra step gives users peace of mind that their high-value swaps are handled with utmost precision and care.
* **Whitelabel Integration for Developers**: [Developers](/builders/hello-world) can effortlessly integrate SafeSwap, leveraging its cross-chain benefits. Our [whitelabel solution](/builders/whitelabel-integration) and [robust AP](/builders/api-integration-guide)I simplify integration, allowing for tailored user experiences and brand consistency.

## Cross-Chain Use Cases

* **Native Token Swaps**: Seamlessly transfer native tokens between various blockchains.
* **Cross-Chain Liquidity**: Projects using SafeSwap can tap into and provide liquidity across different chains, enriching their DeFi ecosystem.
* **Multichain Tokens**: Enable your tokens across multiple chains with ease.
* **Multichain Dapps**: Broaden your dApps' reach and functionality by making them available on multiple chains.

See also: [Cross-Chain Use Cases ](#cross-chain-use-cases)and [Benefits for Builders](broken://pages/eUkaEnr6ZvqXCUKrXnAf).

## Benefits for End Users

* **One-to-One Token Swaps Directly Between User Wallets:** SafeSwap ensures user empowerment by facilitating direct token swaps between personal wallets. Users maintain full control and ownership of their tokens at all times, without any third-party interventions.
* **Always-On Liquidity and Zero Slippage:** Experience consistent liquidity availability, thanks to SafeSwap's locked token pools tailored for atomic 1:1 swaps. With no slippage, users get exactly what they expect, any time of the day.
* **Unparalleled User Security:** Beyond standard blockchain security protocols, SafeSwap introduces an extra protective layer. The platform's backend code ensures that only the initiating device can claim the swapped funds, within the same browser, shielding users from potential unauthorized interventions.
* **True Native Multichain Tokens:** SafeSwap's protocol enables the use of native tokens across different blockchains. There's no minting, burning, or splitting of the supply, preserving tokenomic purity. Users always hold real assets.
* **Fail-Safe Transaction Protocols:** No more worries about lost tokens during failed transactions. SafeSwap is designed to revert failed swaps without imposing additional platform fees. While regular blockchain gas fees are applicable for claiming tokens back, funds remain safeguarded.
* **User-Centric Interface Design:** Navigating through decentralized platforms can be complex, but with Safeswap, users are treated to an intuitive interface that simplifies the cross-chain swapping experience while maintaining the protocol's sophisticated backbone.

## Supported Blockchains

See the [Supported Blockchains](#supported-blockchains) page for a list of supported blockchains.

## Supported Wallets

See the [Supported Wallets](#supported-wallets) page for a list of supported wallets.


# How SafeSwap Works

The process of swapping native tokens from Wallet A on Blockchain X to Wallet B on Blockchain Y.

{% hint style="info" %}
Click [**here**](/user-guides/swap-tokens) to view a **detailed tutorial** on how to swap your tokens with SafeSwap.
{% endhint %}

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FpZ4A22ZlnLsTAlQRzo0Y%2Fimage.png?alt=media&amp;token=545a8560-74de-43eb-b250-c281c099ec60" alt=""><figcaption></figcaption></figure>

## 1. Initiate Swap <a href="#id-1-initiate" id="id-1-initiate"></a>

To initiate a swap, the user must select:

* a source **and** destination blockchain (both)
* connect a source **and** destination wallet (both)
* select the preferred token
* and fill in the amount to swap

## 2. Secure Swap <a href="#id-2-secure" id="id-2-secure"></a>

SafeSwap’s integrated UI creates a unique secret code which delivers hash data to the contract.

## 3. Lock Native Tokens on Source Chain <a href="#id-3-lock" id="id-3-lock"></a>

If a swap is initiated, SafeSwap will lock all tokens received from the source wallet in the related locked token pool on the source blockchain.

## 4. Unlock Native Tokens on Destination Chain <a href="#id-4-unlock" id="id-4-unlock"></a>

SafeSwap accounts for the required tokens necessary and uses the unique code to unlock tokens from a locked token pool on the destination blockchain.

## 5. Claim to Wallet <a href="#id-5-claim" id="id-5-claim"></a>

The user can claim the swapped tokens and they are transferred to the connected destination wallet.


# SHA Token

The SHA token is the primary utility token for both SafeSwap and the broader Safe Haven ecosystem.

## The Role of SHA in SafeSwap

Originally, SafeSwap was built to expand the Safe Haven ecosystem and thus the SHA token to multiple blockchains. The SHA token is integral to the Safe Haven ecosystem.

SafeSwap's synergy with SHA increases the token's utility across the entire Safe Haven ecosystem and especially across blockchains. And as all Safe Haven products require SHA as an element of utility, we anticipate higher demand as adoption of our products increases across multiple blockchains.

Since [fees on SafeSwap](/learn/fee-structure) are either paid in native gas tokens (Blockchain Gas + SafeSwap Platform Fees) or in fiat/stablecoins (Project Listing or Integration Fees), you are probably wondering how SHA is involved and how SafeSwap adds utility to it.

**Well, every swap on SafeSwap and every new project listing indirectly boosts demand for SHA:**

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FXMJao9poIpypuXnV7iX3%2Fimage.png?alt=media&amp;token=7a2760f8-7f1f-402e-97de-65f9187791ae" alt=""><figcaption></figcaption></figure>

## Token Utility Overview

1. **Rewards Pool for SafeNode Owners:** Part of SafeSwap [platform fees](/learn/fee-structure) are used to market buy SHA and are [distributed to SafeNode owners](/learn/fee-distribution).
2. **Permanent Token Burns:** Another part of the SafeSwap [platform fees](/learn/fee-structure) is used to market buy SHA that are then permanently burned, making SHA a scarcer and deflationary asset, enhancing its attractiveness to investors.
3. **Boost from Project Listing Fees:** The initial $10,000 of a [project's listing fee](/learn/fee-structure) contributes 30% to the SafeNode Rewards Pool, indirectly incentivizing SHA purchases.


# Fee Structure

In SafeSwap we can differentiate **3 types of fees**:

1. Default blockchain fee (gas)
2. SafeSwap platform fee
3. Project listing or API integration fee

## Fee #1: Default Blockchain Fee (Gas) <a href="#fee-1-default-blockchain-fee" id="fee-1-default-blockchain-fee"></a>

SafeSwap users pay for swaps in native gas tokens of the blockchains involved in the swap. For example, Ethereum uses ETH as gas, vechain uses VTHO.

This fee is automatically calculated based on live gas prices and is fully used to initiate the atomic swap on the source blockchain and to claim the swapped tokens on the destination blockchain.

{% hint style="info" %}
Safe Haven has no control over the blockchain fees as this is just how blockchains work.
{% endhint %}

## Fee #2: SafeSwap Platform Fee <a href="#fee-2-safeswap-platform-fee" id="fee-2-safeswap-platform-fee"></a>

For every swap made on SafeSwap the user will be charged a small fee known as the SafeSwap platform fee.

The SafeSwap platform fee will automatically be calculated and added to the total fee before a user initiates the swap.

**Below is a list of the different platform fees charged based on the blockchains involved:**

<table><thead><tr><th>Blockchain</th><th>Platform Fee</th><th data-hidden>Platform Fee</th><th data-hidden></th></tr></thead><tbody><tr><td>Ethereum</td><td>1%</td><td>1%</td><td></td></tr><tr><td>vechain</td><td>5%</td><td>5%</td><td></td></tr><tr><td>BNB Chain</td><td>5%</td><td>5%</td><td></td></tr><tr><td>Polygon</td><td>5%</td><td>5%</td><td></td></tr><tr><td>Base</td><td></td><td></td><td></td></tr><tr><td>Optimism</td><td></td><td></td><td></td></tr></tbody></table>

SafeSwap platform fees are paid in the same token as used for gas during the swap.

{% hint style="info" %}
Safe Haven has full control over these percentages and can update these at any time in order to adapt to changing market conditions and blockchain gas prices.
{% endhint %}

## Fee #3: Project Listing or API Integration Fee <a href="#fee-3-project-listing-fee" id="fee-3-project-listing-fee"></a>

**The third fee is not one that is paid by users, but one that is paid by projects.**

Every project that wants to list their token on SafeSwap to grow their project’s reach and go cross-chain, will be charged a one-time listing fee.

Same for projects that want to implement SafeSwap's protocol via a whitelabel API integration.

{% hint style="info" %}
The exact project listing fee is variable and is considered as classified business information of Safe Haven and are paid in fiat or a stablecoin.
{% endhint %}


# Fee Distribution

**All incoming** [**SafeSwap fees**](/learn/fee-structure) **are divided into three different parts:**

1. Foundation Pool
2. SafeNode Rewards Pool
3. Permanent Token Burns

## Part #1: Foundation Pool <a href="#part-1-foundation-pool" id="part-1-foundation-pool"></a>

This pool collects and holds fiat, stablecoins, and gas tokens gathered from both project listing fees and platform fees. It's set up to receive **50% of all platform fees** and **70% of the project listing fees**.

While occasionally this pool might tap into its reserves to purchase and retain SHA tokens, its primary role is to reinvest in business growth and development.

## Part #2: SafeNode Rewards Pool <a href="#part-2-safenode-rewards-pool" id="part-2-safenode-rewards-pool"></a>

Designed with the community in mind, especially those who own a [SafeNode](/learn/safenodes), this pool is the heart of the SHA Buyback Program. It uses its funds to acquire SHA directly from exchanges.

The exciting aspect of this system is that every transaction or swap on SafeSwap indirectly fuels the demand for SHA tokens. A substantial **45% of all platform fees** get directed here.

Additionally, when new projects decide to list on SafeSwap, they contribute **30% of the listing fee** (of the first $10,000) to this pool. As a result, SHA tokens bought through this mechanism are subsequently distributed amongst [SafeNode](/learn/safenodes) owners.

This distribution is determined based on the tier and activity level of each node, making the ownership of a [SafeNode](/learn/safenodes) even more enticing due to the potential rewards.

## Part #3: Permanent Token Burns <a href="#part-3-permanent-token-burns" id="part-3-permanent-token-burns"></a>

Beyond the rewards and growth, there's an embedded mechanism to ensure the longevity and scarcity of SHA tokens. A small **5% of the collected** [**platform fees**](/learn/fee-distribution) is used to purchase SHA tokens and instead of redistributing or holding, these tokens are permanently removed from circulation by being burned. This process inherently makes SHA a deflationary asset.

As the SafeSwap platform continues to grow, welcoming more projects and witnessing more swaps, the availability of SHA reduces, making its proposition even more attractive.

In essence, the more the token is utilized, the lesser it becomes in supply.


# SafeNodes

Owners of a SafeNode are given a share of all SafeSwap Fees.

## Earning SafeSwap Rewards with Your SafeNode

A big part of SafeSwap’s reward system is centered around benefiting our community and in particular the SafeNode owners.

This means that the SafeNode Rewards Pool will be fully dedicated to a continuous SHA Buyback Program and thus will be used to market buy SHA off exchanges. Every swap being made on SafeSwap will indirectly cause demand for SHA tokens to go up since a part of the SafeSwap platform fee will be used to buy SHA.

The same goes for every project being listed on SafeSwap. They pay a project listing fee and 30% of the first $10,000 of a project’s listing fee will be added to the SafeNode Rewards Pool as well.

To be precise: 45% of the SafeSwap platform fee will be sent to the SafeNode Rewards Pool.

[Learn more about the SafeNode Program](https://safehaven.io/sha/safe-nodes/)

All SHA tokens that are market bought with the SafeNode Rewards Pool will then be distributed to SafeNode owners. Distribution of SHA tokens will, as always, be based on node tiers and how many nodes that are active in that particular tier.

## Setup a SafeNode with The SafeNode Mobile App

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FOCJ2PVQZyUtpCEN3fVfl%2Fimage.png?alt=media&amp;token=43e6d14f-8267-4da8-b281-60d7a08d0d19" alt=""><figcaption></figcaption></figure>

To setup a SafeNode, please download our **SafeNode** app and link the **keystore of your wallet**.

[Click here for a walkthrough](https://safehaven.io/safenode-tutorial-how-link-your-wallet-and-bind-your-node/)

{% embed url="<https://apps.apple.com/us/app/safenode/id1471425230>" %}

{% embed url="<https://play.google.com/store/apps/details?id=io.safehaven.safenode>" %}


# Glossary

## SafeSwap

SafeSwap is a decentralized platform and protocol that enables the swapping of native tokens between EVM-compatible blockchains, allowing users to securely transfer tokens across different networks without the need for intermediaries or trusted third parties.

## Atomic Swap

Atomic swap is a decentralized mechanism that allows for the peer-to-peer exchange of cryptocurrencies or tokens directly between two parties (or wallets) on different blockchain networks, ensuring secure and trustless asset transfers without the involvement of intermediaries.

## Native Token

A Native Token refers to a cryptocurrency or digital asset that operates directly on its native blockchain, without being wrapped or represented by another token.

## Wrapped Token

A Wrapped Token is a token that represents another cryptocurrency or asset. It involves creating a separate token that is backed by an equivalent amount of the original native token. The wrapped token is typically pegged to the value of the original native token, and its issuance and redemption are managed by custodians or smart contracts.

## EVM

The Ethereum Virtual Machine (EVM) is a decentralized runtime environment that executes smart contracts on the Ethereum blockchain, enabling the execution of code written in Ethereum's programming language, Solidity.

## EVM Compatible

EVM Compatible refers to blockchain platforms or networks that are designed to be fully or partially compatible with the Ethereum Virtual Machine (EVM) and its programming model, allowing developers to use similar tools and languages to build and deploy smart contracts.

## Cross-Chain

Cross-chain refers to the interaction and interoperability between different blockchain networks, enabling users to access assets and services across multiple networks. Cross-chain dApps specifically facilitate the transfer of assets or data between different blockchains.

## Multichain

Multichain refers to the operation of a decentralized application on multiple blockchain networks simultaneously, providing users with more options and features. However, it does not necessarily imply direct asset transfers between those blockchains.

## Swapping

Swapping involves the exchange of one cryptocurrency or token for another, either within the same blockchain network or across different blockchain networks, typically aiming for a one-to-one exchange ratio without focusing on the market value or price of the tokens involved.

## Trading

Trading involves the buying and selling of cryptocurrencies or tokens on a marketplace or exchange platform to take advantage of price fluctuations and generate profits.

## Cross-Chain Swap

Cross-chain swapping, or interchain swapping, refers to the process of exchanging cryptocurrencies or tokens between different blockchain networks, allowing users to transfer assets seamlessly across disparate blockchain ecosystems, promoting interoperability and liquidity.

## Token Bridge

A Token Bridge is a technology or protocol that facilitates the transfer of tokens or assets between different blockchains, enabling interoperability and connectivity.

## DEX

A DEX is a type of cryptocurrency exchange that operates in a decentralized manner, allowing users to trade digital assets directly with each other without the need for intermediaries.

## HTLC

HTLC, or Hash Time-Locked Contract, is a smart contract mechanism used in blockchain networks to facilitate secure and trustless transactions. It employs cryptographic hash functions and time locks to ensure the conditional execution of a transaction. With an HTLC, the sender locks a certain amount of cryptocurrency or assets in a contract, requiring the recipient to provide a specific pre-image within a specified time to claim the funds. If the pre-image is not provided within the given timeframe, the funds are returned to the sender.

## Transaction Fee

A transaction fee is a small amount of cryptocurrency paid to miners or validators as compensation for processing and validating a transaction on a blockchain network. In the context of SafeSwap, a transaction fee is incurred when initiating a swap on the source blockchain and when claiming tokens on the destination blockchain.

## Platform Fee

The platform fee is an additional fee charged by SafeSwap for utilizing its protocol. This fee is a small premium on top of the standard transaction fees and is designed to support the development and maintenance of SafeSwap.

## Listing Fee

The listing fee is a payment required from projects or token issuers to have their tokens listed on SafeSwap and enable cross-chain functionality. This fee is typically charged to cover the costs associated with evaluating, integrating, and maintaining the token's compatibility with SafeSwap's infrastructure and ensuring its smooth operation across different blockchain networks. The listing fee helps support the ongoing development and expansion of SafeSwap.

## Token Minting

Token Minting refers to the process of creating new tokens on a blockchain. It involves the generation and issuance of new tokens according to a specific protocol or smart contract.

## Token Burning

Token Burning is the process of permanently removing tokens from circulation. It involves sending tokens to an address or smart contract from which they cannot be accessed or spent.

## Token Locking

Token Locking refers to the temporary or permanent restriction placed on tokens, preventing them from being transferred, sold, or used for a specific period or until certain conditions are met.

## Token Unlocking

Token Unlocking is the process of removing the restrictions or limitations placed on tokens that were previously locked. Once tokens are unlocked, they become freely transferable, tradable, and usable according to the token's underlying smart contract rules.

## Native Token Bridge

A Native Token Bridge is a platform that enables the direct transfer of native tokens between different blockchains without the need for wrapping or creating a separate representation of the token. It allows users to transfer tokens from one blockchain to another while maintaining the same token's native properties and characteristics. Native Token Bridges facilitate interoperability and liquidity between blockchains by enabling the seamless movement of tokens without additional wrapping or conversion steps.

## Wrapped Token Bridge

A Wrapped Token Bridge involves the creation of a separate representation of a token on a different blockchain. It typically requires wrapping the original native token by a custodian or a smart contract to issue a wrapped version of the token on the target blockchain.

## Total Supply

Total supply represents the total number of coins or tokens that have been created or mined thus far, including both circulating supply and any locked or reserved tokens. It encompasses all coins that have been issued or generated and excludes any verifiably burned tokens. Total supply gives an overview of the current state of the cryptocurrency's issuance and distribution, including tokens that may be held by the project team, locked in smart contracts, or allocated for specific purposes.

## Circulating Supply

Circulating supply refers to the number of cryptocurrency coins or tokens that are actively circulating in the market and available for trading. It represents the subset of the total supply that is not locked or held by the project team or inaccessible for various reasons. Circulating supply is an important metric used to calculate the market capitalization of a cryptocurrency and is generally more relevant for assessing the current supply-demand dynamics and price performance.

## Max Supply

Max supply is the maximum predetermined limit on the number of coins or tokens that will ever be created or mined in the lifetime of a cryptocurrency. It represents the upper bound on the total supply and signifies the scarcity of the cryptocurrency. The max supply is typically determined by the protocol rules and cannot be exceeded. It provides clarity on the future inflation rate and ensures that the cryptocurrency maintains its scarcity and value proposition.


# Swap Tokens

In this example we will swap native SHA tokens from vechain to native SHA tokens on Polygon.

## 1. Launch SafeSwap <a href="#id-1-launch-the-safeswap-platform" id="id-1-launch-the-safeswap-platform"></a>

Navigate to the SafeSwap platform via [https://app.safeswap.io](https://app.safeswap.io/)

![](https://docs-test.safeswap.io/img/SafeSwap-teaser5.PNG)

## 2. Select the Source Blockchain <a href="#id-2-choose-the-source-blockchain-example-vechain" id="id-2-choose-the-source-blockchain-example-vechain"></a>

This is where your tokens are currently held. For this example, you'd choose vechain.

![](https://docs-test.safeswap.io/img/howtoswap2.PNG)

## 3. Connect Your Source Wallet <a href="#id-3-connect-your-wallet" id="id-3-connect-your-wallet"></a>

Make sure you connect the appropriate wallet where your SHA tokens are currently stored.

![](https://docs-test.safeswap.io/img/howtoswap3.PNG)

## 4. Choose The Preferred Token and Amount <a href="#id-4-your-source-wallet-should-now-be-connected" id="id-4-your-source-wallet-should-now-be-connected"></a>

Upon connecting your source wallet, you can now pick the token you wish to swap (SHA in this case). Enter the quantity of tokens you desire to exchange.

For extra security, we display both the token contract address and the SafeSwap smart contract address for the selected chain, allowing you to verify details.

![](https://docs-test.safeswap.io/img/howtoswap4.PNG)

## 5. Configure Destination Blockchain and Wallet <a href="#id-5-repeat-steps-234-for-the-destination-wallet" id="id-5-repeat-steps-234-for-the-destination-wallet"></a>

The tokens you'll receive on the destination chain (Polygon, in this case) will be identical to the ones chosen on the source chain.

![](https://docs-test.safeswap.io/img/howtoswap5.PNG)

## 6. Ensure Source and Destination Wallets Are Connected <a href="#id-6-now-you-have-both-source-and-destination-wallet-connected" id="id-6-now-you-have-both-source-and-destination-wallet-connected"></a>

![](https://docs-test.safeswap.io/img/howtoswap6.PNG)

## 7. Approve Token and Amount to Swap <a href="#id-7-verify-your-token-and-the-amount-which-you-want-to-swap-from-source-to-destination-chain" id="id-7-verify-your-token-and-the-amount-which-you-want-to-swap-from-source-to-destination-chain"></a>

For first-time swaps, it's essential to authorize the swap contract to move your tokens.

Once done, the SafeSwap routing gets generated and the swap fees estimated.

![](https://docs-test.safeswap.io/img/howtoswap7.PNG)

![](https://docs-test.safeswap.io/img/howtoswap7a.PNG)

## 8. Initiate Swap <a href="#id-8-initiate-the-swap-with-swap-button-below" id="id-8-initiate-the-swap-with-swap-button-below"></a>

Click the "Swap" button to initiate.

![](https://docs-test.safeswap.io/img/howtoswap8.PNG)

## 9. Generate Secret Hash Code <a href="#id-9-confirm-creation-of-the-secret-hash-code-which-will-be-used-later-to-claim-swapped-tokens" id="id-9-confirm-creation-of-the-secret-hash-code-which-will-be-used-later-to-claim-swapped-tokens"></a>

As a safety measure, SafeSwap assigns each swap a unique code.

Important note: To claim your tokens on the destination chain, ensure you stick to the same device and within the same browser throughout the entire swapping procedure.

![](https://docs-test.safeswap.io/img/howtoswap9.PNG)

## 10. Pay Fees for Both Blockchains Involved <a href="#id-10-send-the-required-fees-to-each-chain-to-execute-the-swap" id="id-10-send-the-required-fees-to-each-chain-to-execute-the-swap"></a>

If any pop-ups appear, sign the transaction using your wallet's PIN or password.

![](https://docs-test.safeswap.io/img/howtoswap10.PNG)

## 11. Create Swap <a href="#id-11-after-the-fees-are-paid-the-swap-is-ready-to-proceed" id="id-11-after-the-fees-are-paid-the-swap-is-ready-to-proceed"></a>

The swap might take a while. Remember to keep SafeSwap open and be patient during this period.

Any prompts asking to sign a transaction will require your wallet's PIN or password.

![](https://docs-test.safeswap.io/img/howtoswap11.PNG)

## 12. Claim Funds <a href="#id-12-the-swap-was-successfully-created-now-you-can-claim-your-funds" id="id-12-the-swap-was-successfully-created-now-you-can-claim-your-funds"></a>

After SafeSwap's atomic swap protocol finishes, it's time to claim your SHA tokens on the Polygon chain. Click the "Claim Funds" button.

![](https://docs-test.safeswap.io/img/howtoswap12.PNG)

## 13. Swap Successful!

Upon successful claiming, the swapped tokens will be visible in your designated destination wallet.

And that's it, a successful atomic cross-chain swap of native SHA tokens!

![](https://docs-test.safeswap.io/img/howtoswap12a.PNG)


# Token Dashboard

SafeSwap supports dashboard features, giving users a numerical and graphic visualization of each token listed on SafeSwap.

You can check token information, supply and token distribution of each chain.

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FLjX5wl5oEnKei9nihSM0%2Fdashboard.png?alt=media&amp;token=2b8bd3a6-3aef-42ac-8e18-487c8851b526" alt=""><figcaption></figcaption></figure>

You can check out the total supply of a selected chain, and the split of unlocked and locked (smart contract or liquidity pool) tokens.

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FAw5OfExDWrBqw1LNJWrn%2Fdashboard2.png?alt=media&amp;token=313137af-4d8f-4af8-ac3d-9bcdfe3aa269" alt=""><figcaption></figcaption></figure>


# Cross-Chain Atomic Swaps

## What Are Cross-Chain Atomic Swaps? <a href="#what-is-an-atomic-swap" id="what-is-an-atomic-swap"></a>

Cross-chain atomic swaps facilitate direct transfers of tokens between different blockchains, operationalizing only when both involved parties deposit a stipulated amount of tokens into the exchange contract. This allows users to exchange tokens without dependency on middlemen, thereby mitigating counterparty risks.

The concept of “Atomicity” refers to the principle where transactions are either executed in their entirety or not executed at all. Following this principle, atomic swaps either successfully conduct the swap when all conditions are met, or refund the deposited tokens to the respective owner.

Most atomic swap-enabled wallets and blockchains use smart contracts. Smart contracts are programs within blockchains that execute when certain conditions are met.

## How Do Atomic Swaps Work? <a href="#how-to-do-an-atomic-swap" id="how-to-do-an-atomic-swap"></a>

Atomic swaps employ a Hashed Time-Locked Contract (HTLC), serving as a cryptographic safeguard or a “virtual safe,” ensuring the security of user funds and triggering only when the contract receives the accurate amount of tokens.

To unlock the tokens, each party involved must confirm the receipt within a designated timeframe.

Most cryptocurrency projects develop their products on a single blockchain, and this limits the project to operating within that ecosystem. This means if there is a project on Ethereum, users need to buy the token on Ethereum blockchain in order to use the product/service.

If a project wants access to other blockchain ecosystems, then they will need to deploy token contracts and smart contracts on those blockchains.

Atomic swaps allow users to transfer native tokens across different blockchains, without middlemen.


# HTLC

Hashed Time-Locked Contract

## What is HTLC?

HTLC, or Hashed Time-Locked Contract, is a smart contract mechanism used in blockchain networks to facilitate secure and trustless transactions. It employs cryptographic hash functions and time locks to ensure the conditional execution of a transaction.

With an HTLC, the sender locks a certain amount of assets in a contract, requiring the recipient to provide a specific pre-image within a specified time to claim the funds.

If the pre-image is not provided within the given timeframe, the funds are returned to the sender.

HTLCs are particularly useful in cross-chain transactions and atomic swaps, where two parties want to exchange cryptocurrencies without the need for intermediaries, ensuring neither party can cheat the other.

## **How SafeSwap Uses HTLC**

SafeSwap, as mentioned, is both a platform and protocol for atomic swaps, which in this case are peer-to-peer transfers of tokens between a user's own wallets across different blockchains, without requiring intermediaries.

For cross-chain transfers, the integrity, security and trustworthiness of the swaps are paramount, and that's where HTLCs come in.

When a user initiaties a swap on SafeSwap, an HTLC is created.

The HTLC ensures that:

1. The tokens are locked up securely in the correct Locked Token Pool. Same for unlocking.
2. The intended destination wallet can only claim the funds by providing a cryptographic proof within a set time frame. The SafeSwap protocol has this proof mechanism built-in and since it's browser-based, the swap should be done using the same device and browser. By doing this, users don't need to handle any code themselves.
3. If the necessary proof isn't provided on time, the swap is canceled, and the original source wallet can claim back the tokens.

Through this mechanism, SafeSwap can facilitate cross-chain transactions, such as [swapping SHA from vechain to Polygon](/user-guides/swap-tokens) for example, or any other supported blockchain, with a high level of trust and security.


# Security Measures

Safe Haven maintains the highest possible standard of safety and quality.

## Built-In Security Measurements

### Security Code

Utilizing Hashed Time-Locked Contracts (HTLC), we assign a unique code to each locked token pool for every destination chain through our advanced backend, ensuring accurate and secure swapping and safeguarding against unauthorized or incorrect transactions.

### Additional Confirmations

To fortify the security of high-value transactions, larger swaps necessitate additional confirmations. Specifically, swaps exceeding $10,000 require a minimum of 5 confirmations to ensure precise and secure execution, providing an extra layer of certainty and protection for users.


# Supported Blockchains

SafeSwap works with blockchains based on Ethereum Virtual Machine (EVM). Additional blockchains will be added over time, beginning with a larger pool of Ethereum Virtual Machine-based protocols.

Non-EVM blockchains or specifically requested blockchains, will be added at the discretion of Safe Haven and/or partnership organizations.

## Supported

<table><thead><tr><th width="247">Logo</th><th width="117">Chain</th><th width="117">Gas Token</th><th>Block Explorer</th></tr></thead><tbody><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FbB0XGzhPHPuACweyTPp2%2Fvechain.png?alt=media&amp;token=4a911a9b-1e26-4f2a-87cb-59bc65b2d696" alt=""></td><td>vechain</td><td>VTHO</td><td><a href="https://explore.vechain.org/">https://explore.vechain.org</a></td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FXleqjP9ykdGb69kBhHVT%2Fethereum.png?alt=media&amp;token=abaf6160-99b9-41b4-a912-99ef78a5a10e" alt=""></td><td>Ethereum</td><td>ETH</td><td><a href="https://etherscan.io/">https://etherscan.io</a></td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FVwdRdUQn8lVT6bmLfY8w%2Fpolygon.png?alt=media&amp;token=cae63d22-da91-44a1-992f-8c47f3402dbb" alt=""></td><td>Polygon</td><td>MATIC</td><td><a href="https://polygonscan.com/">https://polygonscan.com</a></td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FqotXqkSOAPQgsbmPoxD9%2Fbnb-chain.png?alt=media&amp;token=7818c08b-8711-4279-af56-24ee95e623a0" alt=""></td><td>BNB Chain</td><td>BNB</td><td><a href="https://bscscan.com/">https://bscscan.com</a></td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FooUf6qfcQbNJwXW61p4S%2Fbase.png?alt=media&amp;token=76ec06ff-d323-416e-9de8-349aec8244b9" alt=""></td><td>Base</td><td>ETH</td><td><a href="https://basescan.org/">https://basescan.org</a></td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2Fu5UfxCGFN4vMyYDrGEvY%2Foptimism.png?alt=media&amp;token=332a5941-0e04-4544-a4b5-067f55fbb383" alt=""></td><td>Optimism</td><td>ETH</td><td><a href="https://optimistic.etherscan.io/">https://optimistic.etherscan.io</a></td></tr></tbody></table>


# Supported Wallets

SafeSwap supports multiple wallets and can be expanded upon request for enhanced flexibility, thereby limiting the barriers of entry for the end-user.

## Wallet Types

The integrated wallets will typically be one of **two wallet types**:

* **Decentralized Wallets** to ensure no custody parties are involved other than the owner
* **Custodial Hybrid Wallets** that pass our vigorous internal security expectations

## Supported

<table><thead><tr><th width="221">Logo</th><th width="196.33333333333331">Wallet</th><th>Blockchains</th></tr></thead><tbody><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FyhVO9uOrusWfPzH8zhyL%2Fcomet.png?alt=media&amp;token=752077d1-ec28-4514-93fc-7cc4030327ed" alt=""></td><td>Comet</td><td>vechain</td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FlLwNA1jdxlUX7aC4kdAm%2Fmetamask.png?alt=media&amp;token=c30cb45b-20b4-456c-bf90-4ef4f5ad2947" alt=""></td><td>MetaMask</td><td>Ethereum, Polygon, BNB Chain, Base, Optimism</td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2F6nBDRl7f8L8Mk1dSGM7z%2Fvenly.png?alt=media&amp;token=e649c148-cc76-4b86-b12c-74f97a2bd8e8" alt=""></td><td>Venly</td><td>vechain, Ethereum, Polygon, BNB Chain</td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FdI1her1q5MjM6l4cIQYR%2Fbinance-wallet.png?alt=media&amp;token=b61c2f68-e565-46dc-a785-a063e9f4d95a" alt=""></td><td>Binance Wallet</td><td>Ethereum, BNB Chain</td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FOWDueCli52zkyUH3iKno%2Fimage.png?alt=media&amp;token=317bb318-f6c6-4742-8cd5-3b66b7c457b0" alt=""></td><td>Sync2</td><td>vechain</td></tr><tr><td><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FcK7L41v4pOdiGuPLodEp%2Fimage.png?alt=media&amp;token=3d3dfd8f-d68d-4218-a50d-9861073a0873" alt=""></td><td>WalletConnect</td><td></td></tr></tbody></table>


# Audits

## Audited by Red4Sec

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FlPHHaHj1f3Vg3AARAfQh%2Fred4sec-safeswap.png?alt=media&amp;token=07e583a9-3f88-4657-953f-7423bc6e16ed" alt=""><figcaption></figcaption></figure>

SafeSwap’s source code is audited by Red4Sec, an organization known for fielding cybersecurity experts and security analysts with many years of experience both inside and outside the blockchain environment.

**Open the SafeSwap audit report below.**

{% file src="/files/EoAcLAhG9MGBbVaBsSxv" %}


# Hello World!

Originally built to expand the Safe Haven ecosystem to multiple blockchains, we are now offering the opportunity to other projects to integrate SafeSwap and easily adopt a multichain strategy too.

**Projects and builders can integrate SafeSwap's atomic swapping protocol in two ways:**

1. [SafeSwap Token Listing](/builders/token-listing)
2. [Whitelabel Integration (API)](/builders/whitelabel-integration)

## Benefits for Builders

* **Lower Development & Operational Costs:** By leveraging SafeSwap’s atomic swapping protocol, quickly and efficiently achieve cross-chain capabilities. Save significant resources, both in terms of time and money. Options for [API](/builders/api-integration-guide) and [whitelabel integrations](/builders/whitelabel-integration) are available for enhanced adaptability.
* **Broaden Project Visibility and User Reach:** Integration with SafeSwap propels your project into a wider audience sphere. Not only does this elevate your project's utility, but the exposure across multiple blockchains ensures organic user base expansion.
* **Preservation of Tokenomic Integrity:** With SafeSwap's smart cross-chain locking/unlocking mechanism, uphold the purity of your project's tokenomics. There will be no exceeded minting, burning, or supply division across chains. Everything remains atomic and consistent.
* **Boundless Multichain dApp Development:** Use the unique features of diverse blockchains (be it technology, speed, cost, support or partnerships) and present your innovative solutions to entirely new user demographics.
* **Optimal User Security Measures:** SafeSwap introduces an advanced security layer, a mechanism ensuring that funds are claimable exclusively on the device that initiated the swap. A critical protective feature that boosts user trust.
* **Elimination of External Liquidity Dependencies:** SafeSwap operates independently of external liquidity pools (LPs), promising continuous access to users and nullifying slippage. Enjoy the freedom of a self-sufficient system that ensures the best user experience.


# Cross-Chain Use Cases

SafeSwap's protocol enables a variety of cross-chain use cases

{% hint style="info" %}
Below are examples of transformative use cases that could be build using SafeSwap.
{% endhint %}

SafeSwap enables a variety of cross-chain use cases for builders looking to implement SafeSwap's atomic swapping protocol into their own project.

This broad adaptability unlocks opportunities previously unattainable, bringing innovation, accessibility and utility to Web3 projects.

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2F8FGQH6uh4DjrJfe04LKd%2Fimage.png?alt=media&amp;token=5a38a73c-bb42-46b9-a5a6-f87c2fe6a7cd" alt="" width="563"><figcaption></figcaption></figure>

## Native Token Swaps

SafeSwap provides a secure and efficient solution for transferring native tokens between different blockchains, preserving the integrity and authenticity of the tokens.

* **Decentralized Cross-Chain Exchanges**: Creation of decentralized platforms where users can directly swap native tokens from one chain to another without central intermediaries.
* **Chain-Specific Rewards**: Projects can reward users in tokens specific to the chain they are interacting with, enhancing user experience.

## Cross-Chain Liquidity for DeFi Protocols

SafeSwap enables DeFi projects to enable cross-chain liquidity, enhancing trading, lending and borrowing experiences across multiple blockchains.

This optimizes the protocol’s reach and usability, creating a more inclusive and versatile ecosystem.

* **Cross-Chain Collateralization**: DeFi platforms could accept collateral from different blockchains, diversifying risk and increasing the types of assets that can be used.
* **Interchain Loan Markets**: Borrowers and lenders from different chains can interact, broadening the scope and liquidity of decentralized lending platforms.

## Multichain Tokens

SafeSwap enhances token utility by facilitating accessibility across diverse blockchains. For instance, a gaming token available on multiple blockchains can be utilized across different gaming ecosystems, enriching user experiences and broadening the token’s adaptability.

* **Cross-Platform Loyalty Points**: Earning loyalty points on an e-commerce platform operating on one chain and spending them on a rewards platform on another chain.
* **Universal Gaming Tokens**: A token earned in a game on one chain could be spent in another game on another chain, allowing players to maximize their in-game earnings.
* **Global Event Tokens**: Attendees of a global event could purchase access tokens on their preferred blockchain and redeem them on another, streamlining event participations.

## Multichain Dapps

SafeSwap enables developers to create decentralized applications utilizing the distinctive features of various blockchains. It paves the way for seamless functionality of dApps across multiple chains, encouraging creativity and broadening user acquisition.

* **Integrated Wallet Swaps:** Wallets can simply integrate SafeSwap as a white label solution and  users would then be able to swap cross-chain without leaving the wallet UI.
* **Interoperable DAOs**: Decentralized Autonomous Organizations could operate and make decisions across multiple blockchains, leveraging resources and governance tokens from different ecosystems.
* **Cross-Chain Gaming**: Gamers could use assets and achievements from one game on one chain in another game on a different chain.
* **Multi-Chain Payment Gateways**: Merchants could accept payments in various tokens across different chains, enhancing flexibility for customers.
* **Unified Social Platforms**: A social networking dApp where a user's profile or reputation earned  on one blockchain can be effortlessly recognized and redeemed on a social platform operating on another blockchain.
* **Interchain DeFi Aggregators**: Users could track their investments, yields and staking rewards across multiple DeFi platforms operating on different chains all from a single UI.


# Token Listing

Elevate your token's accessibility and utility by enabling atomic cross-chain swaps through a listing on SafeSwap.

## Transform Your Token into A Multichain Token

* **Scale Your User Base:** Unlock exponential growth opportunities and enhance token composability by showcasing your token on SafeSwap.
* **Avoid Wrapped Tokens and Malicious Middlemen:** Transform your token into a multichain token, eliminating the necessity for wrappers or reliance on potentially harmful intermediaries.
* **Save Time and Costs:** Achieve secure interoperability with unparalleled efficiency and reduced costs compared to developing an in-house solution.

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2FtRqjA9tKzhx40yjgzcCi%2Fimage.png?alt=media&amp;token=61bbd2cf-9142-4854-807e-c88c33160ea5" alt="" width="563"><figcaption></figcaption></figure>


# Whitelabel Integration

Integrate SafeSwap’s atomic swapping protocol directly in to your own dApps and make them accessible across multiple chains!

## Start Buildling Multichain Applications Today!

Integrating SafeSwap’s Cross-Chain Atomic Swapping Protocol as a whitelabel solution is a seamless and straightforward process. This integration facilitates a customizable and brandable platform for cross-chain token swaps.

The simplicity of this process allows you to quickly implement a multichain strategy with secure atomic swaps, enhancing your ecosystem and user experience without the complexity of building your own solution from scratch.

* **Robust Developer API:** Our comprehensive documentation is designed for developers seeking to interact with our smart contracts and API, facilitating smooth swaps across various chains.
* **Use Your Own Branded Front-end:** Interact directly with the SafeSwap smart contract and API using your branded front-end, ensuring a seamless and consistent brand experience.
* **Enhance User Engagement:** Offering multi-chain access within your dApps can significantly enhance user engagement and retention, opening up new possibilities for user interaction.

<figure><img src="https://705955493-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fpwz7sHAgKUZ7jDj10SoO%2Fuploads%2F0MYHoYkhcqwKXj8IyuRV%2Fimage.png?alt=media&amp;token=64114e4c-cb3e-4b4b-a311-cf73486ec597" alt="" width="563"><figcaption></figcaption></figure>


# API Integration Guide

This guide will provide details about integrating your dapp with SafeSwap. Your front end will interact with the SafeSwap smart contract and with our API. Let's get started!


# Prerequisites

There are some capabilities your web app will need

1. The ability to interact with smart contracts on all the chains you wish to support (Vechain, Ethereum, Polygon, etc.)
2. The ability to make API requests to our SafeSwap API. An API Key will be required, contact us to acquire one.&#x20;


# What is a Swap?

SafeSwap uses the "atomic swap" technique to guarantee that a swap occurs in a trustless manner. The idea is explained fully [here](https://www.investopedia.com/terms/a/atomic-swaps.asp).

## &#x20;Steps in a Swap

1. **Initiate a Swap:** User sends funds to the swap contract with a hashed preimage in the ecosystem where they currently hold their assets.
2. **Send Fees:** Pay the required fees on the original chain and the destination chain. These fees cover our portion of the smart contract interactions.
3. **Creating the Swap in our API:** Send an API request to our server to let us know about the smart contract interaction and the details of the swap that the user is trying to do. This includes information about what chain the swap should be sent to, the token, and more.
4. **Wait for us to set up the Swap:** Poll our API occasionally (usually takes about 30 seconds) to find the status of the swap on the target chain.
5. **Complete the Swap on target chain:** User claims new funds on the destination chain using their preimage. Then our system claims the original funds on the original chain and the swap is complete.


# Perform a Swap

This covers each of the steps of a Swap

There are sections for each step in [What is a Swap?](/builders/api-integration-guide/what-is-a-swap)


# Initiate a Swap

The first step is to create a swap in the smart contract

Setting up a swap in the target chain's smart contract involves a single call to the smart contract but it requires some preparation.

## Calling the Smart Contract

Get values for `SWAP_CONTRACT_ADDRESS` [here](/builders/api-integration-guide/smart-contract-details#contract-addresses)

### Example

<pre class="language-javascript"><code class="lang-javascript">const SWAP_CONTRACT_ADDRESS = "0x..."; // get this from the docs for your network
const ABI = '{
  "constant": false,
  "inputs": [
    {
      "internalType": "address",
      "name": "_receiver",
      "type": "address"
    },
    {
      "internalType": "bytes32",
      "name": "_hashlock",
      "type": "bytes32"
    },
    {
      "internalType": "uint256",
      "name": "_timelock",
      "type": "uint256"
    },
    {
      "internalType": "bool",
      "name": "_allowLateWithdrawal",
      "type": "bool"
    },
    {
      "internalType": "address",
      "name": "_tokenContract",
      "type": "address"
    },
    {
      "internalType": "uint256",
      "name": "_amount",
      "type": "uint256"
    }
  ],
  "name": "newContract",
  "outputs": [
    {
      "internalType": "bytes32",
      "name": "contractId",
      "type": "bytes32"
    }
  ],
  "payable": false,
  "stateMutability": "nonpayable",
  "type": "function"
}';

erc20ApproveABI = '{
    "constant": false,
    "inputs": [
        {
            "name": "_spender",
            "type": "address"
        },
        {
            "name": "_value",
            "type": "uint256"
        }
    ],
    "name": "approve",
    "outputs": [
        {
            "name": "",
            "type": "bool"
        }
    ],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
}';

const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

/**
* This MUST be our SafeSwap receiver address if you want Safeswap to complete the swap.
* It indicates that this receiver will ultimately receive the original coins on the original network. 
* It is NOT the receiver on the destination chain, which will be identified in a future step.
* https://docs.safeswap.io/builders/api-integration-guide/our-swap-addresses
*/
const receiver = "0x..."

const secret = crypto.randomBytes(32); // You will need this secret later to unlock the funds on the destination chain.
const hash = crypto.createHash('sha256').update(secret).digest();
const hashlock = '0x' + hash.toString('hex');

// The timelock is the timestamp at which the swap can be refunded.
// For Safeswap, it has to be atleast 4 hours in the future.
const timelock = (Date.now() / 1000) + (4 * 60 * 60); // 4 hours in the future, in seconds.

// Late withdrawals are a safety feature and should be set to true.
// This allows the swap to continue even if the time period has passed.
const allowLateWithdrawal = true;

// This is the contract address for the ERC20 token that is being swapped away from.
const tokenAddress = "0x...";

// Amount in Wei of tokens the user wishes to swap.
// NOTE: This amount needs to be approved ahead of time by the user for the SafeSwap contract address.
const amount = ethers.utils.BigNumber.of("30000000000000000000"); // 30 tokens, with 18 decimals, in Wei.


// First a token approval must be made for this token to the SWAP_CONTRACT_ADDRESS
const token = new ethers.Contract(tokenAddress, erc20ApproveABI, signer);
<strong>await token.approve(SWAP_CONTRACT_ADDRESS, amount);
</strong>
const safeSwap = new ethers.Contract(SWAP_CONTRACT_ADDRESS, ABI, signer);
const response = await safeSwap.newContract(receiver, hashlock, timelock, allowLateWithdrawal, tokenAddress, amount, { gasLimit: 300000 });
</code></pre>


# Send Fees

Fees cover our portion of the smart contract interactions

Fees. To account for the costs of each blockchain, fees must be paid on both the original network and the destination network. This covers SafeSwap's portion of the smart contract interactions.

### Find the Current Fees

SafeSwap has an API endpoint that will tell you what the fees need to be. Call this API and then have the user send these fees.

**Important:** The fees must be sent by the same user who made the Swap in the smart contract in [Initiate a Swap](/builders/api-integration-guide/perform-a-swap/initiate-a-swap).

Get the addresses for `SAFESWAP_FEE_ADDRESS_...` [here](/builders/api-integration-guide/our-swap-addresses), they are the same as the `SWAP_ADDRESSES`

**For Vechain:** the fee is to be paid in **VTHO**, not VET.

### Example

```javascript
const apiResponse = await fetch(`${SWAP_API_URL}/gas-estimate?sourceChain=VECHAIN&targetChain=ETHEREUM`, {
    headers: {
      'Content-Type': 'application/json',
      'X-API-KEY': 'MY_API_KEY'
    }
});

const fees = await apiResponse.json();

const originalChainFee = fees.sourceChain;
const destinationChainFee = fees.targetChain;

const originalTx = await signerOnOriginalChain.sendTransaction({to: SAFESWAP_FEE_ADDRESS_VECHAIN, value: originalChainFee})
const destinationTx = await signerOnDestinationChain.sendTransaction({to: SAFESWAP_FEE_ADDRESS_ETHEREUM, value: destinationChainFee})

const originalFeeTxId = originalTx.hash;
const destinationFeeTxId = destinationTx.hash;
```


# Create the Swap in API

After creating a Swap in the contract, send it to our API so we can act on it.

### Example

```javascript
const response = ... // response is from the smart contract call when you created the swap.
const receipt = await provider.getTransactionReceipt(response.transactionId);

const contractId = receipt.logs.find(log => log.address.toLowerCase() === SWAP_CONTRACT_ADDRESS.toLowerCase()).topics[1];

const apiResponse = await fetch(`${SWAP_API_URL}/swaps`, {
    method: "POST",
    body: JSON.stringify({
        sourceChain: "VECHAIN",
        sourceContractId: contractId,
        sourceSender: usersAddressOnVechain,
        sourceFeeTx: originalFeeTxId,
        targetChain: "ETHEREUM",
        targetReceiver: usersAddressOnEthereum,
        targetTokenAddress: TOKEN_ADDRESS_ON_ETHEREUM,
        targetFeeTx: destinationFeeTxId
    }),
    headers: {
      'Content-Type': 'application/json',
      'X-API-KEY': 'MY_API_KEY'
    }
});

  if (!response.ok) {
    throw new Error(response);
  }

  const result = await response.json();
  const swapId = result.id;
```


# Wait/Poll for the Swap

Wait for SafeSwap to set up the destination chain Swap

After you have successfully set up a Swap, you need to wait for SafeSwap to complete its portion of the process. This portion involves setting up a smart contract Swap on the destination chain just like you did on the original chain. It is using the Atomic Swap techniques to set up a Swap that the user can claim using their original secret.

In order to find the status of the Swap, you can poll the SafeSwap API at a regular interval.

### Example

```javascript
let swapInfo = null;
const intervalId = setInterval(() => {
      const apiResponse = await fetch(`${SWAP_API_URL}/swaps?swapId=${swapId}`, {  
          headers: {
            'Content-Type': 'application/json',
            'X-API-KEY': 'MY_API_KEY'
          }
      });
      
      const result = await apiResponse.json();
      swapInfo = result[0];
      if (swapInfo.targetContractId) {
          console.log("the swap is ready");
          clearInterval(intervalId);
      } else {
          console.log("Still waiting for the swap to be set up");
      }
}, 3000);

```

### Errors

If there is an error during this process, `swapInfo.erroredAt` will be populated with a timestamp indicating that there is an error and this swap cannot be completed. The user has the option to wait for the timelock to expire (4 hours) and reclaim their original funds. The user can try again.


# Complete the Swap

When the Swap is ready, it is time to claim the funds

The final step is to have the user claim the funds on the destination chain. After the user calls withdraw with the secret, the secret is exposed to the public and now our team can use that secret to withdraw the original funds and complete the atomic swap.

### Example

```javascript

const SWAP_CONTRACT_ADDRESS_ON_DESTINATION = "0x..."; // get this from the docs for your network
const ABI = '{
    "constant": false,
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "_contractId",
        "type": "bytes32"
      },
      {
        "internalType": "bytes32",
        "name": "_preimage",
        "type": "bytes32"
      }
    ],
    "name": "withdraw",
    "outputs": [
      {
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }
    ],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
  }';

const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

const safeSwap = new ethers.Contract(SWAP_CONTRACT_ADDRESS, ABI, signer);

const response = await safeSwap.withdraw(swapInfo.targetContractId, secret, { gasLimit: 200000 });
return response.hash;
```


# Cancel/Refund

If the Swap can't be completed, you can always refund.

The original funds can be reclaimed by the user if they no longer want to complete the swap (took too long, lost the secret, swap failed, etc.)

### Example

```javascript

const SWAP_CONTRACT_ADDRESS_ON_SOURCE_CHAIN = "0x..."; // get this from the docs for your network
const ABI = '{
    "constant": false,
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "_contractId",
        "type": "bytes32"
      }
    ],
    "name": "refund",
    "outputs": [
      {
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }
    ],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
  }';

const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();

const safeSwap = new ethers.Contract(SWAP_CONTRACT_ADDRESS_ON_SOURCE_CHAIN, ABI, signer);

const response = await safeSwap.refund(swapInfo.sourceContractId, { gasLimit: 200000 });
return response.hash;
```


# Smart Contract Details

### Contract Addresses

**Mainnet**

* Ethereum: 0xc3df7f84448086c253bffb0cd30fa543ed074203
* VeChain: 0x17A88f8a34b6e1d6CA9275f5481B99F9E8f2dccC&#x20;
* BNB Smart Chain: 0xc3df7f84448086c253bffb0cd30fa543ed074203
* Polygon: 0xc3df7f84448086c253bffb0cd30fa543ed074203
* Base: 0x534F39c5f4DF9cB13E16B24cA07c7C8C0E2eadB7
* Optimism: 0xc3df7f84448086c253bffb0cd30fa543ed074203

**Testnet**

* Ethereum (Sepolia): 0x88378451e9e5123c95526e2A20E82eb9A0af3ecA
* VeChain: 0xdd4d043b2a0310b09389b120415e32028bf19592
* BNB Smart Chain: 0xd565C6Bcd05DDBd628d837841d69BAAC63aD5473
* Polygon (Mumbai): 0xf76f6c8613874E56F71E1551Be009A9840C5a87c
* Base (Sepolia): 0xd565C6Bcd05DDBd628d837841d69BAAC63aD5473
* Optimism (Sepolia): 0x0705B560Ad8CbBa54c34cD6f26485D7F22d8F271

## ABI

```json
[
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "bytes32",
        "name": "contractId",
        "type": "bytes32"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "sender",
        "type": "address"
      },
      {
        "indexed": true,
        "internalType": "address",
        "name": "receiver",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "address",
        "name": "tokenContract",
        "type": "address"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "bytes32",
        "name": "hashlock",
        "type": "bytes32"
      },
      {
        "indexed": false,
        "internalType": "uint256",
        "name": "timelock",
        "type": "uint256"
      },
      {
        "indexed": false,
        "internalType": "bool",
        "name": "allowLateWithdrawal",
        "type": "bool"
      }
    ],
    "name": "HTLCERC20New",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "bytes32",
        "name": "contractId",
        "type": "bytes32"
      }
    ],
    "name": "HTLCERC20Refund",
    "type": "event"
  },
  {
    "anonymous": false,
    "inputs": [
      {
        "indexed": true,
        "internalType": "bytes32",
        "name": "contractId",
        "type": "bytes32"
      }
    ],
    "name": "HTLCERC20Withdraw",
    "type": "event"
  },
  {
    "constant": false,
    "inputs": [
      {
        "internalType": "address",
        "name": "_receiver",
        "type": "address"
      },
      {
        "internalType": "bytes32",
        "name": "_hashlock",
        "type": "bytes32"
      },
      {
        "internalType": "uint256",
        "name": "_timelock",
        "type": "uint256"
      },
      {
        "internalType": "bool",
        "name": "_allowLateWithdrawal",
        "type": "bool"
      },
      {
        "internalType": "address",
        "name": "_tokenContract",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "_amount",
        "type": "uint256"
      }
    ],
    "name": "newContract",
    "outputs": [
      {
        "internalType": "bytes32",
        "name": "contractId",
        "type": "bytes32"
      }
    ],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "constant": false,
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "_contractId",
        "type": "bytes32"
      },
      {
        "internalType": "bytes32",
        "name": "_preimage",
        "type": "bytes32"
      }
    ],
    "name": "withdraw",
    "outputs": [
      {
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }
    ],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "constant": false,
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "_contractId",
        "type": "bytes32"
      }
    ],
    "name": "refund",
    "outputs": [
      {
        "internalType": "bool",
        "name": "",
        "type": "bool"
      }
    ],
    "payable": false,
    "stateMutability": "nonpayable",
    "type": "function"
  },
  {
    "constant": true,
    "inputs": [
      {
        "internalType": "bytes32",
        "name": "_contractId",
        "type": "bytes32"
      }
    ],
    "name": "getContract",
    "outputs": [
      {
        "internalType": "address",
        "name": "sender",
        "type": "address"
      },
      {
        "internalType": "address",
        "name": "receiver",
        "type": "address"
      },
      {
        "internalType": "address",
        "name": "tokenContract",
        "type": "address"
      },
      {
        "internalType": "uint256",
        "name": "amount",
        "type": "uint256"
      },
      {
        "internalType": "bytes32",
        "name": "hashlock",
        "type": "bytes32"
      },
      {
        "internalType": "uint256",
        "name": "timelock",
        "type": "uint256"
      },
      {
        "internalType": "bool",
        "name": "allowLateWithdrawal",
        "type": "bool"
      },
      {
        "internalType": "bool",
        "name": "withdrawn",
        "type": "bool"
      },
      {
        "internalType": "bool",
        "name": "refunded",
        "type": "bool"
      },
      {
        "internalType": "bytes32",
        "name": "preimage",
        "type": "bytes32"
      }
    ],
    "payable": false,
    "stateMutability": "view",
    "type": "function"
  }
]
```


# Our Swap Addresses

These addresses are the accounts that will be the counterparty to the user's Swaps

When creating a swap on a specific chain, you need to specify a receiver. This receiver MUST be one of our Swap Addresses below.&#x20;

For example, if the user wants to make a Swap from Vechain to Ethereum on testnet, during the smart contract call to create the swap on Vechain, set the receiver as the Vechain Testnet Swap Address.&#x20;

**IMPORTANT:** This is not the same as the `targetReceiver` in the API call to our server. The `targetReceiver` should always be the **user's** account on the destination chain.

### Our Swap Addresses

**Mainnet**

* Ethereum: 0x1bde1Bae878131B919ce8316619C8409f2624E5f
* VeChain: 0x1bde1Bae878131B919ce8316619C8409f2624E5f&#x20;
* BNB Smart Chain: 0x1bde1Bae878131B919ce8316619C8409f2624E5f
* Polygon: 0x1bde1Bae878131B919ce8316619C8409f2624E5f
* Base: 0x1bde1Bae878131B919ce8316619C8409f2624E5f
* Polygon: 0x1bde1Bae878131B919ce8316619C8409f2624E5f

**Testnet**

* Ethereum (Sepolia): 0xB25928E30F0751Ff7cCfd8592D75C734FDeC3B38
* VeChain: 0x4917A44C40C2b59c4DD96ffa422C438dAF27Da09
* BNB Smart Chain: 0xB25928E30F0751Ff7cCfd8592D75C734FDeC3B38
* Polygon (Mumbai): 0xB25928E30F0751Ff7cCfd8592D75C734FDeC3B38
* Base (Sepolia): 0xB25928E30F0751Ff7cCfd8592D75C734FDeC3B38
* Optimism (Sepolia): 0xB25928E30F0751Ff7cCfd8592D75C734FDeC3B38


# API Details

## API Keys

All calls require an API Key. Contact us to get one. Include this API Key in the `X-API-KEY` header of all requests to our service.

## Chain Options

For API calls that require a chain name, the available chain names are: `ETHEREUM`, `VECHAIN`, `BSC`, `MATIC`, `BASE`, `OPTIMISM`.

### API Endpoints

* GET /swaps: Returns swap details. Must contain a query string of `?swapId=345...` or `?firstAddress=0x123...&firstChain=VECHAIN&secondAddress=0x234...&secondChain=ETHEREUM`
* **POST /swaps:** Create a Swap. Payload is&#x20;

  ```
  SwapDetails {
    sourceChain: ChainName;
    sourceContractId: string; // prefixed with 0x
    sourceSender: string; // prefixed with 0x
    targetChain: ChainName;
    targetTokenAddress: string; // prefixed with 0x
    targetReceiver: string; // prefixed with 0x
    sourceFeeTx: string; // prefixed with 0x
    targetFeeTx: string; // prefixed with 0x
  }
  ```
* **GET /gas-estimates:** Shows the required fees for a Swap. Requires query string of `?sourceChain=VECHAIN&targetChain=ETHEREUM`
* **GET /tokens:** Shows the available tokens for swapping.


# Safe Haven

Visit: <https://safehaven.io/>


# SafeTech

Visit: <https://safetech.io/>


# Support


