### Run Signer Example
Source: https://docs.synapseprotocol.com/docs/Services/Signer
Commands to install dependencies and execute the signer example locally.
```bash
brew install go # if on mac
git clone https://github.com/synapsecns/sanguine --recurse-submodules
cd sanguine/ethergo/examples/signer
go run main.go --config=/path/to/signer.yml
```
--------------------------------
### Example Applications
Source: https://docs.synapseprotocol.com/docs/Bridge/Widget
Explore example applications in the repository's `/examples` folder for reference.
```APIDOC
## Example Apps
For reference, you can find three example apps in the repository’s `/examples` folder.
`examples/`| Description
---|---
`landing-page`| Functional demo with basic customization
`with-react`| Simple React implementation
`with-next`| Simple Next.js implementation
```
--------------------------------
### Bridge Widget Quick Start
Source: https://docs.synapseprotocol.com/docs/Bridge/Widget
A quick start guide to integrating the Bridge component into your React application.
```APIDOC
## Quick Start
Import the `Bridge` component from `@synapsecns/widget` and initialize it with your `web3Provider`.
### Request Example
```javascript
import { Bridge } from '@synapsecns/widget'
const MyApp = () => {
const web3Provider = new ethers.BrowserProvider(window.ethereum)
return
}
```
This will result in a fully operational Bridge integrating the routes and tokens supported by the Synapse protocol.
```
--------------------------------
### Install Synapse Widget
Source: https://docs.synapseprotocol.com/docs/Bridge/Widget
Install the Synapse Widget package using either npm or yarn.
```bash
npm install @synapsecns/widget
```
```bash
yarn add @synapsecns/widget
```
--------------------------------
### Initialize MySQL Database Connection
Source: https://docs.synapseprotocol.com/docs/Services/Submitter
Example of opening a GORM connection for a MySQL database.
```go
gdb, err := gorm.Open(mysql.Open(dbURL), &gorm.Config{
Logger: common_base.GetGormLogger(logger),
FullSaveAssociations: true,
NamingStrategy: NamingStrategy,
NowFunc: time.Now,
})
```
--------------------------------
### Example Synapse Protocol Configuration
Source: https://docs.synapseprotocol.com/docs/RFQ/CanonicalRelayer
This is an example YAML configuration file for the Synapse Protocol RFQ Relayer. It demonstrates how to set up database connections, API endpoints, and base chain configurations.
```yaml
submitter_config: # please see the more detailed submitter documentation
chains:
1:
supports_eip_1559: true
gas_estimate: 1000000
database:
type: sqlite # can be other mysql or sqlite
ds n: /tmp/db # should be the dsn of your database. If using sqlite, this can be a path
signer: # please see more detailed signer config #can be text, gcp, or aws
type: GCP
file: /config/signer.txt
screener_api_url: 'http://screener-url' # can be left blank
rfq_url: 'http://rfq-api' # url of the rfq api backend.
omnirpc_url: 'http://omnirpc' # url of the omnirpc instance, please reference the Omnirpc section under Services for proper configuration
rebalance_interval: 2m # how often to rebalance
relayer_api_port: '8081' # api port for the relayer api
volume_limit: 10000 # USD price cap for a bridge under block confirmation minimum (configurable under `chains`)
base_chain_config: # this is hte base chain config, other chains override it
confirmations: 0
# Claim (72.5k) + Prove (57.5k) gas limits, rounded up
origin_gas_estimate: 130_000
```
--------------------------------
### web3Provider Configuration
Source: https://docs.synapseprotocol.com/docs/Bridge/Widget
Examples of how to configure the `web3Provider` using Ethers v5 and v6.
```APIDOC
## web3Provider
While the demo landing page uses the `ethers` library, any similar provider can be used.
### Request Example
```javascript
// Ethers v5
const web3Provider = new ethers.providers.Web3Provider(window.ethereum, 'any')
// Ethers v6
const web3Provider = new ethers.BrowserProvider(window.ethereum)
```
```
--------------------------------
### Start Scribe Components
Source: https://docs.synapseprotocol.com/docs/Services/Scribe
Commands to initialize the indexer and server components with database configuration.
```bash
./scribe --config --db --path
```
```bash
./server --port --db --path
```
--------------------------------
### Install Synapse SDK Router with Yarn
Source: https://docs.synapseprotocol.com/docs/Bridge/SDK
Install the Synapse SDK Router package using the yarn package manager.
```bash
yarn add @synapsecns/sdk-router
```
--------------------------------
### Bridge Widget Installation
Source: https://docs.synapseprotocol.com/docs/Bridge/Widget
Instructions for installing the Synapse Bridge Widget using npm or yarn.
```APIDOC
## Installation
Requires `React`, and the `npm` or `yarn` package manager.
`@synapsecns` packages are published to GitHub Packages. Add the following to your project's `.npmrc`:
```
@synapsecns:registry=https://npm.pkg.github.com
```
### Options
`npm install @synapsecns/widget`
`yarn add @synapsecns/widget`
```
--------------------------------
### Install Synapse SDK Router with NPM
Source: https://docs.synapseprotocol.com/docs/Bridge/SDK
Install the Synapse SDK Router package using the npm package manager.
```bash
npm install @synapsecns/sdk-router
```
--------------------------------
### Initiate Active RFQ Response Example
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/initiate-an-active-rfq
This is an example of a successful response when initiating an active RFQ. It includes details about the quote and its success status.
```json
{
"dest_amount": "string",
"quote_id": "string",
"quote_type": "string",
"reason": "string",
"relayer_address": "string",
"success": true
}
```
--------------------------------
### Sign Message for Authentication (TypeScript)
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API
Example implementation in TypeScript for signing a message using a private key, adhering to EIP-191 for API authentication. Ensure you have the 'ethereumjs-util' library installed.
```typescript
import { ecsign, toBuffer, bufferToHex, hashPersonalMessage } from 'ethereumjs-util';
async function signMessage(privateKey: string) {
const message = Math.floor(Date.now() / 1000).toString();
const messageHash = hashPersonalMessage(Buffer.from(message));
var { v, r, s } = ecsign(messageHash, toBuffer(privateKey));
v -= 27
const signature = Buffer.concat([r, s, Buffer.from([v])]);
return `${message}:${bufferToHex(signature)}`;
}
```
--------------------------------
### Fetch Quotes with HttpClient
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/get-quotes
Example implementation using C# HttpClient to perform a GET request to the quotes endpoint.
```csharp
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://docs.synapseprotocol.com/quotes");
request.Headers.Add("Accept", "application/json");
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
```
--------------------------------
### Quote Response Schema Example
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/get-quotes
Example JSON structure returned by the /quotes endpoint.
```json
[
{
"dest_amount": "string",
"dest_chain_id": 0,
"dest_fast_bridge_address": "string",
"dest_token_addr": "string",
"fixed_fee": "string",
"max_origin_amount": "string",
"origin_chain_id": 0,
"origin_fast_bridge_address": "string",
"origin_token_addr": "string",
"relayer_addr": "string",
"updated_at": "string"
}
]
```
--------------------------------
### Custom Theme Configuration
Source: https://docs.synapseprotocol.com/docs/Bridge/Widget
Example of how to customize the widget's appearance using the `customTheme` property.
```APIDOC
## Theme
The widget will automatically generate a color palette from `bgColor` in the `customTheme` object, which you can also use to override individual color variables.
### Color modes
If your application has multiple color modes, such as light and dark, reload the widget with the appropriate theme colors when your application’s theme changes.
### Request Example
```javascript
const customTheme = {
// Generate from base color, 'dark', or 'light'
bgColor: '#08153a',
// Basic customization
'--synapse-text': 'white',
'--synapse-secondary': '#ffffffb3',
'--synapse-root': '#16182e',
'--synapse-surface': 'linear-gradient(90deg, #1e223de6, #262b47e6)',
'--synapse-border': 'transparent',
// Full customization (Uses 'basic' colors by default)
'--synapse-focus': 'var(--synapse-secondary)',
'--synapse-select-bg': 'var(--synapse-root)',
'--synapse-select-text': 'var(--synapse-text)',
'--synapse-select-border': 'var(--synapse-border)',
'--synapse-button-bg': 'var(--synapse-surface)',
'--synapse-button-text': 'var(--synapse-text)',
'--synapse-button-border': 'var(--synapse-border)',
// Transaction progress colors (set bgColor to auto-generate)
'--synapse-progress': 'hsl(265deg 100% 65%)',
'--synapse-progress-flash': 'hsl(215deg 100% 65%)',
'--synapse-progress-success': 'hsl(120deg 100% 30%)',
'--synapse-progress-error': 'hsl(15deg 100% 65%)',
}
```
```
--------------------------------
### Install Ethers v6 Providers Dependency
Source: https://docs.synapseprotocol.com/docs/Bridge/SDK
Install the necessary @ethersproject/providers dependency for Ethers v6.
```bash
npm install @ethersproject/providers@^5.7.2
```
```bash
yarn add @ethersproject/providers@^5.7.2
```
--------------------------------
### targetChainIds & targetTokens Configuration
Source: https://docs.synapseprotocol.com/docs/Bridge/Widget
Example of how to filter chains and tokens displayed in the widget.
```APIDOC
## targetChainIds & targetTokens
Shows only the chains and tokens your project supports for onboarding, while still allowing users to onboard from, or bridge back to, any preferred chain or token.
### Request Example
```javascript
import { Bridge, CustomRpcs, ETH, USDC, USDT } from '@synapsecns/widget'
const MyApp = () => {
const web3Provider = new ethers.BrowserProvider(window.ethereum)
return (
)
}
```
Token names must match the definitions in `src/constants/bridgeable.ts`. Metis USDC, for example, is `"METISUSDC"`.
For chains, see `src/constants/chains.ts` as well.
```
--------------------------------
### Initiate Active RFQ with HttpClient in C#
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/initiate-an-active-rfq
Example of initiating an active RFQ using HttpClient in C#. This snippet demonstrates how to construct the HTTP request and handle the response.
```csharp
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Put, "https://docs.synapseprotocol.com/rfq");
request.Headers.Add("Accept", "application/json");
var content = new StringContent("{\n \"data\": {\n \"dest_amount\": \"string\",\n \"dest_chain_id\": 0,\n \"dest_token_addr\": \"string\",\n \"expiration_window\": 0,\n \"origin_amount\": \"string\",\n \"origin_chain_id\": 0,\n \"origin_token_addr\": \"string\",\n \"quote_id\": \"string\",\n \"relayer_address\": \"string\"\n },\n \"integrator_id\": \"string\",\n \"quote_types\": [\n \"string\"\n ],\n \"user_address\": \"string\"\n}", null, "application/json");
request.Content = content;
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
```
--------------------------------
### Scribe Configuration YAML
Source: https://docs.synapseprotocol.com/docs/Services/Scribe
Example structure for the Scribe indexer configuration file.
```yaml
chains:
- chain_id: 1
get_logs_range: 500
get_block_batch_amount: 1
store_concurrency: 100
concurrency_threshold: 50000
livefill_threshold: 300
livefill_range: 200
livefill_flush_interval: 10000
confirmations: 200
contracts:
- address: 0xAf41a65F786339e7911F4acDAD6BD49426F2Dc6b
start_block: 18646320
```
--------------------------------
### OmniRPC Configuration File
Source: https://docs.synapseprotocol.com/docs/Services/Omnirpc
Example YAML configuration defining chain-specific RPC endpoints, confirmation requirements, and service settings.
```yaml
chains:
1:
rpcs:
- https://api.mycryptoapi.com/eth
- https://rpc.flashbots.net/
- https://eth-mainnet.gateway.pokt.network/v1/5f3453978e354ab992c4da79
- https://cloudflare-eth.com/
- https://mainnet-nethermind.blockscout.com/
- https://nodes.mewapi.io/rpc/eth
- https://main-rpc.linkpool.io/
- https://mainnet.eth.cloud.ava.do/
- https://ethereumnodelight.app.runonflux.io
- https://rpc.ankr.com/eth
- https://eth-rpc.gateway.pokt.network
- https://main-light.eth.linkpool.io
- https://ethereum-mainnet.core.chainstack.com
- http://18.211.207.34:8545
- https://eth-mainnet.nodereal.io/v1/1659dfb40aa24bbb8153a677b98064d7
- wss://eth-mainnet.nodereal.io/ws/v1/1659dfb40aa24bbb8153a677b98064d7
- https://api.bitstack.com/v1/wNFxbiJyQsSeLrX8RRCHi7NpRxrlErZk/DjShIqLishPCTB9HiMkPHXjUM9CNM9Na/ETH/mainnet
confirmations: 5
10:
rpcs:
- https://mainnet.optimism.io
confirmations: 1
# port to run on
port: 5000
# expressed in seconds
refreshInterval: 60
```
--------------------------------
### Configure Submitter Service
Source: https://docs.synapseprotocol.com/docs/Services/Submitter
Example configuration for the Submitter service, defining chain-specific gas settings and EIP-1559 support.
```yaml
submitter_config:
chains:
1:
supports_eip_1559: true
gas_estimate: 1000000
10:
gas_estimate: 5000000
max_gas_price: 200000000000
supports_eip_1559: true
```
--------------------------------
### Configure NPM for GitHub Packages
Source: https://docs.synapseprotocol.com/docs/Bridge/SDK
Add this to your project's .npmrc file to enable installation of @synapsecns packages from GitHub Packages.
```bash
@synapsecns:registry=https://npm.pkg.github.com
```
--------------------------------
### customRpcs Configuration
Source: https://docs.synapseprotocol.com/docs/Bridge/Widget
Example of how to configure custom RPC endpoints for specific chain IDs.
```APIDOC
## customRpcs
Set preferred RPC endpoints for each `chainId`. Defaults to Synapse fallback values for undefined chains.
### Request Example
```javascript
import { Bridge, CustomRpcs } from '@synapsecns/widget'
const customRpcs: CustomRpcs = {
1: 'https://ethereum.my-custom-rpc.com',
10: 'https://optimism.my-custom-rpc.com',
42161: 'https://arbitrum.my-custom-rpc.com',
}
const MyApp = () => {
const web3Provider = new ethers.BrowserProvider(window.ethereum)
return
}
```
```
--------------------------------
### Fetch contracts using C# HttpClient
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/get-contract-addresses
Uses HttpClient to perform a GET request and output the response content.
```csharp
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://docs.synapseprotocol.com/contracts");
request.Headers.Add("Accept", "application/json");
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
```
--------------------------------
### Establish WebSocket connection for RFQs using HttpClient
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/listen-for-active-rf-qs
Uses the HttpClient library to initiate a GET request to the /rfq_stream endpoint.
```csharp
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://docs.synapseprotocol.com/rfq_stream");
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
```
--------------------------------
### Example JSON response for contracts
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/get-contract-addresses
The expected structure of the response body containing the contracts map.
```json
[
{
"contracts": {}
}
]
```
--------------------------------
### Implement Bridge Logic in React
Source: https://docs.synapseprotocol.com/docs/Bridge/Code-Examples
A React component example demonstrating how to use the Synapse SDK to fetch bridge quotes and execute cross-chain transfers.
```typescript
// `/homepage/index.tsx`
import { useSynapseContext } from '@/utils/SynapseProvider'
import { Zero } from '@ethersproject/constants'
import { useState, useEffect } from 'react'
import { getNetwork } from '@wagmi/core'
import {
DEFAULT_FROM_CHAIN,
DEFAULT_TO_CHAIN,
DEFAULT_FROM_TOKEN,
DEFAULT_TO_TOKEN,
} from '@/constants/bridge'
export default function HomePage({ address }: { address: `0x${string}` }) {
// Get the synapse sdk
const SynapseSDK = useSynapseContext()
// Get the current time
const time = // add logic to get the current unix timestamp
// Example state hooks
const [fromToken, setFromToken] = useState(DEFAULT_FROM_TOKEN)
const [toToken, setToToken] = useState(DEFAULT_TO_TOKEN)
const [fromChainId, setFromChainId] = useState(DEFAULT_FROM_CHAIN)
const [toChainId, setToChainId] = useState(DEFAULT_TO_CHAIN)
const [amount, setAmount] = useState(Zero)
const [bridgeQuote, setBridgeQuote] = useState({
outputAmountString: '',
quotes: { originQuery: null, destQuery: null },
})
// Set connected network when component is mounted
useEffect(() => {
const { chain: fromChainIdRaw } = getNetwork()
setFromChainId(fromChainIdRaw ? fromChainIdRaw?.id : DEFAULT_FROM_CHAIN)
}, [])
// Get Quote function
// Suggestion: this function should be triggered from an useEffect when amount or to/from token/chain is altered
const getQuote = async () = {
SynapseSDK.bridgeQuote(
fromChainId,
toChainId,
fromToken,
toToken,
amount,
{
deadline: time + 10000,
excludedModules: [],
originUserAddress: address,
}
)
.then(
({ feeAmount, bridgeFee, maxAmountOut, originQuery, destQuery }) => {
let toValueBigNum = maxAmountOut ?? Zero
let toValueBase = toValueBigNum.div(toDecimals).toString()
let toValueMantissa = toValueBigNum.mod(toDecimals).toString()
setBridgeQuote({
outputAmountString: toValueBase + '.' + toValueMantissa,
quotes: {
originQuery,
destQuery,
},
})
// do something
}
)
.catch((err) => {
alert('error getting quote', err)
// do something
})
}
// Execute bridge function
const executeBridge = async () = {
await Synapse.bridge(
toAddress, // To Address
bridgeQuote.routerAddress, // bridge router contract address
fromChainId, // Origin Chain
toChainId, // Destination Chain
fromToken, // Origin Token Address
amount, // Amount
bridgeQuote.quotes.originQuery, // Origin query from bridgeQuote()
bridgeQuote.quotes.destQuery // Destination query from bridgeQuote()
).then(({to, data}) => {
// do something
}
)
.catch((err) => {
alert('error bridging', err)
// do something
})
}
// ...
}
```
--------------------------------
### Query Data via cURL
Source: https://docs.synapseprotocol.com/docs/Services/Omnirpc
Example request to fetch data from a specific chain ID using the OmniRPC API.
```bash
curl --location --request POST 'http://localhost:5000/rpc/1' \
--header 'Content-Type: application/json' \
--data-raw '{
"jsonrpc":"2.0",
"method":"eth_getTransactionCount",
"params":[
"0x230a1ac45690b9ae1176389434610b9526d2f21b",
"0xec1d40"
],
"id":1
}'
```
--------------------------------
### Configure CCTP Relayer YAML
Source: https://docs.synapseprotocol.com/docs/Routers/CCTP
Example configuration file for the CCTP relayer, specifying chain addresses, signer details, and submitter gas settings.
```yaml
cctp_type: "synapse"
# prod contract addresses
chains:
- chain_id: 1
synapse_cctp_address: "0x12715a66773BD9C54534a01aBF01d05F6B4Bd35E"
- chain_id: 42161
synapse_cctp_address: "0x12715a66773BD9C54534a01aBF01d05F6B4Bd35E"
base_omnirpc_url: "http://omnrpc-url/"
unbonded_signer:
type: "AWS"
# should be a mounted secret
file: "/config/aws.txt"
http_backoff_initial_interval_ms: 1000
http_backoff_max_elapsed_time_ms: 300000
# submitter config for cctp
submitter_config:
chains:
1:
supports_eip_1559: true
gas_estimate: 1000000
42161:
gas_estimate: 30000000
max_gas_price: 10000000000
supports_eip_1559: true
```
--------------------------------
### Retrieve Open Quote Requests with HttpClient
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/get-open-quote-requests
Example usage of C# HttpClient to fetch open quote requests from the Synapse Protocol API.
```csharp
var client = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://docs.synapseprotocol.com/open_quote_requests");
request.Headers.Add("Accept", "application/json");
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
Console.WriteLine(await response.Content.ReadAsStringAsync());
```
--------------------------------
### Quotable Tokens Configuration Example
Source: https://docs.synapseprotocol.com/docs/RFQ/CanonicalRelayer
This snippet shows how to define quotable token pairs between different chains using their chain IDs and token addresses. It's used to specify which cross-chain token routes are available for quoting.
```yaml
"1-0x00":
- "1-0x01"
```
--------------------------------
### Build and Run OmniRPC from Source
Source: https://docs.synapseprotocol.com/docs/Services/Omnirpc
Commands to clone the repository and execute the service using Go.
```bash
git clone https://github.com/synapsecns/sanguine --recursive
cd sanguine/services/omnirpc
go run main.go --config /path/to/config.yaml
```
--------------------------------
### Deployment Options
Source: https://docs.synapseprotocol.com/docs/RFQ/CanonicalRelayer
Instructions for deploying the Sanguine RFQ Relayer either from a Docker image or from source.
```APIDOC
## Run
### From Docker
Run the Docker image along with the path to your YAML configuration file.
1. `docker run ghcr.io/synapsecns/sanguine/rfq-relayer:latest --config /path/to/config`
### From Source
Requires Go 1.21 or higher
Not generally recommended for end-users.
Clone the Sanguine repository, then run the main.go file along with the path to your YAML configuration file.
1. `git clone https://github.com/synapsecns/sanguine --recursive`
2. `cd sanguine/services/rfq/relayer`
3. `go run main.go --config /path/to/config.yaml`
```
--------------------------------
### Build Quoter API from Source
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API
Instructions for building the Quoter API from source using Go. Requires Go 1.21 or higher. Clone the repository, navigate to the service directory, and run the main Go file with the configuration path.
```bash
git clone https://github.com/synapsecns/sanguine --recursive
cd sanguine/services/rfq
go run main.go --config /path/to/config.yaml
```
--------------------------------
### Basic Synapse SDK Implementation
Source: https://docs.synapseprotocol.com/docs/Bridge/Code-Examples
Initializes the SynapseSDK with RPC providers and demonstrates the bridge quote and execution flow.
```typescript
// app.js
import { JsonRpcProvider } from '@ethersproject/providers'
import { Provider } from '@ethersproject/abstract-provider'
import { SynapseSDK } from '@synapsecns/sdk-router'
import { BigNumber } from '@ethersproject/bignumber'
//Set up providers (RPCs) for each chain desired**
const arbitrumProvider: Provider = new JsonRpcProvider('https://arb1.arbitrum.io/rpc')
const avalancheProvider: Provider = new JsonRpcProvider('https://api.avax.network/ext/bc/C/rpc')
//Structure arguments properly
const chainIds = [42161, 43114]
const providers = [arbitrumProvider, avalancheProvider]
//Set up a SynapseSDK instance
const Synapse = new SynapseSDK(chainIds, providers)
// quote
const quote = await Synapse.bridgeQuote(
42161, // From Chain
43114, // To Chain
'0xff970a61a04b1ca14834a43f5de4533ebddb5cc8', // From Token
'0xa7d7079b0fead91f3e65f86e8915cb59c1a4c664', // To Token
BigNumber.from('20000000'), // Amount
{
deadline: 1234567890,
excludedModules: ['SynapseRFQ'],
originUserAddress: '0x1234567890abcdef1234567890abcdef12345678',
}
)
// bridge
await Synapse.bridge(
'0x0AF91FA049A7e1894F480bFE5bBa20142C6c29a9', // To Address
quote.routerAddress, // bridge router contract address
42161, // Origin Chain
43114, // Destination Chain
'0xff970a61a04b1ca14834a43f5de4533ebddb5cc8', // Origin Token Address
BigNumber.from('20000000'), // Amount
quote.originQuery, // Origin query from bridgeQuote()
quote.destQuery // Destination query from bridgeQuote()
)
```
--------------------------------
### Run CCTP Relayer from Source
Source: https://docs.synapseprotocol.com/docs/Routers/CCTP
Commands to clone the repository and execute the relayer service using Go.
```bash
git clone https://github.com/synapsecns/sanguine --recursive
cd sanguine/services/cctp-relayer
go run main.go --config /path/to/config.yaml
```
--------------------------------
### GET /rfq
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API
Retrieve currently open RFQs.
```APIDOC
## GET /rfq
### Description
Retrieve currently open RFQs.
### Method
GET
### Endpoint
/rfq
```
--------------------------------
### GET /quotes
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API
Retrieve all current passive quotes, with optional filtering.
```APIDOC
## GET /quotes
### Description
Get all quotes, can be filtered by different parameters.
### Method
GET
### Endpoint
/quotes
```
--------------------------------
### Run RFQ Relayer from Source
Source: https://docs.synapseprotocol.com/docs/RFQ/CanonicalRelayer
Commands to clone and execute the relayer service from the source repository.
```bash
git clone https://github.com/synapsecns/sanguine --recursive
cd sanguine/services/rfq/relayer
go run main.go --config /path/to/config.yaml
```
--------------------------------
### GET /rfq_stream
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/listen-for-active-rf-qs
Establish a WebSocket connection to listen for Active Requests-For-Quote.
```APIDOC
## GET /rfq_stream
### Description
Establish a WebSocket connection to listen for Active Requests-For-Quote.
### Method
GET
### Endpoint
/rfq_stream
### Responses
#### Success Response (101)
- **X-Api-Version** (string) - API Version Number - See docs for more info
#### Response Example
```json
{
"example": "response body"
}
```
```
--------------------------------
### Run Quoter API with Docker
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API
Instructions for running the Quoter API using Docker. Build the Docker image and execute it, providing the path to the configuration file. Pin Docker versions in production for stability.
```bash
docker run ghcr.io/synapsecns/sanguine/rfq-api:latest --config /path/to/config
```
--------------------------------
### Build Scribe from Source
Source: https://docs.synapseprotocol.com/docs/Services/Scribe
Commands to clone the repository and compile the Scribe service.
```bash
git clone https://github.com/synapsecns/sanguine --recursive
cd sanguine/services/scribe
go build
```
--------------------------------
### GET /quotes Endpoint Definition
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/get-quotes
The base path for retrieving quotes from all relayers.
```http
GET
## /quotes
```
--------------------------------
### GET /contracts
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/get-contract-addresses
Retrieves a map of chain IDs to their respective contract addresses.
```APIDOC
## GET /contracts
### Description
Retrieves a map of chain IDs to their respective contract addresses.
### Method
GET
### Endpoint
/contracts
### Response
#### Success Response (200)
- **contracts** (object) - A map of chain ID to contract address.
#### Response Example
[
{
"contracts": {}
}
]
```
--------------------------------
### Configure Ethers v6 Providers and SDK Instance
Source: https://docs.synapseprotocol.com/docs/Bridge/SDK
Set up Ethers v6 providers using JsonRpcProvider and instantiate the SynapseSDK with chain IDs and providers.
```typescript
import { JsonRpcProvider } from '@ethersproject/providers'
//Set up providers (RPCs) for each chain desired
const arbitrumProvider: Provider = new JsonRpcProvider(
'https://arb1.arbitrum.io/rpc'
)
const avalancheProvider: Provider = new JsonRpcProvider(
'https://api.avax.network/ext/bc/C/rpc'
)
//Structure arguments properly
const chainIds = [42161, 43114]
const providers = [arbitrumProvider, avalancheProvider]
//Set up a SynapseSDK instance
const Synapse = new SynapseSDK(chainIds, providers)
```
--------------------------------
### Configure Ethers v5 Providers and SDK Instance
Source: https://docs.synapseprotocol.com/docs/Bridge/SDK
Set up Ethers v5 providers for desired chains and instantiate the SynapseSDK with chain IDs and providers.
```typescript
//Set up providers (RPCs) for each chain desired
const arbitrumProvider: Provider = new ethers.providers.JsonRpcProvider(
'https://arb1.arbitrum.io/rpc'
)
const avalancheProvider: Provider = new ethers.providers.JsonRpcProvider(
'https://api.avax.network/ext/bc/C/rpc'
)
//Structure arguments properly
const chainIds = [42161, 43114]
const providers = [arbitrumProvider, avalancheProvider]
//Set up a SynapseSDK instance
const Synapse = new SynapseSDK(chainIds, providers)
```
--------------------------------
### GET /bridge
Source: https://docs.synapseprotocol.com/docs/Bridge/Code-Examples
Estimates the bridge output for a given token transfer between two chains.
```APIDOC
## GET /bridge
### Description
Retrieves bridge quotes to estimate the output amount when bridging tokens between chains.
### Method
GET
### Endpoint
https://api.synapseprotocol.com/bridge
### Parameters
#### Query Parameters
- **fromChain** (number) - Required - The ID of the origin chain.
- **toChain** (number) - Required - The ID of the destination chain.
- **fromToken** (string) - Required - The token address or symbol on the origin chain.
- **toToken** (string) - Required - The token address or symbol on the destination chain.
- **amountFrom** (string) - Required - The amount of tokens to bridge.
### Response
#### Success Response (200)
- **quote** (object) - The first available bridge quote object.
```
--------------------------------
### GET /quotes
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/get-quotes
Retrieves quotes from all relayers for a given set of origin and destination parameters.
```APIDOC
## GET /quotes
### Description
Get quotes from all relayers.
### Method
GET
### Endpoint
/quotes
### Parameters
#### Path Parameters
- **originChainID** (integer) - Required - Origin chain id to filter quotes by
- **originTokenAddr** (string) - Required - Origin chain id to filter quotes by
- **destChainID** (integer) - Required - Destination chain id to filter quotes by
- **destTokenAddr** (string) - Required - Destination token address to filter quotes by
- **relayerAddr** (string) - Required - Relayer address to filter quotes by
### Response
#### Success Response (200)
- **dest_amount** (string) - DestAmount is the max amount of liquidity which exists for a given destination token, provided in the destination token decimals
- **dest_chain_id** (integer) - DestChainID is the chain which the relayer is willing to relay to
- **dest_fast_bridge_address** (string) - DestFastBridgeAddress is the address of the fast bridge contract on the destination chain
- **dest_token_addr** (string) - DestToken is the token address for which the relayer willing to relay to
- **fixed_fee** (string) - FixedFee is the fixed fee for the quote, provided in the destination token terms
- **max_origin_amount** (string) - MaxOriginAmount is the maximum amount of origin tokens bridgeable
- **origin_chain_id** (integer) - OriginChainID is the chain which the relayer is willing to relay from
- **origin_fast_bridge_address** (string) - OriginFastBridgeAddress is the address of the fast bridge contract on the origin chain
- **origin_token_addr** (string) - OriginTokenAddr is the token address for which the relayer willing to relay from
- **relayer_addr** (string) - Address of the relayer providing the quote
- **updated_at** (string) - UpdatedAt is the time that the quote was last upserted
### Response Example
```json
[
{
"dest_amount": "string",
"dest_chain_id": 0,
"dest_fast_bridge_address": "string",
"dest_token_addr": "string",
"fixed_fee": "string",
"max_origin_amount": "string",
"origin_chain_id": 0,
"origin_fast_bridge_address": "string",
"origin_token_addr": "string",
"relayer_addr": "string",
"updated_at": "string"
}
]
```
```
--------------------------------
### Container Configuration
Source: https://docs.synapseprotocol.com/docs/Bridge/Widget
Configure the widget's container to be full-width with a transparent background or supply a solid background.
```APIDOC
## Container
The widget is full-width with a transparent background by default, but can supply its own solid background container.
```
```
```
--------------------------------
### GET /bridgeTxInfo
Source: https://docs.synapseprotocol.com/docs/Bridge/Code-Examples
Generates unsigned bridge transaction information required to execute a cross-chain transfer.
```APIDOC
## GET /bridgeTxInfo
### Description
Fetches the necessary transaction data to perform a bridge operation, including the unsigned transaction payload.
### Method
GET
### Endpoint
https://api.synapseprotocol.com/bridgeTxInfo
### Parameters
#### Query Parameters
- **fromChain** (number) - Required - The ID of the origin chain.
- **toChain** (number) - Required - The ID of the destination chain.
- **fromToken** (string) - Required - The token address or symbol on the origin chain.
- **toToken** (string) - Required - The token address or symbol on the destination chain.
- **amount** (string) - Required - The amount of tokens to bridge.
- **destAddress** (string) - Required - The recipient address on the destination chain.
### Response
#### Success Response (200)
- **transactionInfo** (object) - The unsigned transaction data.
```
--------------------------------
### Cross-Chain Swap with Synapse Protocol (TypeScript Pseudocode)
Source: https://docs.synapseprotocol.com/docs/Routers/Synapse-Router
This pseudocode demonstrates the steps involved in a cross-chain swap using Synapse. It covers fetching router instances, identifying bridge tokens, querying optimal swap routes on both origin and destination chains, and finally executing the bridge transaction.
```typescript
// Beware: below is a TypeScript pseudocode.
// 0. Fetch deployments of SynapseRouter on origin and destination chains
let routerOrigin = getSynapseRouter(originChainId);
let routerDest = getSynapseRouter(destChainId);
// 1. Determine the set of bridge tokens that could enable "receive tokenOut on destination chain"
// For that we perform a static call to SynapseRouter on destination chain
let bridgeTokens = routerDest.getConnectedBridgeTokens(tokenOut);
// Then we get the list of bridge token symbols
let symbols = bridgeTokens.map((token) => token.symbol);
// 2. Get the list of Queries with possible swap instructions for origin chain
// For that we perform a static call to SynapseRouter on origin chain
// This gets us the quotes from tokenIn to every bridge token (one quote per bridge token in the list)
let originQueries = routerOrigin.getOriginAmountOut(
tokenIn,
symbols,
amountIn
);
// 3. Get the list of Queries with possible swap instructions for destination chain
// First, we form a list of "destination requests" by merging
// list of token symbols with list of quotes obtained in step 2.
let requests = symbols.map((value, index) => {
let request: DestRequest = {
symbol: value,
amountIn: originQueries[index].minAmountOut,
};
return request;
});
// Then we perform a static call to SynapseRouter on destination chain
// This gets us the quotes from every bridge token to tokenOut (one quote per bridge token in the list)
// These quotes will take into account the fee for bridging the token to destination chain
let destQueries = routerDest.getDestinationAmountOut(requests, tokenOut);
// 4. Pick a pair of originQueries[i], destQueries[i] to perform the cross-chain swap
// In this example we are picking the pair that yields the best overall quote
let destQuery = maxBy(destQueries, (query) => query.minAmountOut);
let selectedIndex = destQueries.indexOf(destQuery)
let originQuery = originQueries[selectedIndex]
// Now we apply user slippage and deadline settings
originQuery = applyUserSettings(originQuery, userSettings)
destQuery = applyUserSettings(destQuery, userSettings)
// 5. Call SynapseRouter on origin chain to perform a swap
let amountETH: BigInt;
// 0xEeee address is used to represent native ETH
if (tokenIn == "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE") {
// If user selected "native ETH" as tokenIn, we would need to modify msg.value for the call
amountETH = amountIn;
} else {
// If user selected an ERC-20 token as tokenIn, we would need to use msg.value=0
amountETH = 0
// We also need to check if user approved routerOrigin to spend `tokenIn`
if (allowance(tokenIn, userOrigin, routerOrigin) < amountIn) {
// Users needs to issue a token approval
// tokenIn.approve(routerOrigin, amountIn)
}
}
// Perform a call to Synapse Router with all the derived parameters
// Use previously determined msg.value for this call
// (WETH wrapping is done by the Synapse Router)
routerOrigin.bridge{value: amountETH}(
userDest,
destChainId,
tokenIn,
amountIn,
originQuery,
destQuery
);
```
--------------------------------
### GET /open_quote_requests
Source: https://docs.synapseprotocol.com/docs/RFQ/Quoting/Quoter%20API/get-open-quote-requests
Retrieves a list of all open quote requests currently in Received or Pending status.
```APIDOC
## GET /open_quote_requests
### Description
Get all open quote requests that are currently in Received or Pending status.
### Method
GET
### Endpoint
/open_quote_requests
### Response
#### Success Response (200)
- **created_at** (string) - Timestamp of creation
- **dest_chain_id** (integer) - Destination chain identifier
- **dest_token** (string) - Destination token address
- **expiration_window** (integer) - Expiration time window
- **origin_amount** (string) - Amount on the origin chain
- **origin_chain_id** (integer) - Origin chain identifier
- **origin_token** (string) - Origin token address
- **user_address** (string) - User wallet address
#### Response Example
[
{
"created_at": "string",
"dest_chain_id": 0,
"dest_token": "string",
"expiration_window": 0,
"origin_amount": "string",
"origin_chain_id": 0,
"origin_token": "string",
"user_address": "string"
}
]
```
--------------------------------
### Run OmniRPC via Docker
Source: https://docs.synapseprotocol.com/docs/Services/Omnirpc
Execute the OmniRPC service using the official Docker image.
```bash
docker run ghcr.io/synapsecns/sanguine/omnirpc:latest --config /path/to/config
```