Synthetix
- class synthetix.Synthetix(provider_rpc: str, op_mainnet_rpc: str = 'https://optimism.llamarpc.com', ipfs_gateway: str = 'https://ipfs.synthetix.io/ipfs/', address: str = '0x0000000000000000000000000000000000000000', private_key: str | None = None, network_id: int | None = None, core_account_id: int | None = None, perps_account_id: int | None = None, perps_disabled_markets: list | None = None, tracking_code: str = '0x53594e5448455449585f53444b00000000000000000000000000000000000000', referrer: str = '0x0000000000000000000000000000000000000000', max_price_impact: float = 2.0, use_estimate_gas: bool = True, cannon_config: dict | None = None, gql_endpoint_perps: str | None = None, gql_endpoint_rates: str | None = None, satsuma_api_key: str | None = None, price_service_endpoint: str | None = None, pyth_cache_ttl: int = 60, gas_multiplier: float = 2.0, is_fork: bool = False, request_kwargs: dict = {})
The main class for interacting with the Synthetix protocol. The class requires a provider RPC endpoint and a wallet address:
snx = Synthetix( provider_rpc='https://base-mainnet.infura.io/v3/...', network_id=8453, address='0x12345...' )
The class can be initialized with a private key to allow for transactions to be signed and sent to your RPC:
snx = Synthetix( provider_rpc='https://base-mainnet.infura.io/v3/...', network_id=8453, address='0x12345...', private_key='0xabcde...' )
- Parameters:
provider_rpc (str) – An RPC endpoint to use for the provider that interacts with the smart contracts. This must match the
network_id
.op_mainnet_rpc (str) – An Optimism mainnet RPC endpoint to use for the provider that fetches deployments from the Cannon registry.
ipfs_gateway (str) – An IPFS gateway to use for fetching deployments from Cannon.
address (str) – Wallet address to use as a default. If a private key is specified, this address will be used to sign transactions.
private_key (str) – Private key of the provided wallet address. If specified, the wallet will be enabled to sign and submit transactions.
network_id (int) – Network ID for the chain to connect to. This must match the chain ID of the RPC endpoint.
core_account_id (int) – A default
account_id
for core transactions. Setting a default will avoid the need to specify on each transaction. If not specified, the firstaccount_id
will be used.perps_account_id (int) – A default
account_id
for perps transactions. Setting a default will avoid the need to specify on each transaction. If not specified, the firstaccount_id
will be used.perps_disabled_markets (list) – A list of market ids to disable for perps trading. This is useful for disabling markets that are deprecated, or to limit the number of markets available for trading.
tracking_code (str) – Set a tracking code for trades.
referrer (str) – Set a referrer address for trades.
max_price_impact (float) – Max price impact setting for trades, specified as a percentage. This setting applies to both spot and perps markets.
use_estimate_gas (bool) – Use estimate gas for transactions. If false, it is assumed you will add a gas limit to all transactions.
gql_endpoint_perps (str) – GraphQL endpoint for perps data.
satsuma_api_key (str) – API key for Satsuma. If the endpoint is from Satsuma, the API key will be automatically added to the request.
price_service_endpoint (str) – Endpoint for a Pyth price service. If not specified, a default endpoint is used.
pyth_cache_ttl (int) – Time to live for Pyth cache in seconds.
gas_multiplier (float) – Multiplier for gas estimates. This is used to increase the gas limit for transactions.
is_fork (bool) – Set to true if the chain is a fork. This will improve the way price data is handled by requesting at the block timestamp.
- Returns:
Synthetix class instance
- Return type:
- _get_tx_params(value=0, to=None) TxParams
A helper function to prepare transaction parameters. This function will set up the transaction based on the parameters at initialization, but leave the
data
parameter empty.- Parameters:
value (int) – value to send with transaction
to (str | None) – address to send transaction to
- Returns:
A prepared transaction without the
data
parameter- Return type:
TxParams
- _load_contracts()
Initializes and sets up contracts according to the connected chain. On calling this function, the following contracts are connected and set up: *
PerpsV2MarketData
*PerpsV2MarketProxy
(for each V2 market) *sUSD
contracts for both V3 and legacy sUSD. *TrustedMulticallForwarder
(if available)These are stored as methods on the base Synthetix object:
>>> snx.susd_token.address 0x...
- Returns:
web3 contracts
- Return type:
[contract, contract, contract, contract]
- _send_transaction(tx_data: dict)
Send a prepared transaction to the connected RPC. If the RPC has a signer for the account in the from field, the transaction is sent directly to the RPC. For other addresses, if a private key is provided, the transaction is signed and sent to the RPC. Otherwise, this function will raise an error.
- Parameters:
tx_data (dict) – transaction data
- Returns:
A transaction hash
- Return type:
str
- allowance(token_address: str, spender_address: str, owner_address: str | None = None) float
Get the allowance for a target address to spend a specified ERC20 token for an owner. This is a general implementation that can be used for any ERC20 token.:
snx.allowance( snx.susd_token.address, snx.perps.market_proxy.address )
- Parameters:
token_address (str) – address of the token to approve
spender_address (str) – address to spender of the token
owner_address (str) – address to token owner. If not specified, the default address is used.
- Returns:
The allowance for the target address to spend the token for the owner
- Return type:
float
- approve(token_address: str, target_address: str, amount: float | None = None, submit: bool = False)
Approve an address to spend a specified ERC20 token. This is a general implementation that can be used for any ERC20 token. Specify the amount as an ether value, otherwise it will default to the maximum amount:
snx.approve( snx.susd_token.address, snx.perps.market_proxy.address, amount=1000 )
- Parameters:
token_address (str) – address of the token to approve
target_address (str) – address to approve to spend the token
amount (float) – amount of the token to approve
submit (bool) – submit the transaction
- Returns:
If
submit
, returns a transaction hash. Otherwise, returns the transaction parameters.- Return type:
str | dict
- execute_transaction(tx_data: dict, reset_nonce: bool = False)
Execute a provided transaction. This function will be signed with the provided private key and submitted to the connected RPC. The
Synthetix
object tracks the nonce internally, and will handle estimating gas limits if they are not provided.- Parameters:
tx_data (dict) – transaction data
reset_nonce (bool) – call the RPC to get the current nonce, otherwise use the stored nonce
- Returns:
A transaction hash
- Return type:
str
- get_eth_balance(address: str | None = None) dict
Gets current ETH and WETH balances at the specified address.
- Parameters:
address (str) – address to check balances for
- Returns:
A dictionary with the ETH and WETH balances
- Return type:
dict
- get_susd_balance(address: str | None = None, legacy: bool = False) dict
Gets current sUSD balance in wallet. Supports both legacy and V3 sUSD.
- Parameters:
address (str) – address to check balances for
legacy (bool) – check legacy sUSD balance
- Returns:
A dictionary with the sUSD balance
- Return type:
dict
- wait(tx_hash: str, timeout: int = 120)
Wait for a transaction to be confirmed and return the receipt. The function will throw an error if the timeout is exceeded. Use this as a helper function to wait for a transaction to be confirmed, then check the results and react accordingly.
- Parameters:
tx_hash (str) – transaction hash to wait for
timeout (int) – timeout in seconds
- Returns:
A transaction receipt
- Return type:
dict
- wrap_eth(amount: float, submit: bool = False) str
Wraps or unwaps ETH to/from the WETH implementation stored in the constants file. Negative numbers will unwrap ETH, positive numbers will wrap ETH:
snx.wrap_eth(1) snx.wrap_eth(-1)
- Parameters:
amount (float) – amount of ETH to wrap
submit (bool) – submit the transaction
- Returns:
If
submit
, returns a transaction hash. Otherwise, returns the transaction parameters.- Return type:
str | dict
- class synthetix.perps.PerpsV3(snx, default_account_id: int | None = None, disabled_markets=None)
Class for interacting with Synthetix Perps V3 contracts. Provides methods for creating and managing accounts, depositing and withdrawing collateral, committing and settling orders, and liquidating accounts.
Use
get_
methods to fetch information about accounts, markets, and orders:markets = snx.perps.get_markets() open_positions = snx.perps.get_open_positions()
Other methods prepare transactions, and submit them to your RPC:
create_tx_hash = snx.perps.create_account(submit=True) collateral_tx_hash = snx.perps.modify_collateral(amount=1000, market_name='sUSD', submit=True) order_tx_hash = snx.perps.commit_order(size=10, market_name='ETH', desired_fill_price=2000, submit=True)
An instance of this module is available as
snx.perps
. If you are using a network without perps deployed, the contracts will be unavailable and the methods will raise an error.The following contracts are required:
PerpsMarketProxy
PerpsAccountProxy
PythERC7412Wrapper
- Parameters:
snx (Synthetix) – An instance of the Synthetix class.
default_account_id (int | None) – The default
account_id
to use for transactions.
:param list | None : A list of market ids to disable.
- Returns:
An instance of the Perps class.
- Return type:
Perps
- _prepare_oracle_call(market_names: [<class 'str'>] = [])
Prepare a call to the external node with oracle updates for the specified market names. The result can be passed as the first argument to a multicall function to improve performance of ERC-7412 calls. If no market names are provided, all markets are fetched. This is useful for read functions since the user does not pay gas for those oracle calls, and reduces RPC calls and runtime.
- Parameters:
market_names ([str]) – A list of market names to fetch prices for. If not provided, all markets are fetched.
- Returns:
The address of the oracle contract, the value to send, and the encoded transaction data.
- Return type:
(str, int, str)
- commit_order(size: int, settlement_strategy_id: int = 0, market_id: int | None = None, market_name: str | None = None, account_id: int | None = None, desired_fill_price: float | None = None, max_price_impact: float | None = None, submit: bool = False)
Submit an order to the specified market. Keepers will attempt to fill the order according to the settlement strategy. If
desired_fill_price
is provided, the order will be filled at that price or better. Ifmax_price_impact
is provided, thedesired_fill_price
is calculated from the current market price and the price impact.- Parameters:
size (int) – The size of the order to submit.
settlement_strategy_id (int) – The id of the settlement strategy to use.
market_id (int | None) – The id of the market to submit the order to. If not provided, market_name must be provided.
market_name (str | None) – The name of the market to submit the order to. If not provided, market_id must be provided.
account_id (int | None) – The id of the account to submit the order for. Defaults to default_account_id.
desired_fill_price (float | None) – The max price for longs and minimum price for shorts. If not provided, one will be calculated based on max_price_impact.
max_price_impact (float | None) – The maximum price impact to allow when filling the order as a percentage (1.0 = 1%). If not provided, it will inherit the default value from snx.max_price_impact.
submit (bool) – If
True
, submit the transaction to the blockchain.
- Returns:
If submit, returns the trasaction hash. Otherwise, returns the transaction.
- get_can_liquidate(account_id: int | None = None)
Check if an
account_id
is eligible for liquidation.- Parameters:
account_id (int | None) – The id of the account to check. If not provided, the default account is used.
- Returns:
A boolean indicating if the account is eligible for liquidation.
- Return type:
bool
- get_can_liquidates(account_ids: [<class 'int'>] = [None])
Check if a batch of
account_id
are eligible for liquidation.- Parameters:
account_ids ([int]) – A list of account ids to check.
- Returns:
A list of tuples containing the
account_id
and a boolean indicating if the account is eligible for liquidation.- Return type:
[(int, bool)]
- get_collateral_balances(account_id: int | None = None)
Fetch the balance of each collateral type for an account.
- Parameters:
account_id (int | None) – The id of the account to fetch the collateral balances for. If not provided, the default account is used.
- Returns:
A dictionary with the collateral balances.
- Return type:
dict
- get_margin_info(account_id: int | None = None)
Fetch information about an account’s margin requirements and balances. Accounts must maintain an
available_margin
above themaintenance_margin_requirement
to avoid liquidation. Accounts withavailable_margin
below theinitial_margin_requirement
can not interact with their position unless they deposit more collateral.- Parameters:
account_id (int | None) – The id of the account to fetch the margin info for. If not provided, the default account is used.
- Returns:
A dictionary with the margin information.
- Return type:
dict
- get_market_summaries(market_ids: [<class 'int'>] = [])
Fetch the market summaries for a list of
market_id
.- Parameters:
market_ids ([int]) – A list of market ids to fetch.
- Returns:
A list of market summaries in the order of the input
market_ids
.- Return type:
[dict]
- get_market_summary(market_id: int | None = None, market_name: str | None = None)
Fetch the market summary for a single market, including information about the market’s price, open interest, funding rate, and skew. Provide either the market_id or market_name.
- Parameters:
market_id (int | None) – A market id to fetch the summary for.
market_name (str | None) – A market name to fetch the summary for.
- Returns:
A dictionary with the market summary.
- Return type:
dict
- get_markets()
Fetch the ids and summaries for all perps markets. Market summaries include information about the market’s price, open interest, funding rate, and skew:
markets_by_name = { 'ETH': { 'market_id': 100, 'market_name': 'ETH', 'skew': -15, 'size': 100, 'max_open_interest': 10000, 'current_funding_rate': 0.000182, 'current_funding_velocity': 0.00002765, 'index_price': 1852.59, ... } 'BTC': { ... } }
- Returns:
Market summaries keyed by market_id and market_name.
- Return type:
(dict, dict)
- get_open_position(market_id: int | None = None, market_name: int | None = None, account_id: int | None = None)
Fetch the position for a specified account and market. The result includes the unrealized pnl since the last interaction with this position, any accrued funding, and the position size. Provide either a
market_id
or amarket_name
:open_position = { 'pnl': 86.56, 'accrued_funding': -10.50, 'position_size': 10.0, }
- Parameters:
market_id (int | None) – The id of the market to fetch the position for.
market_name (str | None) – The name of the market to fetch the position for.
account_id (int | None) – The id of the account to fetch the position for. If not provided, the default account is used.
- Returns:
A dictionary with the position information.
- Return type:
dict
- get_open_positions(market_names: [<class 'str'>] = None, market_ids: [<class 'int'>] = None, account_id: int = None)
Get the open positions for a list of markets. Provide either a list of
market_name
ormarket_id
:open_positions = { 'ETH': { 'market_id': 100, 'market_name': 'ETH', 'pnl': 86.56, 'accrued_funding': -10.50, 'position_size': 10.0, }, 'BTC': { ... } }
- Parameters:
market_names ([str] | None) – A list of market names to fetch the positions for.
market_ids ([int] | None) – A list of market ids to fetch the positions for.
account_id (int | None) – The id of the account to fetch the positions for. If not provided, the default account is used.
- Returns:
A dictionary with the position information keyed by
market_name
.- Return type:
dict
- get_order(account_id: int | None = None, fetch_settlement_strategy: bool = True)
Fetches the open order for an account. Optionally fetches the settlement strategy, which can be useful for order settlement and debugging.
- Parameters:
account_id (int | None) – The id of the account. If not provided, the default account is used.
fetch_settlement_strategy (bool | None) – If
True
, fetch the settlement strategy information.
- Returns:
A dictionary with order information.
- Return type:
dict
- get_quote(size: float, price: float | None = None, market_id: int | None = None, market_name: str | None = None, account_id: int | None = None, settlement_strategy_id: int = 0, include_required_margin: bool = True)
Get a quote for the size of an order in a specified market. The quote includes the provided price and the fill price of the order after price impact. If a price is not provided, a price will be fetched from Pyth. Provide either a
market_id
ormarket_name
.- Parameters:
size (float) – The size of the order to quote.
price (float | None) – The price to quote the order at. If not provided, the current market price is used.
market_id (int | None) – The id of the market to quote the order for.
market_name (str | None) – The name of the market to quote the order for.
account_id (int | None) – The id of the account to quote the order for. If not provided, the default account is used.
settlement_strategy_id (int) – The id of the settlement strategy to use for the settlement reward calculation.
include_required_margin (bool) – If
True
, include the required margin for the account in the quote.
- Returns:
A dictionary with the quote information.
- Return type:
dict
- get_settlement_strategy(settlement_strategy_id: int, market_id: int | None = None, market_name: str | None = None)
Fetch the settlement strategy for a market. Settlement strategies describe the conditions under which an order can be settled. Provide either a
market_id
ormarket_name
.- Parameters:
settlement_strategy_id (int) – The id of the settlement strategy to fetch.
market_id (int | None) – The id of the market to fetch the settlement strategy for.
market_name (str | None) – The name of the market to fetch the settlement strategy for.
- Returns:
A dictionary with the settlement strategy information.
- Return type:
dict
- liquidate(account_id: int | None = None, submit: bool = False, static: bool = False)
Submit a liquidation for an account, or static call the liquidation function to fetch the liquidation reward. The static call is important for accounts which have been partially liquidated. Due to the throughput limit on liquidated value, the static call returning a nonzero value means more value can be liquidated (and rewards collected). This function can not be called if
submit
andstatic
are true.- Parameters:
account_id (int | None) – The id of the account to liquidate. If not provided, the default account is used.
submit (bool) – If
True
, submit the transaction to the blockchain.static (bool) – If
True
, static call the liquidation function to fetch the liquidation reward.
- Returns:
If
submit
, returns the trasaction hash. Ifstatic
, returns the liquidation reward. Otherwise, returns the transaction.- Return type:
str | dict | float
- modify_collateral(amount: int, market_id=None, market_name=None, account_id: int | None = None, submit: bool = False)
Move collateral in or out of a specified perps account. The
market_id
ormarket_name
must be provided to specify the collateral type. Provide either amarket_id
or amarket_name
. Note that themarket_id
here refers to the spot market id, not the perps market id. Make sure to approve the market proxy to transfer tokens of the collateral type before calling this function.- Parameters:
amount (int) – The amount of collateral to move. Positive values deposit collateral, negative values withdraw collateral.
market_id (int | None) – The id of the market to move collateral for.
market_name (str | None) – The name of the market to move collateral for.
account_id (int | None) – The id of the account to move collateral for. If not provided, the default account is used.
submit (bool) – If
True
, submit the transaction to the blockchain.
- Returns:
If
submit
, returns the trasaction hash. Otherwise, returns the transaction.- Return type:
str | dict
- pay_debt(amount: int | None = None, account_id: int | None = None, submit: bool = False)
Pay the debt of a perps account. If no amount is provided, the full debt of the account is repaid. Make sure to approve the proxy to transfer sUSD before calling this function.
- Parameters:
amount (int | None) – The amount of debt to repay. If not provided, the full debt is repaid.
account_id (int | None) – The id of the account to repay the debt for. If not provided, the default account is used.
submit (bool) – If
True
, submit the transaction to the blockchain.
- Returns:
If
submit
, returns the trasaction hash. Otherwise, returns the transaction.- Return type:
str | dict
- settle_order(account_id: int | None = None, submit: bool = False, max_tx_tries: int = 3, tx_delay: int = 2)
Settles an order using ERC7412 by handling
OracleDataRequired
errors and forming a multicall. If the order is not yet ready to be settled, this function will wait until the settlement time. If the transaction fails, this function will retry until the max number of tries is reached with a configurable delay.- Parameters:
account_id (int | None) – The id of the account to settle. If not provided, the default account is used.
submit (bool) – If
True
, submit the transaction to the blockchain.max_tx_tries (int) – The max number of tries to submit the transaction.
tx_delay (int) – The delay in seconds between transaction submissions.
- class synthetix.perps.BfPerps(snx, default_account_id: int | None = None)
Class for interacting with Synthetix Perps contracts on L1. Provides methods for creating and managing accounts, depositing and withdrawing collateral, committing and settling orders, and liquidating accounts.
Use
get_
methods to fetch information about accounts, markets, and orders:markets = snx.perps.get_markets() open_positions = snx.perps.get_open_positions()
Other methods prepare transactions, and submit them to your RPC:
create_tx_hash = snx.perps.create_account(submit=True) collateral_tx_hash = snx.perps.modify_collateral(amount=1000, market_name='sUSD', submit=True) order_tx_hash = snx.perps.commit_order(size=10, market_name='ETH', desired_fill_price=2000, submit=True)
An instance of this module is available as
snx.perps
. If you are using a network without perps deployed, the contracts will be unavailable and the methods will raise an error.The following contracts are required:
PerpsMarketProxy
PerpsAccountProxy
PythERC7412Wrapper
- Parameters:
- Returns:
An instance of the Perps class.
- Return type:
Perps
- cancel_stale_order(account_id: int | None = None, market_id: int | None = None, market_name: str | None = None, submit: bool = False)
Cancels and order for the specified account and market.
- Parameters:
account_id (int | None) – The id of the account to cancel the order for. If not provided, uses the default account.
market_id (int | None) – The id of the market to cancel the order in.
market_name (str | None) – The name of the market to cancel the order in.
submit (bool) – If True, submit the transaction to the blockchain. If False, return the transaction parameters.
- Returns:
If submit is True, returns the transaction hash. Otherwise, returns the transaction parameters.
- Return type:
str | dict
- commit_order(size: float, market_id: int | None = None, market_name: str | None = None, account_id: int | None = None, limit_price: float | None = None, keeper_fee_buffer_usd: float = 0, hooks: list | None = None, submit: bool = False)
Commit an order to the specified market.
- Parameters:
size (float) – The size of the order to submit. Positive for long, negative for short.
market_id (int | None) – The id of the market to submit the order to.
market_name (str | None) – The name of the market to submit the order to.
account_id (int | None) – The id of the account to submit the order for. Defaults to default_account_id.
limit_price (float | None) – The limit price for the order. If not provided, will use the current oracle price.
keeper_fee_buffer_usd (float) – Additional keeper fee buffer in USD.
hooks (list | None) – List of settlement hook addresses.
submit (bool) – If True, submit the transaction to the blockchain. If False, return the transaction parameters.
- Returns:
If submit is True, returns the transaction hash. Otherwise, returns the transaction parameters.
- Return type:
str | dict
- get_can_liquidate(account_id: int | None = None, market_id: int | None = None, market_name: str | None = None)
Check if an
account_id
is eligible for liquidation on a specified market- Parameters:
account_id (int | None) – The id of the account to check. If not provided, the default account is used.
- Returns:
A boolean indicating if the account is eligible for liquidation.
- Return type:
bool
- get_margin_info(account_id: int | None = None, market_id: int | None = None)
Fetch comprehensive information about an account’s margin requirements, balances, and position.
- Parameters:
account_id (int | None) – The id of the account to fetch the margin info for. If not provided, the default account is used.
market_id (int | None) – The id of the market to fetch the margin info for. Required parameter.
- Returns:
A dictionary with detailed margin and position information.
- Return type:
dict
- get_markets()
Fetch the ids and summaries for all perps markets. Market summaries include information about the market’s price, open interest, funding rate, and skew:
markets_by_name = { 'ETH': { 'market_id': 100, 'market_name': 'ETH', 'skew': -15, 'size': 100, 'max_open_interest': 10000, 'current_funding_rate': 0.000182, 'current_funding_velocity': 0.00002765, 'index_price': 1852.59, ... } 'BTC': { ... } }
- Returns:
Market summaries keyed by market_id and market_name.
- Return type:
(dict, dict)
- get_open_position(market_id: int | None = None, market_name: str | None = None, account_id: int | None = None)
Fetch the position for a specified account and market. The result includes detailed information about the position, including unrealized PnL, funding, size, and various margins.
- Parameters:
market_id (int | None) – The id of the market to fetch the position for.
market_name (str | None) – The name of the market to fetch the position for.
account_id (int | None) – The id of the account to fetch the position for. If not provided, the default account is used.
- Returns:
A dictionary with comprehensive position information.
- Return type:
dict
- get_order(account_id: int | None = None, market_id: int | None = None, market_name: str | None = None)
Fetches the open order for an account.
- Parameters:
account_id (int | None) – The id of the account. If not provided, the default account is used.
- Returns:
A dictionary with order information.
- Return type:
dict
- get_quote(size: float, market_id: int | None = None, market_name: str | None = None, account_id: int | None = None, keeper_fee_buffer_usd: float = 0)
Get a quote for the size of an order in a specified market. The quote includes the fill price of the order after price impact, estimated fees, and other relevant information.
- Parameters:
size (float) – The size of the order to quote (positive for long, negative for short).
market_id (int | None) – The id of the market to quote the order for.
market_name (str | None) – The name of the market to quote the order for.
account_id (int | None) – The id of the account to quote the order for. If not provided, the default account is used.
keeper_fee_buffer_usd (float) – Additional keeper fee buffer in USD.
- Returns:
A dictionary with the quote information.
- Return type:
dict
- modify_collateral(amount: float, collateral_address: str, market_id: int | None = None, market_name: str | None = None, account_id: int | None = None, submit: bool = False)
Modify the collateral for a specified account and market. Positive amounts deposit collateral, while negative amounts withdraw collateral.
- Parameters:
amount (float) – The amount of collateral to modify. Positive values deposit, negative values withdraw.
collateral_address (str) – The address of the collateral token to modify.
market_id (int | None) – The id of the market to modify collateral for.
market_name (str | None) – The name of the market to modify collateral for.
account_id (int | None) – The id of the account to modify collateral for. If not provided, the default account is used.
submit (bool) – If True, submit the transaction to the blockchain. If False, return the transaction parameters.
- Returns:
If submit is True, returns the transaction hash. Otherwise, returns the transaction parameters.
- Return type:
str | dict
- pay_debt(amount: int | None = None, account_id: int | None = None, market_id: int | None = None, market_name: str | None = None, submit: bool = False)
Pay the debt of a perps account. If no amount is provided, the full debt of the account is repaid. Make sure to approve the proxy to transfer sUSD before calling this function.
- Parameters:
amount (int | None) – The amount of debt to repay. If not provided, the full debt is repaid.
account_id (int | None) – The id of the account to repay the debt for. If not provided, the default account is used.
submit (bool) – If
True
, submit the transaction to the blockchain.
- Returns:
If
submit
, returns the trasaction hash. Otherwise, returns the transaction.- Return type:
str | dict
- settle_order(account_id: int | None = None, market_id: int | None = None, market_name: str | None = None, max_attempts: int = 3, attempt_delay: int = 5, submit: bool = False)
Settle an open order for the specified account and market.
- Parameters:
account_id (int | None) – The id of the account to settle the order for. If not provided, uses the default account.
market_id (int | None) – The id of the market to settle the order in.
market_name (str | None) – The name of the market to settle the order in.
max_attempts (int) – Maximum number of attempts to settle the order.
attempt_delay (int) – Delay in seconds between settlement attempts.
submit (bool) – If True, submit the transaction to the blockchain. If False, return the transaction parameters.
- Returns:
If submit is True, returns the transaction hash. Otherwise, returns the transaction parameters.
- Return type:
str | dict
- class synthetix.core.Core(snx, default_account_id: int | None = None)
Class for interacting with Synthetix V3 core contracts.
Provides methods for creating accounts, depositing and delegating collateral, minting sUSD, and interacting with liquidity pools.
Use
get_
methods to fetch information about accounts, collateral, and pools:account_ids = snx.core.get_account_ids() usd_token = snx.core.get_usd_token() available_collateral = snx.core.get_available_collateral()
Other methods prepare transactions to create accounts, deposit collateral, mint sUSD, etc. and submit them to the user’s RPC:
create_account_tx = snx.core.create_account(submit=True) deposit_tx = snx.core.deposit(amount=100, token='USDC', submit=True) mint_tx = snx.core.mint_usd(amount=50, submit=True)
An instance of this module is available as
snx.core
. If you are using a network without core contracts deployed, the contracts will be unavailable and the methods will raise an error.The following contracts are required:
CoreProxy
AccountProxy
- Parameters:
snx (Synthetix) – An instance of the Synthetix class
default_account_id (int) – The default account ID to use
- Returns:
An instance of the Core class
- Return type:
- create_account(account_id: int | None = None, submit: bool = False)
Create a new Synthetix account on the core system.
This function will mint an account NFT to the connected address. Each account can have separate LP positions.
- Parameters:
account_id (int) – The ID of the new account. If not provided, the next available ID will be used.
submit (bool) – If True, immediately submit the transaction to the blockchain. If False, build the transaction but do not submit.
- Returns:
The transaction hash if submitted, else the unsigned transaction data.
- Return type:
str | dict
- delegate_collateral(token_address: str, amount: float, pool_id: int, leverage: float = 1, account_id: int | None = None, submit: bool = False)
Delegate collateral for an account to a pool. In order to delegate, the account must have undelegated collateral for
token_address
and the pool must be accepting collateral fortoken_address
.Delegates an
amount
oftoken_address
collateral topool_id
withleverage
ratio fromaccount_id
.- Parameters:
token_address (str) – The address of the collateral token to delegate.
amount (float) – The amount of collateral to delegate.
pool_id (int) – The ID of the pool to delegate to.
leverage (float) – The leverage ratio, default 1.
account_id (int) – The account ID. Uses default if not provided.
submit (bool) – If True, submit the transaction.
- Returns:
The transaction hash if submitted, else the unsigned transaction
- Return type:
str | dict
- deposit(token_address: str, amount: float, decimals: int = 18, account_id: int | None = None, submit: bool = False)
Deposit collateral into the specified account. In order to deposit, the
token_address
must be enabled as collateral on the core system.Deposits an
amount
oftoken
as collateral into theaccount_id
.- Parameters:
amount (int) – The amount of tokens to deposit as collateral.
token (str) – The address of the token to deposit.
account_id (int) – The ID of the account to deposit into. Uses default if not provided.
submit (bool) – If True, immediately submit the transaction.
- Returns:
The transaction hash if submitted, else the unsigned transaction.
- Return type:
str | dict
- get_account_ids(address: str | None = None, default_account_id: int | None = None)
Get the core account IDs owned by an address.
Fetches the account IDs for the given address by checking the balance of the AccountProxy contract, which is an NFT owned by the address. If no address is provided, uses the connected wallet address.
- Parameters:
address (str) – The address to get accounts for. Uses connected address if not provided.
default_account_id (int) – The default account ID to set after fetching.
- Returns:
A list of account IDs owned by the address.
- Return type:
list
- get_available_collateral(token_address: str, account_id: int | None = None)
Get the available collateral for an account for a specified collateral type of
token_address
.Fetches the amount of undelegated collateral available for withdrawal for a given token and account.
- Parameters:
token_address (str) – The address of the collateral token.
account_id (int) – The ID of the account to check. Uses default if not provided.
- Returns:
The available collateral as an ether value.
- Return type:
float
- get_usd_token()
Get the address of the USD stablecoin token.
- mint_usd(token_address: str, amount: float, pool_id: int, account_id: int | None = None, submit: bool = False)
Mint sUSD to a core account. In order to mint, the account must have capacity to mint given the settings of the pool.
Mints
amount
of sUSD againsttoken_address
collateral inpool_id
foraccount_id
.- Parameters:
token_address (str) – The collateral token address.
amount (float) – The amount of sUSD to mint.
pool_id (int) – The ID of the pool to mint against.
account_id (int) – The account ID. Uses default if not provided.
submit (bool) – If True, submit the transaction.
- Returns:
The transaction hash if submitted, else the unsigned transaction
- Return type:
str | dict
- withdraw(amount: float, decimals: int = 18, token_address: str | None = None, account_id: int | None = None, submit: bool = False)
Withdraw collateral from the specified account. In order to withdraw, the account must have undelegated collateral for
token_address
and must be past the withdrawal delay.Withdraws an amount of token collateral from the account_id.
- Parameters:
amount (int) – The amount of tokens to withdraw from the account.
token (str) – The address of the token to withdraw.
account_id (int) – The ID of the account to withdraw from. Uses default if not provided.
submit (bool) – If True, immediately submit the transaction.
- Returns:
The transaction hash if submitted, else the unsigned transaction.
- Return type:
str | dict
- class synthetix.spot.Spot(snx)
Class for interacting with Synthetix V3 spot market contracts. Provider methods for wrapping and unwrapping assets, approvals, atomic orders, and async orders.
Use
get_
methods to fetch information about balances, allowances, and markets:markets_by_id, markets_by_name = snx.perps.get_markets() balance = snx.spot.get_balance(market_name='sUSD') allowance = snx.spot.get_allowance(snx.spot.market_proxy.address, market_name='sUSD')
Other methods prepare transactions, and submit them to your RPC:
wrap_tx_hash = snx.spot.wrap(100, market_name='sUSDC', submit=True) unwrap_tx_hash = snx.spot.wrap(-100, market_name='sUSDC', submit=True) atomic_buy_tx_hash = snx.spot.atomic_order('buy', 100, market_name='sUSDC', submit=True)
An instance of this module is available as
snx.spot
. If you are using a network without spot contracts deployed, the contracts will be unavailable and the methods will raise an error.The following contracts are required:
SpotMarketProxy
- Parameters:
- Returns:
An instance of the Spot class.
- Return type:
- _format_size(size: float, market_id: int)
Format the size of a synth for an order. This is used for synths whose base asset does not use 18 decimals. For example, USDC uses 6 decimals, so we need to handle size differently from other assets.
- Parameters:
size (float) – The size as an ether value (e.g. 100).
market_id (int) – The id of the market.
- Returns:
The formatted size in wei. (e.g. 100 = 100000000000000000000)
- Return type:
int
- _get_synth_contract(market_id: int | None = None, market_name: str | None = None)
Private method to fetch the underlying synth contract for a market. Synths are represented as an ERC20 token, so this is useful to do things like check allowances or transfer tokens. This method requires a
market_id
ormarket_name
to be provided.- Parameters:
market_id (int | None) – The id of the market.
market_name (str | None) – The name of the market.
- Returns:
A contract object for the underlying synth.
- Return type:
web3.eth.Contract
- _resolve_market(market_id: int, market_name: str)
Look up the market_id and market_name for a market. If only one is provided, the other is resolved. If both are provided, they are checked for consistency.
- Parameters:
market_id (int | None) – The id of the market. If not known, provide
None
.market_name (str | None) – The name of the market. If not known, provide
None
.
- Returns:
The
market_id
andmarket_name
for the market.- Return type:
(int, str)
- approve(target_address: str, amount: int | None = None, market_id: int | None = None, market_name: str | None = None, submit: bool = False)
Approve an address to transfer a specified synth from the connected address.
Approves the
target_address
to transfer up to theamount
from your account. Ifamount
isNone
, approves the maximum possible amount.Requires either a
market_id
ormarket_name
to be provided to resolve the market.- Parameters:
target_address (str) – The address to approve.
amount (int) – The amount in ether to approve. Default is max uint256.
market_id (int) – The ID of the market.
market_name (str) – The name of the market.
submit (bool) – Whether to broadcast the transaction.
- Returns:
The transaction dict if submit=False, otherwise the tx hash.
- atomic_order(side: Literal['buy', 'sell'], size: int, slippage_tolerance: float = 0, min_amount_received: int | None = None, market_id: int | None = None, market_name: str | None = None, submit: bool = False)
Execute an atomic order on the spot market.
Atomically executes a buy or sell order for the given size.
Amounts are transferred directly, no need to settle later. This function is useful for swapping sUSDC with sUSD on Base Andromeda contracts. The default slippage is set to zero, since sUSDC and sUSD can be swapped 1:1:
atomic_order("sell", 100, market_name="sUSDC")
Requires either a
market_id
ormarket_name
to be provided to resolve the market.- Parameters:
side (Literal["buy", "sell"]) – The side of the order (buy/sell).
size (int) – The order size in ether.
slippage_tolerance (float) – The slippage tolerance for the order as a percentage (0.01 = 1%). Default is 0.
min_amount_received (int) – The minimum amount to receive in ether units. This will override the slippage_tolerance.
market_id (int) – The ID of the market.
market_name (str) – The name of the market.
submit (bool) – Whether to broadcast the transaction.
- Returns:
The transaction dict if submit=False, otherwise the tx hash.
- commit_order(side: Literal['buy', 'sell'], size: int, slippage_tolerance: float = 0, min_amount_received: int | None = None, settlement_strategy_id: int = 0, market_id: int | None = None, market_name: str | None = None, submit: bool = False)
Commit an async order to the spot market.
Commits a buy or sell order of the given size. The order will be settled according to the settlement strategy.
Requires either a
market_id
ormarket_name
to be provided to resolve the market.- Parameters:
side (Literal["buy", "sell"]) – The side of the order (buy/sell).
size (int) – The order size in ether. If
side
is “buy”, this is the amount of the synth to buy. Ifside
is “sell”, this is the amount of the synth to sell.slippage_tolerance (float) – The slippage tolerance for the order as a percentage (0.01 = 1%). Default is 0.
min_amount_received (int) – The minimum amount to receive in ether units. This will override the slippage_tolerance.
settlement_strategy_id (int) – The settlement strategy ID. Default 2.
market_id (int) – The ID of the market.
market_name (str) – The name of the market.
submit (bool) – Whether to broadcast the transaction.
- Returns:
The transaction dict if submit=False, otherwise the tx hash.
- get_allowance(target_address: str, address: str | None = None, market_id: int | None = None, market_name: str | None = None)
Get the allowance for a
target_address
to transfer fromaddress
. Provide either amarket_id
ormarket_name
to choose the synth.- Parameters:
target_address (str) – The address for which to check allowance.
address (str) – The owner address to check allowance for.
market_id (int) – The id of the market.
market_name (str) – The name of the market.
- Returns:
The allowance in ether.
- Return type:
float
- get_balance(address: str | None = None, market_id: int | None = None, market_name: str | None = None)
Get the balance of a spot synth. Provide either a
market_id
ormarket_name
to choose the synth.- Parameters:
address (str | None) – The address to check the balance of. If not provided, the current account will be used.
market_id (int | None) – The id of the market.
market_name (str | None) – The name of the market.
- Returns:
The balance of the synth in ether.
- Return type:
float
- get_markets()
Fetches contracts and metadata about all spot markets on the network. This includes the market id, synth name, contract address, and the underlying synth contract. Each synth is an ERC20 token, so these contracts can be used for transfers and allowances. The metadata is also used to simplify interactions in the SDK by mapping market ids and names to their metadata:
>>> snx.spot.wrap(100, market_name='sUSDC', submit=True)
This will look up the market id for the sUSDC market and use that to wrap 100 USDC into sUSDC.
The market metadata is returned from the method as a tuple of two dictionaries. The first is keyed by
market_id
and the second is keyed bymarket_name
:>>> snx.spot.markets_by_name { 'sUSD': {'market_id': 0, 'contract': ...}, ...} >>> snx.spot.markets_by_id { '0': {'market_name': 'sUSD', 'contract': ...}, ...}
- Returns:
Market info keyed by
market_id
andmarket_name
.- Return type:
(dict, dict)
- get_order(async_order_id: int, market_id: int | None = None, market_name: str | None = None, fetch_settlement_strategy: bool = True)
Get details about an async order by its ID.
Retrieves order details like owner, amount escrowed, settlement strategy, etc. Can also fetch the full settlement strategy parameters if
fetch_settlement_strategy
isTrue
.Requires either a
market_id
ormarket_name
to be provided to resolve the market.- Parameters:
async_order_id (int) – The ID of the async order to retrieve.
market_id (int) – The ID of the market.
market_name (str) – The name of the market.
fetch_settlement_strategy (bool) – Whether to fetch the full settlement strategy parameters. Default is True.
- Returns:
The order details.
- Return type:
dict
- get_settlement_strategies(strategy_id: int, market_ids: list[int] | None = None)
Fetch the settlement strategy id for all spot markets.
- Parameters:
settlement_strategy_id (int) – The id of the settlement strategy to retrieve.
market_id (int) – The ids of the markets.
- Returns:
The settlement strategy parameters.
- Return type:
dict
- get_settlement_strategy(settlement_strategy_id: int, market_id: int | None = None, market_name: str | None = None)
Fetch the settlement strategy for a spot market.
- Parameters:
settlement_strategy_id (int) – The id of the settlement strategy to retrieve.
market_id (int) – The id of the market.
market_name (str) – The name of the market.
- Returns:
The settlement strategy parameters.
- Return type:
dict
- settle_order(async_order_id: int, market_id: int | None = None, market_name: str | None = None, max_tx_tries: int = 5, tx_delay: int = 2, submit: bool = False)
Settle an async Pyth order after price data is available.
Fetches the price for the order from Pyth and settles the order. Retries up to
max_tx_tries
times on failure with a delay oftx_delay
seconds.Requires either a
market_id
ormarket_name
to be provided to resolve the market.- Parameters:
async_order_id (int) – The ID of the async order to settle.
market_id (int) – The ID of the market. (e.g. “ETH”)
market_name (str) – The name of the market.
max_tx_tries (int) – Max retry attempts if price fetch fails.
tx_delay (int) – Seconds to wait between retries.
submit (bool) – Whether to broadcast the transaction.
- Returns:
The transaction dict if submit=False, otherwise the tx hash.
- wrap(size: int, market_id: int | None = None, market_name: str | None = None, submit: bool = False)
Wrap an underlying asset into a synth or unwrap back to the asset.
Wraps an asset into a synth if size > 0, unwraps if size < 0. The default slippage is set to zero, since the synth and asset can be swapped 1:1.:
wrap(100, market_name="sUSDC") # wrap 100 USDC into sUSDC wrap(-100, market_name="sUSDC") # wrap 100 USDC into sUSDC
Requires either a
market_id
ormarket_name
to be provided to resolve the market.- Parameters:
size (int) – The amount of the asset to wrap/unwrap.
market_id (int) – The ID of the market.
market_name (str) – The name of the market.
submit (bool) – Whether to broadcast the transaction.
- Returns:
The transaction dict if submit=False, otherwise the tx hash.
- class synthetix.pyth.Pyth(snx, cache_ttl, price_service_endpoint: str | None = None)
Class for interacting with the Pyth price service. The price service is connected to the endpoint specified as
price_service_endpoint
when initializing theSynthetix
class:snx = Synthetix( ..., price_service_endpoint='https://hermes.pyth.network' )
If an endpoint isn’t specified, the default endpoint is used. The default endpoint should be considered unreliable for production applications.
The
Pyth
class is used to fetch the latest price update data for a list of tokens or feed ids:price_data_symbol = snx.pyth.get_price_from_symbols(['SNX', 'ETH']) price_data_id = snx.pyth.get_price_from_ids(['0x12345...', '0xabcde...'])
- Parameters:
snx (Synthetix) – Synthetix class instance
price_service_endpoint (str) – Pyth price service endpoint
cache_ttl (int) – Cache time-to-live in seconds
- Returns:
Pyth class instance
- Return type:
- get_price_from_ids(feed_ids: [<class 'str'>], publish_time: int | None = None)
Fetch the latest Pyth price data for a list of feed ids. This is the most reliable way to specify the exact feed you want to fetch data for. The feed ids can be found in the Pyth price service documentation, or at a price service API. This function calls the V2 endpoint
updates/price/latest
to fetch the data. Specify a publish time in order to fetch benchmark data.Usage:
>>> snx.pyth.get_price_from_ids(['0x12345...', '0xabcde...']) { "price_update_data": [b'...', b'...'], "meta": { "0x12345...": { "symbol": "ETH", "price": 2000, "publish_time": 1621203900 } }
- Parameters:
feed_ids ([str]) – List of feed ids to fetch data for
publish_time (int) – Publish time for benchmark data
- Returns:
Dictionary with price update data and metadata
- Return type:
dict | None
- get_price_from_symbols(symbols: [<class 'str'>], publish_time: int | None = None)
Fetch the latest Pyth price data for a list of market symbols. This function is the same as
get_price_from_ids
but uses the symbol to fetch the feed id from the lookup table.Usage:
>>> snx.pyth.get_price_from_symbols(['ETH', 'BTC']) { "price_update_data": [b'...', b'...'], "meta": { "0x12345...": { "symbol": "ETH", "price": 2000, "publish_time": 1621203900 } }
- Parameters:
symbols ([str]) – List of symbols to fetch data for
publish_time (int) – Publish time for benchmark data
- Returns:
Dictionary with price update data and metadata
- Return type:
dict | None
- update_price_feed_ids(feed_ids: dict)
Update the price feed IDs for the Pyth price service. Additionally sets a lookup for feed_id to symbol.
- Parameters:
feed_ids (dict) – Dictionary of feed IDs to update