Smart Contracts
Synthetix Core
Account Module
getAccountPermissions
Returns an array of AccountPermission
for the provided accountId
.
Parameters
accountId
(uint128) - The id of the account whose permissions are being retrieved.
Returns
accountPerms
(struct IAccountModule.AccountPermissions[]) - An array of AccountPermission objects describing the permissions granted to the account.
createAccount
Mints an account token with id requestedAccountId
to ERC2771Context._msgSender()
.
Parameters
requestedAccountId
(uint128) - The id requested for the account being created. Reverts if id already exists. Requirements: -requestedAccountId
must not already be minted. -requestedAccountId
must be less than type(uint128).max / 2 Emits a {AccountCreated} event.
createAccount
Mints an account token with an available id to ERC2771Context._msgSender()
.
Emits a {AccountCreated} event.
notifyAccountTransfer
Called by AccountTokenModule to notify the system when the account token is transferred.
Resets user permissions and assigns ownership of the account token to the new holder.
Parameters
to
(address) - The new holder of the account NFT.accountId
(uint128) - The id of the account that was just transferred. Requirements: -ERC2771Context._msgSender()
must be the account token.
grantPermission
Grants permission
to user
for account accountId
.
Parameters
accountId
(uint128) - The id of the account that granted the permission.permission
(bytes32) - The bytes32 identifier of the permission.user
(address) - The target address that received the permission. Requirements: -ERC2771Context._msgSender()
must own the account token with IDaccountId
or have the "admin" permission. Emits a {PermissionGranted} event.
revokePermission
Revokes permission
from user
for account accountId
.
Parameters
accountId
(uint128) - The id of the account that revoked the permission.permission
(bytes32) - The bytes32 identifier of the permission.user
(address) - The target address that no longer has the permission. Requirements: -ERC2771Context._msgSender()
must own the account token with IDaccountId
or have the "admin" permission. Emits a {PermissionRevoked} event.
renouncePermission
Revokes permission
from ERC2771Context._msgSender()
for account accountId
.
Parameters
accountId
(uint128) - The id of the account whose permission was renounced.permission
(bytes32) - The bytes32 identifier of the permission. Emits a {PermissionRevoked} event.
hasPermission
Returns true
if user
has been granted permission
for account accountId
.
Parameters
accountId
(uint128) - The id of the account whose permission is being queried.permission
(bytes32) - The bytes32 identifier of the permission.user
(address) - The target address whose permission is being queried.
Returns
hasPermission
(bool) - A boolean with the response of the query.
isAuthorized
Returns true
if target
is authorized to permission
for account accountId
.
Parameters
accountId
(uint128) - The id of the account whose permission is being queried.permission
(bytes32) - The bytes32 identifier of the permission.target
(address) - The target address whose permission is being queried.
Returns
isAuthorized
(bool) - A boolean with the response of the query.
getAccountTokenAddress
Returns the address for the account token used by the module.
Returns
accountNftToken
(address) - The address of the account token.
getAccountOwner
Returns the address that owns a given account, as recorded by the system.
Parameters
accountId
(uint128) - The account id whose owner is being retrieved.
Returns
owner
(address) - The owner of the given account id.
getAccountLastInteraction
Returns the last unix timestamp that a permissioned action was taken with this account
Parameters
accountId
(uint128) - The account id to check
Returns
timestamp
(uint256) - The unix timestamp of the last time a permissioned action occured with the account
AccountCreated
Emitted when an account token with id accountId
is minted to sender
.
Parameters
accountId
(uint128) - The id of the account.owner
(address) - The address that owns the created account.
PermissionGranted
Emitted when user
is granted permission
by sender
for account accountId
.
Parameters
accountId
(uint128) - The id of the account that granted the permission.permission
(bytes32) - The bytes32 identifier of the permission.user
(address) - The target address to whom the permission was granted.sender
(address) - The Address that granted the permission.
PermissionRevoked
Emitted when user
has permission
renounced or revoked by sender
for account accountId
.
Parameters
accountId
(uint128) - The id of the account that has had the permission revoked.permission
(bytes32) - The bytes32 identifier of the permission.user
(address) - The target address for which the permission was revoked.sender
(address) - The address that revoked the permission.
Account Token Module
isInitialized
Returns whether the token has been initialized.
Returns
[0]
(bool) - A boolean with the result of the query.
initialize
Initializes the token with name, symbol, and uri.
mint
Allows the owner to mint tokens.
Parameters
to
(address) - The address to receive the newly minted tokens.tokenId
(uint256) - The ID of the newly minted token
safeMint
Allows the owner to mint tokens. Verifies that the receiver can receive the token
Parameters
to
(address) - The address to receive the newly minted token.tokenId
(uint256) - The ID of the newly minted tokendata
(bytes) - any data which should be sent to the receiver
burn
Allows the owner to burn tokens.
Parameters
tokenId
(uint256) - The token to burn
setAllowance
Allows an address that holds tokens to provide allowance to another.
Parameters
tokenId
(uint256) - The token which should be allowed to spenderspender
(address) - The address that is given allowance.
setBaseTokenURI
Allows the owner to update the base token URI.
Parameters
uri
(string) - The new base token uri
totalSupply
Returns the total amount of tokens stored by the contract.
tokenOfOwnerByIndex
Returns a token ID owned by owner
at a given index
of its token list. Use along with {balanceOf} to enumerate all of owner
's tokens.
Requirements:
owner
must be a valid addressindex
must be less than the balance of the tokens for the owner
tokenByIndex
Returns a token ID at a given index
of all the tokens stored by the contract. Use along with {totalSupply} to enumerate all tokens.
Requirements:
index
must be less than the total supply of the tokens
balanceOf
Returns the number of tokens in owner
's account.
Requirements:
holder
must be a valid address
ownerOf
Returns the owner of the tokenId
token.
Requirements:
tokenId
must exist.
safeTransferFrom
Safely transfers tokenId
token from from
to to
.
Requirements:
from
cannot be the zero address.to
cannot be the zero address.tokenId
token must exist and be owned byfrom
.If the caller is not
from
, it must be approved to move this token by either {approve} or {setApprovalForAll}.If
to
refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
Emits a {Transfer} event.
safeTransferFrom
Safely transfers tokenId
token from from
to to
, checking first that contract recipients are aware of the ERC721 protocol to prevent tokens from being forever locked.
Requirements:
from
cannot be the zero address.to
cannot be the zero address.tokenId
token must exist and be owned byfrom
.If the caller is not
from
, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.If
to
refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
Emits a {Transfer} event.
transferFrom
Transfers tokenId
token from from
to to
.
WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
Requirements:
from
cannot be the zero address.to
cannot be the zero address.tokenId
token must be owned byfrom
.If the caller is not
from
, it must be approved to move this token by either {approve} or {setApprovalForAll}.
Emits a {Transfer} event.
approve
Gives permission to to
to transfer tokenId
token to another account. The approval is cleared when the token is transferred.
Only a single account can be approved at a time, so approving the zero address clears previous approvals.
Requirements:
The caller must own the token or be an approved operator.
tokenId
must exist.
Emits an {Approval} event.
setApprovalForAll
Approve or remove operator
as an operator for the caller. Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
Requirements:
The
operator
cannot be the caller.
Emits an {ApprovalForAll} event.
getApproved
Returns the account approved for tokenId
token.
Requirements:
tokenId
must exist.
isApprovedForAll
Returns if the operator
is allowed to manage all of the assets of owner
.
See {setApprovalForAll}
Transfer
Emitted when tokenId
token is transferred from from
to to
.
Approval
Emitted when owner
enables approved
to manage the tokenId
token.
ApprovalForAll
Emitted when owner
enables or disables (approved
) operator
to manage all of its assets.
Associate Debt Module
associateDebt
Allows a market to associate debt with a specific position. The specified debt will be removed from all vault participants pro-rata. After removing the debt, the amount will be allocated directly to the specified account. NOTE: if the specified account is an existing staker on the vault, their position will be included in the pro-rata reduction. Ex: if there are 10 users staking 10 USD of debt on a pool, and associate debt is called with 10 USD on one of those users, their debt after the operation is complete will be 19 USD. This might seem unusual, but its actually ideal behavior when your market has incurred some new debt, and it wants to allocate this amount directly to a specific user. In this case, the user's debt balance would increase pro rata, but then get decreased pro-rata, and then increased to the full amount on their account. All other accounts would be left with no change to their debt, however.
Parameters
marketId
(uint128) - The id of the market to which debt was associated.poolId
(uint128) - The id of the pool associated to the target market.collateralType
(address) - The address of the collateral type that acts as collateral in the corresponding pool.accountId
(uint128) - The id of the account whose debt is being associated.amount
(uint256) - The amount of debt being associated with the specified account, denominated with 18 decimals of precision.
Returns
debtAmount
(int256) - The updated debt of the position, denominated with 18 decimals of precision.
DebtAssociated
Emitted when associateDebt
is called.
Parameters
marketId
(uint128) - The id of the market to which debt was associated.poolId
(uint128) - The id of the pool associated to the target market.collateralType
(address) - The address of the collateral type that acts as collateral in the corresponding pool.accountId
(uint128) - The id of the account whose debt is being associated.amount
(uint256) - The amount of debt being associated with the specified account, denominated with 18 decimals of precision.updatedDebt
(int256) - The total updated debt of the account, denominated with 18 decimals of precision
Collateral Configuration Module
configureCollateral
Creates or updates the configuration for the given collateralType
.
Parameters
config
(struct CollateralConfiguration.Data) - The CollateralConfiguration object describing the new configuration. Requirements: -ERC2771Context._msgSender()
must be the owner of the system. Emits a {CollateralConfigured} event.
getCollateralConfigurations
Returns a list of detailed information pertaining to all collateral types registered in the system.
Optionally returns only those that are currently enabled.
Parameters
hideDisabled
(bool) - Wether to hide disabled collaterals or just return the full list of collaterals in the system.
Returns
collaterals
(struct CollateralConfiguration.Data[]) - The list of collateral configuration objects set in the system.
getCollateralConfiguration
Returns detailed information pertaining the specified collateral type.
Parameters
collateralType
(address) - The address for the collateral whose configuration is being queried.
Returns
collateral
(struct CollateralConfiguration.Data) - The configuration object describing the given collateral.
getCollateralPrice
Returns the current value of a specified collateral type.
Parameters
collateralType
(address) - The address for the collateral whose price is being queried.
Returns
priceD18
(uint256) - The price of the given collateral, denominated with 18 decimals of precision.
CollateralConfigured
Emitted when a collateral type’s configuration is created or updated.
Parameters
collateralType
(address) - The address of the collateral type that was just configured.config
(struct CollateralConfiguration.Data) - The object with the newly configured details.
Collateral Module
deposit
Deposits tokenAmount
of collateral of type collateralType
into account accountId
.
Anyone can deposit into anyone's active account without restriction.
Parameters
accountId
(uint128) - The id of the account that is making the deposit.collateralType
(address) - The address of the token to be deposited.tokenAmount
(uint256) - The amount being deposited, denominated in the token's native decimal representation. Emits a {Deposited} event.
withdraw
Withdraws tokenAmount
of collateral of type collateralType
from account accountId
.
Parameters
accountId
(uint128) - The id of the account that is making the withdrawal.collateralType
(address) - The address of the token to be withdrawn.tokenAmount
(uint256) - The amount being withdrawn, denominated in the token's native decimal representation. Requirements: -ERC2771Context._msgSender()
must be the owner of the account, have theADMIN
permission, or have theWITHDRAW
permission. Emits a {Withdrawn} event.
getAccountCollateral
Returns the total values pertaining to account accountId
for collateralType
.
Parameters
accountId
(uint128) - The id of the account whose collateral is being queried.collateralType
(address) - The address of the collateral type whose amount is being queried.
Returns
totalDeposited
(uint256) - The total collateral deposited in the account, denominated with 18 decimals of precision.totalAssigned
(uint256) - The amount of collateral in the account that is delegated to pools, denominated with 18 decimals of precision.totalLocked
(uint256) - The amount of collateral in the account that cannot currently be undelegated from a pool, denominated with 18 decimals of precision.
getAccountAvailableCollateral
Returns the amount of collateral of type collateralType
deposited with account accountId
that can be withdrawn or delegated to pools.
Parameters
accountId
(uint128) - The id of the account whose collateral is being queried.collateralType
(address) - The address of the collateral type whose amount is being queried.
Returns
amountD18
(uint256) - The amount of collateral that is available for withdrawal or delegation, denominated with 18 decimals of precision.
cleanExpiredLocks
Clean expired locks from locked collateral arrays for an account/collateral type. It includes offset and items to prevent gas exhaustion. If both, offset and items, are 0 it will traverse the whole array (unlimited).
Parameters
accountId
(uint128) - The id of the account whose locks are being cleared.collateralType
(address) - The address of the collateral type to clean locks for.offset
(uint256) - The index of the first lock to clear.count
(uint256) - The number of slots to check for cleaning locks. Set to 0 to clean all locks at/after offset
Returns
cleared
(uint256) - the number of locks that were actually expired (and therefore cleared)
getLocks
Get a list of locks existing in account. Lists all locks in storage, even if they are expired
Parameters
accountId
(uint128) - The id of the account whose locks we want to readcollateralType
(address) - The address of the collateral type for locks we want to readoffset
(uint256) - The index of the first lock to readcount
(uint256) - The number of slots to check for cleaning locks. Set to 0 to read all locks after offset
createLock
Create a new lock on the given account. you must have admin
permission on the specified account to create a lock.
Collateral can be withdrawn from the system if it is not assigned or delegated to a pool. Collateral locks are an additional restriction that applies on top of that. I.e. if collateral is not assigned to a pool, but has a lock, it cannot be withdrawn. Collateral locks are initially intended for the Synthetix v2 to v3 migration, but may be used in the future by the Spartan Council, for example, to create and hand off accounts whose withdrawals from the system are locked for a given amount of time.
Parameters
accountId
(uint128) - The id of the account for which a lock is to be created.collateralType
(address) - The address of the collateral type for which the lock will be created.amount
(uint256) - The amount of collateral tokens to wrap in the lock being created, denominated with 18 decimals of precision.expireTimestamp
(uint64) - The date in which the lock will become clearable.
Deposited
Emitted when tokenAmount
of collateral of type collateralType
is deposited to account accountId
by sender
.
Parameters
accountId
(uint128) - The id of the account that deposited collateral.collateralType
(address) - The address of the collateral that was deposited.tokenAmount
(uint256) - The amount of collateral that was deposited, denominated in the token's native decimal representation.sender
(address) - The address of the account that triggered the deposit.
CollateralLockCreated
Emitted when a lock is created on someone's account
Parameters
accountId
(uint128) - The id of the account that received a lockcollateralType
(address) - The address of the collateral type that was lockedtokenAmount
(uint256) - The amount of collateral that was locked, demoninated in system units (1e18)expireTimestamp
(uint64) - unix timestamp at which the lock is due to expire
CollateralLockExpired
Emitted when a lock is cleared from an account due to expiration
Parameters
accountId
(uint128) - The id of the account that has the expired lockcollateralType
(address) - The address of the collateral type that was unlockedtokenAmount
(uint256) - The amount of collateral that was unlocked, demoninated in system units (1e18)expireTimestamp
(uint64) - unix timestamp at which the unlock is due to expire
Withdrawn
Emitted when tokenAmount
of collateral of type collateralType
is withdrawn from account accountId
by sender
.
Parameters
accountId
(uint128) - The id of the account that withdrew collateral.collateralType
(address) - The address of the collateral that was withdrawn.tokenAmount
(uint256) - The amount of collateral that was withdrawn, denominated in the token's native decimal representation.sender
(address) - The address of the account that triggered the withdrawal.
Cross ChainUSD Module
transferCrossChain
Allows users to transfer tokens cross-chain using CCIP.
Parameters
destChainId
(uint64) - The id of the chain where tokens are to be transferred to.amount
(uint256) - The amount of tokens to be transferred, denominated with 18 decimals of precision.
Returns
gasTokenUsed
(uint256) - The amount of fees paid in the cross-chain transfer, denominated with 18 decimals of precision.
TransferCrossChainInitiated
IssueUSD Module
mintUsd
Mints {amount} of snxUSD with the specified liquidity position.
Parameters
accountId
(uint128) - The id of the account that is minting snxUSD.poolId
(uint128) - The id of the pool whose collateral will be used to back up the mint.collateralType
(address) - The address of the collateral that will be used to back up the mint.amount
(uint256) - The amount of snxUSD to be minted, denominated with 18 decimals of precision. Requirements: -ERC2771Context._msgSender()
must be the owner of the account, have theADMIN
permission, or have theMINT
permission. - After minting, the collateralization ratio of the liquidity position must not be below the target collateralization ratio for the corresponding collateral type. Emits a {UsdMinted} event.
burnUsd
Burns {amount} of snxUSD with the specified liquidity position.
Parameters
accountId
(uint128) - The id of the account that is burning snxUSD.poolId
(uint128) - The id of the pool whose collateral was used to back up the snxUSD.collateralType
(address) - The address of the collateral that was used to back up the snxUSD.amount
(uint256) - The amount of snxUSD to be burnt, denominated with 18 decimals of precision. Emits a {UsdMinted} event.
UsdMinted
Emitted when {sender} mints {amount} of snxUSD with the specified liquidity position.
Parameters
accountId
(uint128) - The id of the account for which snxUSD was emitted.poolId
(uint128) - The id of the pool whose collateral was used to emit the snxUSD.collateralType
(address) - The address of the collateral that is backing up the emitted snxUSD.amount
(uint256) - The amount of snxUSD emitted, denominated with 18 decimals of precision.sender
(address) - The address that triggered the operation.
UsdBurned
Emitted when {sender} burns {amount} of snxUSD with the specified liquidity position.
Parameters
accountId
(uint128) - The id of the account for which snxUSD was burned.poolId
(uint128) - The id of the pool whose collateral was used to emit the snxUSD.collateralType
(address) - The address of the collateral that was backing up the emitted snxUSD.amount
(uint256) - The amount of snxUSD burned, denominated with 18 decimals of precision.sender
(address) - The address that triggered the operation.
IssuanceFeePaid
Liquidation Module
liquidate
Liquidates a position by distributing its debt and collateral among other positions in its vault.
Parameters
accountId
(uint128) - The id of the account whose position is to be liquidated.poolId
(uint128) - The id of the pool which holds the position that is to be liquidated.collateralType
(address) - The address of the collateral being used in the position that is to be liquidated.liquidateAsAccountId
(uint128) - Account id that will receive the rewards from the liquidation.
Returns
liquidationData
(struct ILiquidationModule.LiquidationData) - Information about the position that was liquidated.
liquidateVault
Liquidates an entire vault.
Can only be done if the vault itself is under collateralized. LiquidateAsAccountId determines which account to deposit the seized collateral into (this is necessary particularly if the collateral in the vault is vesting). Will only liquidate a portion of the debt for the vault if maxUsd
is supplied.
Parameters
poolId
(uint128) - The id of the pool whose vault is being liquidated.collateralType
(address) - The address of the collateral whose vault is being liquidated.liquidateAsAccountId
(uint128) -maxUsd
(uint256) - The maximum amount of USD that the liquidator is willing to provide for the liquidation, denominated with 18 decimals of precision.
Returns
liquidationData
(struct ILiquidationModule.LiquidationData) - Information about the vault that was liquidated.
isPositionLiquidatable
Determines whether a specified position is liquidatable.
Parameters
accountId
(uint128) - The id of the account whose position is being queried for liquidation.poolId
(uint128) - The id of the pool whose position is being queried for liquidation.collateralType
(address) - The address of the collateral backing up the position being queried for liquidation.
Returns
canLiquidate
(bool) - A boolean with the response to the query.
isVaultLiquidatable
Determines whether a specified vault is liquidatable.
Parameters
poolId
(uint128) - The id of the pool that owns the vault that is being queried for liquidation.collateralType
(address) - The address of the collateral being held at the vault that is being queried for liquidation.
Returns
canVaultLiquidate
(bool) - A boolean with the response to the query.
Liquidation
Emitted when an account is liquidated.
Parameters
accountId
(uint128) - The id of the account that was liquidated.poolId
(uint128) - The pool id of the position that was liquidated.collateralType
(address) - The collateral type used in the position that was liquidated.liquidationData
(struct ILiquidationModule.LiquidationData) - The amount of collateral liquidated, debt liquidated, and collateral awarded to the liquidator.liquidateAsAccountId
(uint128) - Account id that will receive the rewards from the liquidation.sender
(address) - The address of the account that is triggering the liquidation.
VaultLiquidation
Emitted when a vault is liquidated.
Parameters
poolId
(uint128) - The id of the pool whose vault was liquidated.collateralType
(address) - The collateral address of the vault that was liquidated.liquidationData
(struct ILiquidationModule.LiquidationData) - The amount of collateral liquidated, debt liquidated, and collateral awarded to the liquidator.liquidateAsAccountId
(uint128) - Account id that will receive the rewards from the liquidation.sender
(address) - The address of the account that is triggering the liquidation.
Market Collateral Module
depositMarketCollateral
Allows a market to deposit collateral.
Parameters
marketId
(uint128) - The id of the market in which the collateral was directly deposited.collateralType
(address) - The address of the collateral that was deposited in the market.amount
(uint256) - The amount of collateral that was deposited, denominated in the token's native decimal representation.
withdrawMarketCollateral
Allows a market to withdraw collateral that it has previously deposited.
Parameters
marketId
(uint128) - The id of the market from which the collateral was withdrawn.collateralType
(address) - The address of the collateral that was withdrawn from the market.amount
(uint256) - The amount of collateral that was withdrawn, denominated in the token's native decimal representation.
configureMaximumMarketCollateral
Allow the system owner to configure the maximum amount of a given collateral type that a specified market is allowed to deposit.
Parameters
marketId
(uint128) - The id of the market for which the maximum is to be configured.collateralType
(address) - The address of the collateral for which the maximum is to be applied.amount
(uint256) - The amount that is to be set as the new maximum, denominated with 18 decimals of precision.
getMaximumMarketCollateral
Return the total maximum amount of a given collateral type that a specified market is allowed to deposit.
Parameters
marketId
(uint128) - The id of the market for which the maximum is being queried.collateralType
(address) - The address of the collateral for which the maximum is being queried.
Returns
amountD18
(uint256) - The maximum amount of collateral set for the market, denominated with 18 decimals of precision.
getMarketCollateralAmount
Return the total amount of a given collateral type that a specified market has deposited.
Parameters
marketId
(uint128) - The id of the market for which the directly deposited collateral amount is being queried.collateralType
(address) - The address of the collateral for which the amount is being queried.
Returns
amountD18
(uint256) - The total amount of collateral of this type delegated to the market, denominated with 18 decimals of precision.
getMarketCollateralValue
Return the total value of collateral that a specified market has deposited.
Parameters
marketId
(uint128) - The id of the market for which the directly deposited collateral amount is being queried.
Returns
valueD18
(uint256) - The total value of collateral deposited by the market, denominated with 18 decimals of precision.
MarketCollateralDeposited
Emitted when amount
of collateral of type collateralType
is deposited to market marketId
by sender
.
Parameters
marketId
(uint128) - The id of the market in which collateral was deposited.collateralType
(address) - The address of the collateral that was directly deposited in the market.tokenAmount
(uint256) - The amount of tokens that were deposited, denominated in the token's native decimal representation.sender
(address) - The address that triggered the deposit.creditCapacity
(int128) - Updated credit capacity of the market after depositing collateral.netIssuance
(int128) - Updated net issuance.depositedCollateralValue
(uint256) - Updated deposited collateral value of the market.reportedDebt
(uint256) - Updated reported debt of the market after depositing collateral.
MarketCollateralWithdrawn
Emitted when amount
of collateral of type collateralType
is withdrawn from market marketId
by sender
.
Parameters
marketId
(uint128) - The id of the market from which collateral was withdrawn.collateralType
(address) - The address of the collateral that was withdrawn from the market.tokenAmount
(uint256) - The amount of tokens that were withdrawn, denominated in the token's native decimal representation.sender
(address) - The address that triggered the withdrawal.creditCapacity
(int128) - Updated credit capacity of the market after withdrawing.netIssuance
(int128) - Updated net issuance.depositedCollateralValue
(uint256) - Updated deposited collateral value of the market.reportedDebt
(uint256) - Updated reported debt of the market after withdrawing collateral.
MaximumMarketCollateralConfigured
Emitted when the system owner specifies the maximum depositable collateral of a given type in a given market.
Parameters
marketId
(uint128) - The id of the market for which the maximum was configured.collateralType
(address) - The address of the collateral for which the maximum was configured.systemAmount
(uint256) - The amount to which the maximum was set, denominated with 18 decimals of precision.owner
(address) - The owner of the system, which triggered the configuration change.
Market Manager Module
registerMarket
Connects an external market to the system.
Creates a Market object to track the external market, and returns the newly created market id.
Parameters
market
(address) - The address of the external market that is to be registered in the system.
Returns
newMarketId
(uint128) - The id with which the market will be registered in the system.
depositMarketUsd
Allows an external market connected to the system to deposit USD in the system.
The system burns the incoming USD, increases the market's credit capacity, and reduces its issuance. See IMarket
.
Parameters
marketId
(uint128) - The id of the market in which snxUSD will be deposited.target
(address) - The address of the account on who's behalf the deposit will be made.amount
(uint256) - The amount of snxUSD to be deposited, denominated with 18 decimals of precision.
Returns
feeAmount
(uint256) - the amount of fees paid (billed as additional debt towards liquidity providers)
withdrawMarketUsd
Allows an external market connected to the system to withdraw snxUSD from the system.
The system mints the requested snxUSD (provided that the market has sufficient credit), reduces the market's credit capacity, and increases its net issuance. See IMarket
.
Parameters
marketId
(uint128) - The id of the market from which snxUSD will be withdrawn.target
(address) - The address of the account that will receive the withdrawn snxUSD.amount
(uint256) - The amount of snxUSD to be withdraw, denominated with 18 decimals of precision.
Returns
feeAmount
(uint256) - the amount of fees paid (billed as additional debt towards liquidity providers)
getMarketFees
Get the amount of fees paid in USD for a call to depositMarketUsd
and withdrawMarketUsd
for the given market and amount
Parameters
marketId
(uint128) - The market to check fees foramount
(uint256) - The amount deposited or withdrawn in USD
Returns
depositFeeAmount
(uint256) - the amount of USD paid for a call todepositMarketUsd
withdrawFeeAmount
(uint256) - the amount of USD paid for a call towithdrawMarketUsd
getWithdrawableMarketUsd
Returns the total withdrawable snxUSD amount for the specified market.
Parameters
marketId
(uint128) - The id of the market whose withdrawable USD amount is being queried.
Returns
withdrawableD18
(uint256) - The total amount of snxUSD that the market could withdraw at the time of the query, denominated with 18 decimals of precision.
getMarketAddress
Returns the contract address for the specified market.
Parameters
marketId
(uint128) - The id of the market
Returns
marketAddress
(address) - The contract address for the specified market
getMarketNetIssuance
Returns the net issuance of the specified market (snxUSD withdrawn - snxUSD deposited).
Parameters
marketId
(uint128) - The id of the market whose net issuance is being queried.
Returns
issuanceD18
(int128) - The net issuance of the market, denominated with 18 decimals of precision.
getMarketReportedDebt
Returns the reported debt of the specified market.
Parameters
marketId
(uint128) - The id of the market whose reported debt is being queried.
Returns
reportedDebtD18
(uint256) - The market's reported debt, denominated with 18 decimals of precision.
getMarketTotalDebt
Returns the total debt of the specified market.
Parameters
marketId
(uint128) - The id of the market whose debt is being queried.
Returns
totalDebtD18
(int256) - The total debt of the market, denominated with 18 decimals of precision.
getMarketCollateral
Returns the total snxUSD value of the collateral for the specified market.
Parameters
marketId
(uint128) - The id of the market whose collateral is being queried.
Returns
valueD18
(uint256) - The market's total snxUSD value of collateral, denominated with 18 decimals of precision.
getMarketDebtPerShare
Returns the value per share of the debt of the specified market.
This is not a view function, and actually updates the entire debt distribution chain.
Parameters
marketId
(uint128) - The id of the market whose debt per share is being queried.
Returns
debtPerShareD18
(int256) - The market's debt per share value, denominated with 18 decimals of precision.
isMarketCapacityLocked
Returns whether the capacity of the specified market is locked.
Parameters
marketId
(uint128) - The id of the market whose capacity is being queried.
Returns
isLocked
(bool) - A boolean that is true if the market's capacity is locked at the time of the query.
getUsdToken
Returns the USD token associated with this synthetix core system
getOracleManager
Retrieve the systems' configured oracle manager address
distributeDebtToPools
Update a market's current debt registration with the system. This function is provided as an escape hatch for pool griefing, preventing overwhelming the system with a series of very small pools and creating high gas costs to update an account.
Parameters
marketId
(uint128) - the id of the market that needs pools bumpedmaxIter
(uint256) -
Returns
finishedDistributing
(bool) - whether or not all bumpable pools have been bumped and target price has been reached
setMarketMinDelegateTime
allows for a market to set its minimum delegation time. This is useful for preventing stakers from frontrunning rewards or losses by limiting the frequency of delegateCollateral
(or setPoolConfiguration
) calls. By default, there is no minimum delegation time.
Parameters
marketId
(uint128) - the id of the market that wants to set delegation time.minDelegateTime
(uint32) - the minimum number of seconds between delegation calls. Note: this value must be less than the globally defined maximum minDelegateTime
getMarketMinDelegateTime
Retrieve the minimum delegation time of a market
Parameters
marketId
(uint128) - the id of the market
setMinLiquidityRatio
Allows the system owner (not the pool owner) to set a market-specific minimum liquidity ratio.
Parameters
marketId
(uint128) - the id of the marketminLiquidityRatio
(uint256) - The new market-specific minimum liquidity ratio, denominated with 18 decimals of precision. (100% is represented by 1 followed by 18 zeros.)
getMinLiquidityRatio
Retrieves the market-specific minimum liquidity ratio.
Parameters
marketId
(uint128) - the id of the market
Returns
minRatioD18
(uint256) - The current market-specific minimum liquidity ratio, denominated with 18 decimals of precision. (100% is represented by 1 followed by 18 zeros.)
getMarketPools
getMarketPoolDebtDistribution
MarketRegistered
Emitted when a new market is registered in the system.
Parameters
market
(address) - The address of the external market that was registered in the system.marketId
(uint128) - The id with which the market was registered in the system.sender
(address) - The account that trigger the registration of the market.
MarketUsdDeposited
Emitted when a market deposits snxUSD in the system.
Parameters
marketId
(uint128) - The id of the market that deposited snxUSD in the system.target
(address) - The address of the account that provided the snxUSD in the deposit.amount
(uint256) - The amount of snxUSD deposited in the system, denominated with 18 decimals of precision.market
(address) - The address of the external market that is depositing.creditCapacity
(int128) - Updated credit capacity of the market after depositing.netIssuance
(int128) - Updated net issuance.depositedCollateralValue
(uint256) - Updated deposited collateral value of the market.
MarketUsdWithdrawn
Emitted when a market withdraws snxUSD from the system.
Parameters
marketId
(uint128) - The id of the market that withdrew snxUSD from the system.target
(address) - The address of the account that received the snxUSD in the withdrawal.amount
(uint256) - The amount of snxUSD withdrawn from the system, denominated with 18 decimals of precision.market
(address) - The address of the external market that is withdrawing.creditCapacity
(int128) - Updated credit capacity of the market after withdrawing.netIssuance
(int128) - Updated net issuance.depositedCollateralValue
(uint256) - Updated deposited collateral value of the market
MarketSystemFeePaid
SetMinDelegateTime
Emitted when a market sets an updated minimum delegation time
Parameters
marketId
(uint128) - The id of the market that the setting is applied tominDelegateTime
(uint32) - The minimum amount of time between delegation changes
SetMarketMinLiquidityRatio
Emitted when a market-specific minimum liquidity ratio is set
Parameters
marketId
(uint128) - The id of the market that the setting is applied tominLiquidityRatio
(uint256) - The new market-specific minimum liquidity ratio
Pool Configuration Module
setPreferredPool
Sets the unique system preferred pool.
Note: The preferred pool does not receive any special treatment. It is only signaled as preferred here.
Parameters
poolId
(uint128) - The id of the pool that is to be set as preferred.
addApprovedPool
Marks a pool as approved by the system owner.
Approved pools do not receive any special treatment. They are only signaled as approved here.
Parameters
poolId
(uint128) - The id of the pool that is to be approved.
removeApprovedPool
Un-marks a pool as preferred by the system owner.
Parameters
poolId
(uint128) - The id of the pool that is to be no longer approved.
getPreferredPool
Retrieves the unique system preferred pool.
Returns
poolId
(uint128) - The id of the pool that is currently set as preferred in the system.
getApprovedPools
Retrieves the pool that are approved by the system owner.
Returns
poolIds
(uint256[]) - An array with all of the pool ids that are approved in the system.
PreferredPoolSet
Emitted when the system owner sets the preferred pool.
Parameters
poolId
(uint256) - The id of the pool that was set as preferred.
PoolApprovedAdded
Emitted when the system owner adds an approved pool.
Parameters
poolId
(uint256) - The id of the pool that was approved.
PoolApprovedRemoved
Emitted when the system owner removes an approved pool.
Parameters
poolId
(uint256) - The id of the pool that is no longer approved.
Pool Module
createPool
Creates a pool with the requested pool id.
Parameters
requestedPoolId
(uint128) - The requested id for the new pool. Reverts if the id is not available.owner
(address) - The address that will own the newly created pool.
setPoolConfiguration
Allows the pool owner to configure the pool.
The pool's configuration is composed of an array of MarketConfiguration objects, which describe which markets the pool provides liquidity to, in what proportion, and to what extent. Incoming market ids need to be provided in ascending order.
Parameters
poolId
(uint128) - The id of the pool whose configuration is being set.marketDistribution
(struct MarketConfiguration.Data[]) - The array of market configuration objects that define the list of markets that are connected to the system.
setPoolCollateralConfiguration
Allows the pool owner to set the configuration of a specific collateral type for their pool.
Parameters
poolId
(uint128) - The id of the pool whose configuration is being set.collateralType
(address) - The collatenewConfig
(struct PoolCollateralConfiguration.Data) - The config to set
getPoolCollateralConfiguration
Retrieves the pool configuration of a specific collateral type.
Parameters
poolId
(uint128) - The id of the pool whose configuration is being returned.collateralType
(address) - The address of the collateral.
Returns
config
(struct PoolCollateralConfiguration.Data) - The PoolCollateralConfiguration object that describes the requested collateral configuration of the pool.
setPoolCollateralDisabledByDefault
Allows collaterals accepeted by the system to be accepeted by the pool by default
Parameters
poolId
(uint128) - The id of the pool.disabled
(bool) - If set to true new collaterals will be disabled for the pool.
getPoolConfiguration
Retrieves the MarketConfiguration of the specified pool.
Parameters
poolId
(uint128) - The id of the pool whose configuration is being queried.
Returns
markets
(struct MarketConfiguration.Data[]) - The array of MarketConfiguration objects that describe the pool's configuration.
setPoolName
Allows the owner of the pool to set the pool's name.
Parameters
poolId
(uint128) - The id of the pool whose name is being set.name
(string) - The new name to give to the pool.
getPoolName
Returns the pool's name.
Parameters
poolId
(uint128) - The id of the pool whose name is being queried.
Returns
poolName
(string) - The current name of the pool.
nominatePoolOwner
Allows the current pool owner to nominate a new owner.
Parameters
nominatedOwner
(address) - The address to nominate os the new pool owner.poolId
(uint128) - The id whose ownership is being transferred.
acceptPoolOwnership
After a new pool owner has been nominated, allows it to accept the nomination and thus ownership of the pool.
Parameters
poolId
(uint128) - The id of the pool for which the caller is to accept ownership.
revokePoolNomination
After a new pool owner has been nominated, allows it to reject the nomination.
Parameters
poolId
(uint128) - The id of the pool for which the new owner nomination is to be revoked.
renouncePoolNomination
Allows the current nominated owner to renounce the nomination.
Parameters
poolId
(uint128) - The id of the pool for which the caller is renouncing ownership nomination.
renouncePoolOwnership
Allows the current owner to renounce his ownership.
Parameters
poolId
(uint128) - The id of the pool for which the caller is renouncing ownership nomination.
getPoolOwner
Returns the current pool owner.
Parameters
poolId
(uint128) - The id of the pool whose ownership is being queried.
Returns
owner
(address) - The current owner of the pool.
getNominatedPoolOwner
Returns the current nominated pool owner.
Parameters
poolId
(uint128) - The id of the pool whose nominated owner is being queried.
Returns
nominatedOwner
(address) - The current nominated owner of the pool.
setMinLiquidityRatio
Allows the system owner (not the pool owner) to set the system-wide minimum liquidity ratio.
Parameters
minLiquidityRatio
(uint256) - The new system-wide minimum liquidity ratio, denominated with 18 decimals of precision. (100% is represented by 1 followed by 18 zeros.)
getPoolCollateralIssuanceRatio
returns a pool minimum issuance ratio
Parameters
poolId
(uint128) - The id of the pool for to check the collateral for.collateral
(address) - The address of the collateral.
getMinLiquidityRatio
Retrieves the system-wide minimum liquidity ratio.
Returns
minRatioD18
(uint256) - The current system-wide minimum liquidity ratio, denominated with 18 decimals of precision. (100% is represented by 1 followed by 18 zeros.)
rebalancePool
Distributes cached debt in a pool to its vaults and updates market credit capacities.
Parameters
poolId
(uint128) - the pool to rebalanceoptionalCollateralType
(address) - in addition to rebalancing the pool, calculate updated collaterals and debts for the specified vault
PoolCreated
Gets fired when pool will be created.
Parameters
poolId
(uint128) - The id of the newly created pool.owner
(address) - The owner of the newly created pool.sender
(address) - The address that triggered the creation of the pool.
PoolOwnerNominated
Gets fired when pool owner proposes a new owner.
Parameters
poolId
(uint128) - The id of the pool for which the nomination ocurred.nominatedOwner
(address) - The address that was nominated as the new owner of the pool.owner
(address) - The address of the current owner of the pool.
PoolOwnershipAccepted
Gets fired when pool nominee accepts nomination.
Parameters
poolId
(uint128) - The id of the pool for which the owner nomination was accepted.owner
(address) - The address of the new owner of the pool, which accepted the nomination.
PoolNominationRevoked
Gets fired when pool owner revokes nomination.
Parameters
poolId
(uint128) - The id of the pool in which the nomination was revoked.owner
(address) - The current owner of the pool.
PoolNominationRenounced
Gets fired when pool nominee renounces nomination.
Parameters
poolId
(uint128) - The id of the pool for which the owner nomination was renounced.owner
(address) - The current owner of the pool.
PoolOwnershipRenounced
Gets fired when pool owner renounces his own ownership.
Parameters
poolId
(uint128) - The id of the pool for which the owner nomination was renounced.owner
(address) -
PoolNameUpdated
Gets fired when pool name changes.
Parameters
poolId
(uint128) - The id of the pool whose name was updated.name
(string) - The new name of the pool.sender
(address) - The address that triggered the rename of the pool.
PoolConfigurationSet
Gets fired when pool gets configured.
Parameters
poolId
(uint128) - The id of the pool whose configuration was set.markets
(struct MarketConfiguration.Data[]) - Array of configuration data of the markets that were connected to the pool.sender
(address) - The address that triggered the pool configuration.
PoolCollateralConfigurationUpdated
SetMinLiquidityRatio
Emitted when a system-wide minimum liquidity ratio is set
Parameters
minLiquidityRatio
(uint256) - The new system-wide minimum liquidity ratio
PoolCollateralDisabledByDefaultSet
Allows collaterals accepeted by the system to be accepeted by the pool by default
Parameters
poolId
(uint128) - The id of the pool.disabled
(bool) - Shows if new collateral's will be dsiabled by default for the pool
Rewards Manager Module
registerRewardsDistributor
Called by pool owner to register rewards for vault participants.
Parameters
poolId
(uint128) - The id of the pool whose rewards are to be managed by the specified distributor.collateralType
(address) - The address of the collateral used in the pool's rewards.distributor
(address) - The address of the reward distributor to be registered.
removeRewardsDistributor
Called by pool owner to remove a registered rewards distributor for vault participants. WARNING: if you remove a rewards distributor, the same address can never be re-registered again. If you simply want to turn off rewards, call distributeRewards
with 0 emission. If you need to completely reset the rewards distributor again, create a new rewards distributor at a new address and register the new one. This function is provided since the number of rewards distributors added to an account is finite, so you can remove an unused rewards distributor if need be. NOTE: unclaimed rewards can still be claimed after a rewards distributor is removed (though any rewards-over-time will be halted)
Parameters
poolId
(uint128) - The id of the pool whose rewards are to be managed by the specified distributor.collateralType
(address) - The address of the collateral used in the pool's rewards.distributor
(address) - The address of the reward distributor to be registered.
distributeRewards
Called by a registered distributor to set up rewards for vault participants.
Will revert if the caller is not a registered distributor.
Parameters
poolId
(uint128) - The id of the pool to distribute rewards to.collateralType
(address) - The address of the collateral used in the pool's rewards.amount
(uint256) - The amount of rewards to be distributed.start
(uint64) - The date at which the rewards will begin to be claimable.duration
(uint32) - The period after which all distributed rewards will be claimable.
claimRewards
Allows a user with appropriate permissions to claim rewards associated with a position.
Parameters
accountId
(uint128) - The id of the account that is to claim the rewards.poolId
(uint128) - The id of the pool to claim rewards on.collateralType
(address) - The address of the collateral used in the pool's rewards.distributor
(address) - The address of the rewards distributor associated with the rewards being claimed.
Returns
amountClaimedD18
(uint256) - The amount of rewards that were available for the account and thus claimed.
updateRewards
For a given position, return the rewards that can currently be claimed.
Parameters
poolId
(uint128) - The id of the pool being queried.collateralType
(address) - The address of the collateral used in the pool's rewards.accountId
(uint128) - The id of the account whose available rewards are being queried.
Returns
claimableD18
(uint256[]) - An array of ids of the reward entries that are claimable by the position.distributors
(address[]) - An array with the addresses of the reward distributors associated with the claimable rewards.
getRewardRate
Returns the number of individual units of amount emitted per second per share for the given poolId, collateralType, distributor vault.
Parameters
poolId
(uint128) - The id of the pool being queried.collateralType
(address) - The address of the collateral used in the pool's rewards.distributor
(address) - The address of the rewards distributor associated with the rewards in question.
Returns
rateD18
(uint256) - The queried rewards rate.
getAvailableRewards
Returns the amount of claimable rewards for a given accountId for a vault distributor.
Parameters
accountId
(uint128) - The id of the account to look up rewards on.poolId
(uint128) - The id of the pool to claim rewards on.collateralType
(address) - The address of the collateral used in the pool's rewards.distributor
(address) - The address of the rewards distributor associated with the rewards being claimed.
Returns
rewardAmount
(uint256) - The amount of available rewards that are available for the provided account.
RewardsDistributed
Emitted when the pool owner or an existing reward distributor sets up rewards for vault participants.
Parameters
poolId
(uint128) - The id of the pool on which rewards were distributed.collateralType
(address) - The collateral type of the pool on which rewards were distributed.distributor
(address) - The reward distributor associated to the rewards that were distributed.amount
(uint256) - The amount of rewards that were distributed.start
(uint256) - The date one which the rewards will begin to be claimable.duration
(uint256) - The time in which all of the distributed rewards will be claimable.
RewardsClaimed
Emitted when a vault participant claims rewards.
Parameters
accountId
(uint128) - The id of the account that claimed the rewards.poolId
(uint128) - The id of the pool where the rewards were claimed.collateralType
(address) - The address of the collateral used in the pool's rewards.distributor
(address) - The address of the rewards distributor associated with these rewards.amount
(uint256) - The amount of rewards that were claimed.
RewardsDistributorRegistered
Emitted when a new rewards distributor is registered.
Parameters
poolId
(uint128) - The id of the pool whose reward distributor was registered.collateralType
(address) - The address of the collateral used in the pool's rewards.distributor
(address) - The address of the newly registered reward distributor.
RewardsDistributorRemoved
Emitted when an already registered rewards distributor is removed.
Parameters
poolId
(uint128) - The id of the pool whose reward distributor was registered.collateralType
(address) - The address of the collateral used in the pool's rewards.distributor
(address) - The address of the registered reward distributor.
USD Token Module
burnWithAllowance
Allows the core system to burn snxUSD held by the from
address, provided that it has given allowance to spender
.
Parameters
from
(address) - The address that holds the snxUSD to be burned.spender
(address) - The address to which the holder has given allowance to.amount
(uint256) - The amount of snxUSD to be burned, denominated with 18 decimals of precision.
burn
Destroys amount
of snxUSD tokens from the caller. This is derived from ERC20Burnable.sol and is currently included for testing purposes with CCIP token pools.
Parameters
amount
(uint256) - The amount of snxUSD to be burned, denominated with 18 decimals of precision.
isInitialized
Returns wether the token has been initialized.
Returns
[0]
(bool) - A boolean with the result of the query.
initialize
Initializes the token with name, symbol, and decimals.
mint
Allows the owner to mint tokens.
Parameters
to
(address) - The address to receive the newly minted tokens.amount
(uint256) - The amount of tokens to mint.
burn
Allows the owner to burn tokens.
Parameters
from
(address) - The address whose tokens will be burnt.amount
(uint256) - The amount of tokens to burn.
setAllowance
Allows an address that holds tokens to provide allowance to another.
Parameters
from
(address) - The address that is providing allowance.spender
(address) - The address that is given allowance.amount
(uint256) - The amount of allowance being given.
name
Retrieves the name of the token, e.g. "Synthetix Network Token".
Returns
[0]
(string) - A string with the name of the token.
symbol
Retrieves the symbol of the token, e.g. "SNX".
Returns
[0]
(string) - A string with the symbol of the token.
decimals
Retrieves the number of decimals used by the token. The default is 18.
Returns
[0]
(uint8) - The number of decimals.
totalSupply
Returns the total number of tokens in circulation (minted - burnt).
Returns
[0]
(uint256) - The total number of tokens.
balanceOf
Returns the balance of a user.
Parameters
owner
(address) - The address whose balance is being retrieved.
Returns
[0]
(uint256) - The number of tokens owned by the user.
allowance
Returns how many tokens a user has allowed another user to transfer on its behalf.
Parameters
owner
(address) - The user who has given the allowance.spender
(address) - The user who was given the allowance.
Returns
[0]
(uint256) - The amount of tokensspender
can transfer onowner
's behalf.
transfer
Transfer tokens from one address to another.
Parameters
to
(address) - The address that will receive the tokens.amount
(uint256) - The amount of tokens to be transferred.
Returns
[0]
(bool) - A boolean which is true if the operation succeeded.
approve
Allows users to provide allowance to other users so that they can transfer tokens on their behalf.
Parameters
spender
(address) - The address that is receiving the allowance.amount
(uint256) - The amount of tokens that are being added to the allowance.
Returns
[0]
(bool) - A boolean which is true if the operation succeeded.
increaseAllowance
Atomically increases the allowance granted to spender
by the caller.
This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.
Emits an {Approval} event indicating the updated allowance.
Requirements:
spender
cannot be the zero address.
decreaseAllowance
Atomically decreases the allowance granted to spender
by the caller.
This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.
Emits an {Approval} event indicating the updated allowance.
Requirements:
spender
cannot be the zero address.spender
must have allowance for the caller of at leastsubtractedValue
.
transferFrom
Allows a user who has been given allowance to transfer tokens on another user's behalf.
Parameters
from
(address) - The address that owns the tokens that are being transferred.to
(address) - The address that will receive the tokens.amount
(uint256) - The number of tokens to transfer.
Returns
[0]
(bool) - A boolean which is true if the operation succeeded.
Transfer
Emitted when tokens have been transferred.
Parameters
from
(address) - The address that originally owned the tokens.to
(address) - The address that received the tokens.amount
(uint256) - The number of tokens that were transferred.
Approval
Emitted when a user has provided allowance to another user for transferring tokens on its behalf.
Parameters
owner
(address) - The address that is providing the allowance.spender
(address) - The address that received the allowance.amount
(uint256) - The number of tokens that were added tospender
's allowance.
Vault Module
delegateCollateral
Updates an account's delegated collateral amount for the specified pool and collateral type pair.
Parameters
accountId
(uint128) - The id of the account associated with the position that will be updated.poolId
(uint128) - The id of the pool associated with the position.collateralType
(address) - The address of the collateral used in the position.amount
(uint256) - The new amount of collateral delegated in the position, denominated with 18 decimals of precision.leverage
(uint256) - The new leverage amount used in the position, denominated with 18 decimals of precision. Requirements: -ERC2771Context._msgSender()
must be the owner of the account, have theADMIN
permission, or have theDELEGATE
permission. - If increasing the amount delegated, it must not exceed the available collateral (getAccountAvailableCollateral
) associated with the account. - If decreasing the amount delegated, the liquidity position must have a collateralization ratio greater than the target collateralization ratio for the corresponding collateral type. Emits a {DelegationUpdated} event.
getPositionCollateralRatio
Returns the collateralization ratio of the specified liquidity position. If debt is negative, this function will return 0.
Call this function using callStatic
to treat it as a view function. The return value is a percentage with 18 decimals places.
Parameters
accountId
(uint128) - The id of the account whose collateralization ratio is being queried.poolId
(uint128) - The id of the pool in which the account's position is held.collateralType
(address) - The address of the collateral used in the queried position.
Returns
ratioD18
(uint256) - The collateralization ratio of the position (collateral / debt), denominated with 18 decimals of precision.
getPositionDebt
Returns the debt of the specified liquidity position. Credit is expressed as negative debt.
This is not a view function, and actually updates the entire debt distribution chain. Call this function using callStatic
to treat it as a view function.
Parameters
accountId
(uint128) - The id of the account being queried.poolId
(uint128) - The id of the pool in which the account's position is held.collateralType
(address) - The address of the collateral used in the queried position.
Returns
debtD18
(int256) - The amount of debt held by the position, denominated with 18 decimals of precision.
getPositionCollateral
Returns the amount of the collateral associated with the specified liquidity position.
Call this function using callStatic
to treat it as a view function. collateralAmount is represented as an integer with 18 decimals.
Parameters
accountId
(uint128) - The id of the account being queried.poolId
(uint128) - The id of the pool in which the account's position is held.collateralType
(address) - The address of the collateral used in the queried position.
Returns
collateralAmountD18
(uint256) - The amount of collateral used in the position, denominated with 18 decimals of precision.
getPosition
Returns all information pertaining to a specified liquidity position in the vault module.
Parameters
accountId
(uint128) - The id of the account being queried.poolId
(uint128) - The id of the pool in which the account's position is held.collateralType
(address) - The address of the collateral used in the queried position.
Returns
collateralAmountD18
(uint256) - The amount of collateral used in the position, denominated with 18 decimals of precision.collateralValueD18
(uint256) - The value of the collateral used in the position, denominated with 18 decimals of precision.debtD18
(int256) - The amount of debt held in the position, denominated with 18 decimals of precision.collateralizationRatioD18
(uint256) - The collateralization ratio of the position (collateral / debt), denominated with 18 decimals of precision.
getVaultDebt
Returns the total debt (or credit) that the vault is responsible for. Credit is expressed as negative debt.
This is not a view function, and actually updates the entire debt distribution chain. Call this function using callStatic
to treat it as a view function.
Parameters
poolId
(uint128) - The id of the pool that owns the vault whose debt is being queried.collateralType
(address) - The address of the collateral of the associated vault.
Returns
debtD18
(int256) - The overall debt of the vault, denominated with 18 decimals of precision.
getVaultCollateral
Returns the amount and value of the collateral held by the vault.
Call this function using callStatic
to treat it as a view function. collateralAmount is represented as an integer with 18 decimals. collateralValue is represented as an integer with the number of decimals specified by the collateralType.
Parameters
poolId
(uint128) - The id of the pool that owns the vault whose collateral is being queried.collateralType
(address) - The address of the collateral of the associated vault.
Returns
collateralAmountD18
(uint256) - The collateral amount of the vault, denominated with 18 decimals of precision.collateralValueD18
(uint256) - The collateral value of the vault, denominated with 18 decimals of precision.
getVaultCollateralRatio
Returns the collateralization ratio of the vault. If debt is negative, this function will return 0.
Call this function using callStatic
to treat it as a view function. The return value is a percentage with 18 decimals places.
Parameters
poolId
(uint128) - The id of the pool that owns the vault whose collateralization ratio is being queried.collateralType
(address) - The address of the collateral of the associated vault.
Returns
ratioD18
(uint256) - The collateralization ratio of the vault, denominated with 18 decimals of precision.
DelegationUpdated
Emitted when {sender} updates the delegation of collateral in the specified liquidity position.
Parameters
accountId
(uint128) - The id of the account whose position was updated.poolId
(uint128) - The id of the pool in which the position was updated.collateralType
(address) - The address of the collateral associated to the position.amount
(uint256) - The new amount of the position, denominated with 18 decimals of precision.leverage
(uint256) - The new leverage value of the position, denominated with 18 decimals of precision.sender
(address) - The address that triggered the update of the position.
Spot Market
Async Order Configuration Module
addSettlementStrategy
Adds new settlement strategy to the specified market id.
Parameters
synthMarketId
(uint128) - Id of the market to associate the strategy with.strategy
(struct SettlementStrategy.Data) - Settlement strategy data. see SettlementStrategy.Data struct.
Returns
strategyId
(uint256) - newly created settlement strategy id.
setSettlementStrategyEnabled
Sets the strategy to enabled or disabled.
when disabled, the strategy will be invalid for committing of new async orders.
Parameters
synthMarketId
(uint128) - Id of the market associated with the strategy.strategyId
(uint256) - id of the strategy.enabled
(bool) - set enabled/disabled.
setSettlementStrategy
updates the strategy with the new strategy passed in.
THIS WILL OVERRIDE ANY SETTINGS FOR EXISTING ORDERS
Parameters
synthMarketId
(uint128) - Id of the market associated with the strategy.strategyId
(uint256) - id of the strategy.strategy
(struct SettlementStrategy.Data) - new strategy config
getSettlementStrategy
Returns the settlement strategy data for given market/strategy id.
Parameters
marketId
(uint128) - Id of the market associated with the strategy.strategyId
(uint256) - id of the strategy.
Returns
settlementStrategy
(struct SettlementStrategy.Data) -
SettlementStrategyAdded
Gets fired when new settlement strategy is added.
Parameters
synthMarketId
(uint128) - adds settlement strategy to this specific market.strategyId
(uint256) - the newly created settlement strategy id.
SettlementStrategySet
Gets fired when settlement strategy is enabled/disabled.
currently only enabled/disabled flag can be updated.
Parameters
synthMarketId
(uint128) - adds settlement strategy to this specific market.strategyId
(uint256) - id of the strategy.strategy
(struct SettlementStrategy.Data) - updated strategy
Async Order Module
commitOrder
Commit an async order via this function
commitment transfers the amountProvided into the contract and escrows the funds until settlement.
Parameters
marketId
(uint128) - Id of the market used for the trade.orderType
(enum Transaction.Type) - Should send either 2 or 3 which correlates to the transaction type enum defined in Transaction.Type.amountProvided
(uint256) - amount of value provided by the user for trade. Should have enough allowance.settlementStrategyId
(uint256) - id of the settlement strategy used for trade.minimumSettlementAmount
(uint256) - minimum amount of value returned to trader after fees.referrer
(address) - Optional address of the referrer, for fee share
Returns
asyncOrderClaim
(struct AsyncOrderClaim.Data) - claim details (see AsyncOrderClaim.Data struct).
cancelOrder
Cancel an async order via this function
cancellation transfers the amountProvided back to the trader without any fee collection cancellation can only happen after the settlement time has passed needs to satisfy commitmentTime + settlementDelay + settlementDuration < block.timestamp
Parameters
marketId
(uint128) - Id of the market used for the trade.asyncOrderId
(uint128) - id of the async order created during commitment.
getAsyncOrderClaim
Get async order claim details
Parameters
marketId
(uint128) - Id of the market used for the trade.asyncOrderId
(uint128) - id of the async order created during commitment.
Returns
asyncOrderClaim
(struct AsyncOrderClaim.Data) - claim details (see AsyncOrderClaim.Data struct).
OrderCommitted
Gets fired when a new order is committed.
Parameters
marketId
(uint128) - Id of the market used for the trade.orderType
(enum Transaction.Type) - Should send either 2 or 3 which correlates to the transaction type enum defined in Transaction.Type.amountProvided
(uint256) - amount of value provided by the user for trade.asyncOrderId
(uint128) - id of the async order created (used for settlements).sender
(address) - trader address.referrer
(address) - Optional address of the referrer, for fee share
OrderCancelled
Gets fired when an order is cancelled.
Parameters
marketId
(uint128) - Id of the market used for the trade.asyncOrderId
(uint128) - id of the async order.asyncOrderClaim
(struct AsyncOrderClaim.Data) - claim details (see AsyncOrderClaim.Data struct).sender
(address) - trader address and also the receiver of the funds.
Async Order Settlement Module
settleOrder
Settle already created async order via this function
if the strategy is onchain, the settlement is done similar to an atomic buy except with settlement time if the strategy is offchain, this function will revert with OffchainLookup error and the client should perform offchain lookup and call the callback specified see: EIP-3668
Parameters
marketId
(uint128) - Id of the market used for the trade.asyncOrderId
(uint128) - id of the async order created during commitment.
Returns
finalOrderAmount
(uint256) - amount returned to trader after fees.[1]
(struct OrderFees.Data) - OrderFees.Data breakdown of all the fees incurred for the transaction.
OrderSettled
Gets fired when an order is settled.
Parameters
marketId
(uint128) - Id of the market used for the trade.asyncOrderId
(uint128) - id of the async order.finalOrderAmount
(uint256) - amount returned to trader after fees.fees
(struct OrderFees.Data) - breakdown of all the fees incurred for the transaction.collectedFees
(uint256) - fees collected by the configured fee collector.settler
(address) - address that settled the order.price
(uint256) -orderType
(enum Transaction.Type) -
Atomic Order Module
buyExactIn
Initiates a buy trade returning synth for the specified amountUsd.
Transfers the specified amountUsd, collects fees through configured fee collector, returns synth to the trader. Leftover fees not collected get deposited into the market manager to improve market PnL. Uses the buyFeedId configured for the market.
Parameters
synthMarketId
(uint128) - Id of the market used for the trade.amountUsd
(uint256) - Amount of snxUSD trader is providing allowance for the trade.minAmountReceived
(uint256) - Min Amount of synth is expected the trader to receive otherwise the transaction will revert.referrer
(address) - Optional address of the referrer, for fee share
Returns
synthAmount
(uint256) - Synth received on the trade based on amount provided by trader.fees
(struct OrderFees.Data) - breakdown of all the fees incurred for the transaction.
buy
alias for buyExactIn
Parameters
marketId
(uint128) - (see buyExactIn)usdAmount
(uint256) - (see buyExactIn)minAmountReceived
(uint256) - (see buyExactIn)referrer
(address) - (see buyExactIn)
Returns
synthAmount
(uint256) - (see buyExactIn)fees
(struct OrderFees.Data) - (see buyExactIn)
buyExactOut
user provides the synth amount they'd like to buy, and the function charges the USD amount which includes fees
the inverse of buyExactIn
Parameters
synthMarketId
(uint128) - market id valuesynthAmount
(uint256) - the amount of synth the trader wants to buymaxUsdAmount
(uint256) - max amount the trader is willing to pay for the specified synthreferrer
(address) - optional address of the referrer, for fee share
Returns
usdAmountCharged
(uint256) - amount of USD charged for the tradefees
(struct OrderFees.Data) - breakdown of all the fees incurred for the transaction
quoteBuyExactIn
quote for buyExactIn. same parameters and return values as buyExactIn
Parameters
synthMarketId
(uint128) - market id valueusdAmount
(uint256) - amount of USD to use for the tradestalenessTolerance
(enum Price.Tolerance) - this enum determines what staleness tolerance to use
Returns
synthAmount
(uint256) - return amount of synth given the USD amount - feesfees
(struct OrderFees.Data) - breakdown of all the quoted fees for the buy txn
quoteBuyExactOut
quote for buyExactOut. same parameters and return values as buyExactOut
Parameters
synthMarketId
(uint128) - market id valuesynthAmount
(uint256) - amount of synth requestedstalenessTolerance
(enum Price.Tolerance) - this enum determines what staleness tolerance to use
Returns
usdAmountCharged
(uint256) - USD amount charged for the synth requested - fees[1]
(struct OrderFees.Data) - fees breakdown of all the quoted fees for the buy txn
sellExactIn
Initiates a sell trade returning snxUSD for the specified amount of synth (sellAmount)
Transfers the specified synth, collects fees through configured fee collector, returns snxUSD to the trader. Leftover fees not collected get deposited into the market manager to improve market PnL.
Parameters
synthMarketId
(uint128) - Id of the market used for the trade.sellAmount
(uint256) - Amount of synth provided by trader for trade into snxUSD.minAmountReceived
(uint256) - Min Amount of snxUSD trader expects to receive for the tradereferrer
(address) - Optional address of the referrer, for fee share
Returns
returnAmount
(uint256) - Amount of snxUSD returned to userfees
(struct OrderFees.Data) - breakdown of all the fees incurred for the transaction.
sellExactOut
initiates a trade where trader specifies USD amount they'd like to receive
the inverse of sellExactIn
Parameters
marketId
(uint128) - synth market idusdAmount
(uint256) - amount of USD trader wants to receivemaxSynthAmount
(uint256) - max amount of synth trader is willing to use to receive the specified USD amountreferrer
(address) - optional address of the referrer, for fee share
Returns
synthToBurn
(uint256) - amount of synth charged for the specified usd amountfees
(struct OrderFees.Data) - breakdown of all the fees incurred for the transaction
sell
alias for sellExactIn
Parameters
marketId
(uint128) - (see sellExactIn)synthAmount
(uint256) - (see sellExactIn)minUsdAmount
(uint256) - (see sellExactIn)referrer
(address) - (see sellExactIn)
Returns
usdAmountReceived
(uint256) - (see sellExactIn)fees
(struct OrderFees.Data) - (see sellExactIn)
quoteSellExactIn
quote for sellExactIn
returns expected USD amount trader would receive for the specified synth amount
Parameters
marketId
(uint128) - synth market idsynthAmount
(uint256) - synth amount trader is providing for the tradestalenessTolerance
(enum Price.Tolerance) - this enum determines what staleness tolerance to use
Returns
returnAmount
(uint256) - amount of USD expected backfees
(struct OrderFees.Data) - breakdown of all the quoted fees for the txn
quoteSellExactOut
quote for sellExactOut
returns expected synth amount expected from trader for the requested USD amount
Parameters
marketId
(uint128) - synth market idusdAmount
(uint256) - USD amount trader wants to receivestalenessTolerance
(enum Price.Tolerance) - this enum determines what staleness tolerance to use
Returns
synthToBurn
(uint256) - amount of synth expected from traderfees
(struct OrderFees.Data) - breakdown of all the quoted fees for the txn
getMarketSkew
gets the current market skew
Parameters
marketId
(uint128) - synth market id
Returns
marketSkew
(int256) - the skew
SynthBought
Gets fired when buy trade is complete
Parameters
synthMarketId
(uint256) - Id of the market used for the trade.synthReturned
(uint256) - Synth received on the trade based on amount provided by trader.fees
(struct OrderFees.Data) - breakdown of all fees incurred for transaction.collectedFees
(uint256) - Fees collected by the configured FeeCollector for the market (rest of the fees are deposited to market manager).referrer
(address) - Optional address of the referrer, for fee shareprice
(uint256) -
SynthSold
Gets fired when sell trade is complete
Parameters
synthMarketId
(uint256) - Id of the market used for the trade.amountReturned
(uint256) - Amount of snxUSD returned to user based on synth provided by trader.fees
(struct OrderFees.Data) - breakdown of all fees incurred for transaction.collectedFees
(uint256) - Fees collected by the configured FeeCollector for the market (rest of the fees are deposited to market manager).referrer
(address) - Optional address of the referrer, for fee shareprice
(uint256) -
Market Configuration Module
getMarketFees
gets the atomic fixed fee for a given market
Parameters
synthMarketId
(uint128) - Id of the market the fee applies to.
Returns
atomicFixedFee
(uint256) - fixed fee amount represented in bips with 18 decimals.asyncFixedFee
(uint256) - fixed fee amount represented in bips with 18 decimals.wrapFee
(int256) - wrapping fee in %, 18 decimals. Can be negative.unwrapFee
(int256) - unwrapping fee in %, 18 decimals. Can be negative.
setAtomicFixedFee
sets the atomic fixed fee for a given market
only marketOwner can set the fee
Parameters
synthMarketId
(uint128) - Id of the market the fee applies to.atomicFixedFee
(uint256) - fixed fee amount represented in bips with 18 decimals.
setAsyncFixedFee
sets the async fixed fee for a given market
only marketOwner can set the fee
Parameters
synthMarketId
(uint128) - Id of the market the fee applies to.asyncFixedFee
(uint256) - fixed fee amount represented in bips with 18 decimals.
setMarketSkewScale
sets the skew scale for a given market
only marketOwner can set the skew scale
Parameters
synthMarketId
(uint128) - Id of the market the skew scale applies to.skewScale
(uint256) - max amount of synth which makes the skew 100%. the fee is derived as a % of the max value. 100% premium means outstanding synth == skewScale.
getMarketSkewScale
gets the skew scale for a given market
Parameters
synthMarketId
(uint128) - Id of the market the skew scale applies to.
Returns
skewScale
(uint256) - max amount of synth which makes the skew 100%. the fee is derived as a % of the max value. 100% premium means outstanding synth == skewScale.
setMarketUtilizationFees
sets the market utilization fee for a given market
only marketOwner can set the fee 100% utilization means the fee is 0. 120% utilization means the fee is 20% * this fee rate (in bips).
Parameters
synthMarketId
(uint128) - Id of the market the utilization fee applies to.utilizationFeeRate
(uint256) - the rate is represented in bips with 18 decimals and is the rate at which fee increases based on the % above 100% utilization of the delegated collateral for the market.
getMarketUtilizationFees
gets the market utilization fee for a given market
100% utilization means the fee is 0. 120% utilization means the fee is 20% * this fee rate (in bips).
Parameters
synthMarketId
(uint128) - Id of the market the utilization fee applies to.
Returns
utilizationFeeRate
(uint256) - the rate is represented in bips with 18 decimals and is the rate at which fee increases based on the % above 100% utilization of the delegated collateral for the market.
setCollateralLeverage
sets the collateral leverage for a given market
only marketOwner can set the leverage this leverage value is a value applied to delegated collateral which is compared to outstanding synth to determine utilization of market, and locked amounts
Parameters
synthMarketId
(uint128) - Id of the market the collateral leverage applies to.collateralLeverage
(uint256) - the leverage is represented as % with 18 decimals. 1 = 1x leverage
getCollateralLeverage
gets the collateral leverage for a given market
this leverage value is a value applied to delegated collateral which is compared to outstanding synth to determine utilization of market, and locked amounts
Parameters
synthMarketId
(uint128) - Id of the market the collateral leverage applies to.
Returns
collateralLeverage
(uint256) - the leverage is represented as % with 18 decimals. 1 = 1x leverage
setCustomTransactorFees
sets the fixed fee for a given market and transactor
overrides both the atomic and async fixed fees only marketOwner can set the fee especially useful for direct integrations where configured traders get a discount
Parameters
synthMarketId
(uint128) - Id of the market the custom transactor fee applies to.transactor
(address) - address of the trader getting discounted fees.fixedFeeAmount
(uint256) - the fixed fee applying to the provided transactor.
getCustomTransactorFees
gets the fixed fee for a given market and transactor
overrides both the atomic and async fixed fees especially useful for direct integrations where configured traders get a discount
Parameters
synthMarketId
(uint128) - Id of the market the custom transactor fee applies to.transactor
(address) - address of the trader getting discounted fees.
Returns
fixedFeeAmount
(uint256) - the fixed fee applying to the provided transactor.
setFeeCollector
sets a custom fee collector for a given market
only marketOwner can set the fee collector a use case here would be if the market owner wants to collect the fees via this contract and distribute via rewards distributor to SNX holders for example. if fee collector is not set, the fees are deposited into the market manager.
Parameters
synthMarketId
(uint128) - Id of the market the fee collector applies to.feeCollector
(address) - address of the fee collector inheriting the IFeeCollector interface.
getFeeCollector
gets a custom fee collector for a given market
Parameters
synthMarketId
(uint128) - Id of the market the fee collector applies to.
Returns
feeCollector
(address) - address of the fee collector inheriting the IFeeCollector interface.
setWrapperFees
sets wrapper related fees.
only marketOwner can set the wrapper fees fees can be negative. this is a way to unwind the wrapper if needed by providing incentives.
Parameters
synthMarketId
(uint128) - Id of the market the wrapper fees apply to.wrapFee
(int256) - wrapping fee in %, 18 decimals. Can be negative.unwrapFee
(int256) - unwrapping fee in %, 18 decimals. Can be negative.
updateReferrerShare
Update the referral share percentage for a given market
Parameters
marketId
(uint128) - id of the marketreferrer
(address) - The address of the referrersharePercentage
(uint256) - The new share percentage for the referrer
getReferrerShare
get the referral share percentage for a given market
Parameters
marketId
(uint128) - id of the marketreferrer
(address) - The address of the referrer
Returns
sharePercentage
(uint256) - The new share percentage for the referrer
MarketUtilizationFeesSet
emitted when market utilization fees are set for specified market
Parameters
synthMarketId
(uint256) - market idutilizationFeeRate
(uint256) - utilization fee rate value
MarketSkewScaleSet
emitted when the skew scale is set for a market
Parameters
synthMarketId
(uint256) - market idskewScale
(uint256) - skew scale value
CollateralLeverageSet
emitted when the collateral leverage is set for a market
Parameters
synthMarketId
(uint256) - market idcollateralLeverage
(uint256) - leverage value
AtomicFixedFeeSet
emitted when the fixed fee for atomic orders is set.
Parameters
synthMarketId
(uint256) - market idatomicFixedFee
(uint256) - fee value
AsyncFixedFeeSet
emitted when the fixed fee for async orders is set.
Parameters
synthMarketId
(uint256) - market idasyncFixedFee
(uint256) - fee value
TransactorFixedFeeSet
emitted when the fixed fee is set for a given transactor
this overrides the async/atomic fixed fees for a given transactor
Parameters
synthMarketId
(uint256) - Id of the market to set the fees for.transactor
(address) - fixed fee for the transactor (overrides the global fixed fee)fixedFeeAmount
(uint256) - the fixed fee for the corresponding market, and transactor
FeeCollectorSet
emitted when custom fee collector is set for a given market
Parameters
synthMarketId
(uint256) - Id of the market to set the collector for.feeCollector
(address) - the address of the fee collector to set.
WrapperFeesSet
emitted when wrapper fees are set for a given market
Parameters
synthMarketId
(uint256) - Id of the market to set the wrapper fees.wrapFee
(int256) - wrapping fee in %, 18 decimals. Can be negative.unwrapFee
(int256) - unwrapping fee in %, 18 decimals. Can be negative.
ReferrerShareUpdated
Emitted when the share percentage for a referrer address has been updated.
Parameters
marketId
(uint128) - Id of the marketreferrer
(address) - The address of the referrersharePercentage
(uint256) - The new share percentage for the referrer
Spot Market Factory Module
setSynthetix
Sets the v3 synthetix core system.
Pulls in the USDToken and oracle manager from the synthetix core system and sets those appropriately.
Parameters
synthetix
(contract ISynthetixSystem) - synthetix v3 core system address
setSynthImplementation
When a new synth is created, this is the erc20 implementation that is used.
Parameters
synthImplementation
(address) - erc20 implementation address
createSynth
Creates a new synth market with synthetix v3 core system via market manager
The synth is created using the initial synth implementation and creates a proxy for future upgrades of the synth implementation. Sets up the market owner who can update configuration for the synth.
Parameters
tokenName
(string) - name of synth (i.e Synthetix ETH)tokenSymbol
(string) - symbol of synth (i.e snxETH)synthOwner
(address) - owner of the market that's created.
Returns
synthMarketId
(uint128) - id of the synth market that was created
getSynth
Get the proxy address of the synth for the provided marketId
Uses associated systems module to retrieve the token address.
Parameters
marketId
(uint128) - id of the market
Returns
synthAddress
(address) - address of the proxy for the synth
getSynthImpl
Get the implementation address of the synth for the provided marketId. This address should not be used directly--use getSynth
instead
Uses associated systems module to retrieve the token address.
Parameters
marketId
(uint128) - id of the market
Returns
implAddress
(address) - address of the proxy for the synth
updatePriceData
Update the price data for a given market.
Only the market owner can call this function.
Parameters
marketId
(uint128) - id of the marketbuyFeedId
(bytes32) - the oracle manager buy feed node idsellFeedId
(bytes32) - the oracle manager sell feed node idstrictPriceStalenessTolerance
(uint256) - configurable price staleness tolerance used for transacting
getPriceData
Gets the price data for a given market.
Only the market owner can call this function.
Parameters
marketId
(uint128) - id of the market
Returns
buyFeedId
(bytes32) - the oracle manager buy feed node idsellFeedId
(bytes32) - the oracle manager sell feed node idstrictPriceStalenessTolerance
(uint256) - configurable price staleness tolerance used for transacting
upgradeSynthImpl
upgrades the synth implementation to the current implementation for the specified market. Anyone who is willing and able to spend the gas can call this method.
The synth implementation is upgraded via the proxy.
Parameters
marketId
(uint128) - id of the market
setDecayRate
Allows market to adjust decay rate of the synth
Parameters
marketId
(uint128) - the market to update the synth decay rate forrate
(uint256) - APY to decay of the synth to decay by, as a 18 decimal ratio
nominateMarketOwner
Allows the current market owner to nominate a new owner.
The nominated owner will have to call acceptOwnership
in a separate transaction in order to finalize the action and become the new contract owner.
Parameters
synthMarketId
(uint128) - synth market id valuenewNominatedOwner
(address) - The address that is to become nominated.
acceptMarketOwnership
Allows a nominated address to accept ownership of the market.
Reverts if the caller is not nominated.
Parameters
synthMarketId
(uint128) - synth market id value
renounceMarketNomination
Allows a nominated address to renounce ownership of the market.
Reverts if the caller is not nominated.
Parameters
synthMarketId
(uint128) - synth market id value
renounceMarketOwnership
Allows the market owner to renounce his ownership.
Reverts if the caller is not the owner.
Parameters
synthMarketId
(uint128) - synth market id value
getMarketOwner
Returns market owner.
Parameters
synthMarketId
(uint128) - synth market id value
getNominatedMarketOwner
Returns nominated market owner.
Parameters
synthMarketId
(uint128) - synth market id value
name
returns a human-readable name for a given market
reportedDebt
returns amount of USD that the market would try to mint if everything was withdrawn
minimumCredit
prevents reduction of available credit capacity by specifying this amount, for which withdrawals will be disallowed
supportsInterface
Determines if the contract in question supports the specified interface.
Parameters
interfaceID
(bytes4) - XOR of all selectors in the contract.
Returns
[0]
(bool) - True if the contract supports the specified interface.
SynthetixSystemSet
Gets fired when the synthetix is set
Parameters
synthetix
(address) - address of the synthetix core contractusdTokenAddress
(address) - address of the USDToken contractoracleManager
(address) - address of the Oracle Manager contract
SynthImplementationSet
Gets fired when the synth implementation is set
Parameters
synthImplementation
(address) - address of the synth implementation
SynthRegistered
Gets fired when the synth is registered as a market.
Parameters
synthMarketId
(uint256) - Id of the synth market that was createdsynthTokenAddress
(address) - address of the newly created synth token
SynthImplementationUpgraded
Gets fired when the synth's implementation is updated on the corresponding proxy.
Parameters
synthMarketId
(uint256) -proxy
(address) - the synth proxy servicing the latest implementationimplementation
(address) - the latest implementation of the synth
SynthPriceDataUpdated
Gets fired when the market's price feeds are updated, compatible with oracle manager
Parameters
synthMarketId
(uint256) -buyFeedId
(bytes32) - the oracle manager feed id for the buy pricesellFeedId
(bytes32) - the oracle manager feed id for the sell pricestrictStalenessTolerance
(uint256) -
DecayRateUpdated
Gets fired when the market's price feeds are updated, compatible with oracle manager
Parameters
marketId
(uint128) - Id of the synth marketrate
(uint256) - the new decay rate (1e16 means 1% decay per year)
MarketOwnerNominated
Emitted when an address has been nominated.
Parameters
marketId
(uint128) - id of the marketnewOwner
(address) - The address that has been nominated.
MarketNominationRenounced
Emitted when market nominee renounces nomination.
Parameters
marketId
(uint128) - id of the marketnominee
(address) - The address that has been nominated.
MarketOwnerChanged
Emitted when the owner of the market has changed.
Parameters
marketId
(uint128) - id of the marketoldOwner
(address) - The previous owner of the market.newOwner
(address) - The new owner of the market.
Synth Token Module
setDecayRate
Updates the decay rate for a year
Parameters
_rate
(uint256) - The decay rate with 18 decimals (1e16 means 1% decay per year).
decayRate
get decay rate for a year
advanceEpoch
advance epoch manually in order to avoid precision loss
isInitialized
Returns wether the token has been initialized.
Returns
[0]
(bool) - A boolean with the result of the query.
initialize
Initializes the token with name, symbol, and decimals.
mint
Allows the owner to mint tokens.
Parameters
to
(address) - The address to receive the newly minted tokens.amount
(uint256) - The amount of tokens to mint.
burn
Allows the owner to burn tokens.
Parameters
from
(address) - The address whose tokens will be burnt.amount
(uint256) - The amount of tokens to burn.
setAllowance
Allows an address that holds tokens to provide allowance to another.
Parameters
from
(address) - The address that is providing allowance.spender
(address) - The address that is given allowance.amount
(uint256) - The amount of allowance being given.
name
Retrieves the name of the token, e.g. "Synthetix Network Token".
Returns
[0]
(string) - A string with the name of the token.
symbol
Retrieves the symbol of the token, e.g. "SNX".
Returns
[0]
(string) - A string with the symbol of the token.
decimals
Retrieves the number of decimals used by the token. The default is 18.
Returns
[0]
(uint8) - The number of decimals.
totalSupply
Returns the total number of tokens in circulation (minted - burnt).
Returns
[0]
(uint256) - The total number of tokens.
balanceOf
Returns the balance of a user.
Parameters
owner
(address) - The address whose balance is being retrieved.
Returns
[0]
(uint256) - The number of tokens owned by the user.
allowance
Returns how many tokens a user has allowed another user to transfer on its behalf.
Parameters
owner
(address) - The user who has given the allowance.spender
(address) - The user who was given the allowance.
Returns
[0]
(uint256) - The amount of tokensspender
can transfer onowner
's behalf.
transfer
Transfer tokens from one address to another.
Parameters
to
(address) - The address that will receive the tokens.amount
(uint256) - The amount of tokens to be transferred.
Returns
[0]
(bool) - A boolean which is true if the operation succeeded.
approve
Allows users to provide allowance to other users so that they can transfer tokens on their behalf.
Parameters
spender
(address) - The address that is receiving the allowance.amount
(uint256) - The amount of tokens that are being added to the allowance.
Returns
[0]
(bool) - A boolean which is true if the operation succeeded.
increaseAllowance
Atomically increases the allowance granted to spender
by the caller.
This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.
Emits an {Approval} event indicating the updated allowance.
Requirements:
spender
cannot be the zero address.
decreaseAllowance
Atomically decreases the allowance granted to spender
by the caller.
This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}.
Emits an {Approval} event indicating the updated allowance.
Requirements:
spender
cannot be the zero address.spender
must have allowance for the caller of at leastsubtractedValue
.
transferFrom
Allows a user who has been given allowance to transfer tokens on another user's behalf.
Parameters
from
(address) - The address that owns the tokens that are being transferred.to
(address) - The address that will receive the tokens.amount
(uint256) - The number of tokens to transfer.
Returns
[0]
(bool) - A boolean which is true if the operation succeeded.
Transfer
Emitted when tokens have been transferred.
Parameters
from
(address) - The address that originally owned the tokens.to
(address) - The address that received the tokens.amount
(uint256) - The number of tokens that were transferred.
Approval
Emitted when a user has provided allowance to another user for transferring tokens on its behalf.
Parameters
owner
(address) - The address that is providing the allowance.spender
(address) - The address that received the allowance.amount
(uint256) - The number of tokens that were added tospender
's allowance.
Wrapper Module
setWrapper
Used to set the wrapper supply cap for a given market and collateral type.
If the supply cap is set to 0 or lower than the current outstanding supply, then the wrapper is disabled. There is a synthetix v3 core system supply cap also set. If the current supply becomes higher than either the core system supply cap or the local market supply cap, wrapping will be disabled.
Parameters
marketId
(uint128) - Id of the market to enable wrapping for.wrapCollateralType
(address) - The collateral being used to wrap the synth.maxWrappableAmount
(uint256) - The maximum amount of collateral that can be wrapped.
getWrapper
Used to get the wrapper supply cap for a given market and collateral type.
Parameters
marketId
(uint128) - Id of the market to enable wrapping for.
Returns
wrapCollateralType
(address) - The collateral being used to wrap the synth.maxWrappableAmount
(uint256) - The maximum amount of collateral that can be wrapped.
wrap
Wraps the specified amount and returns similar value of synth minus the fees.
Fees are collected from the user by way of the contract returning less synth than specified amount of collateral.
Parameters
marketId
(uint128) - Id of the market used for the trade.wrapAmount
(uint256) - Amount of collateral to wrap. This amount gets deposited into the market collateral manager.minAmountReceived
(uint256) - The minimum amount of synths the trader is expected to receive, otherwise the transaction will revert.
Returns
amountToMint
(uint256) - Amount of synth returned to user.fees
(struct OrderFees.Data) - breakdown of all fees. in this case, only wrapper fees are returned.
unwrap
Unwraps the synth and returns similar value of collateral minus the fees.
Transfers the specified synth, collects fees through configured fee collector, returns collateral minus fees to trader.
Parameters
marketId
(uint128) - Id of the market used for the trade.unwrapAmount
(uint256) - Amount of synth trader is unwrapping.minAmountReceived
(uint256) - The minimum amount of collateral the trader is expected to receive, otherwise the transaction will revert.
Returns
returnCollateralAmount
(uint256) - Amount of collateral returned.fees
(struct OrderFees.Data) - breakdown of all fees. in this case, only wrapper fees are returned.
WrapperSet
Gets fired when wrapper supply is set for a given market, collateral type.
Parameters
synthMarketId
(uint256) - Id of the market the wrapper is initialized for.wrapCollateralType
(address) - the collateral used to wrap the synth.maxWrappableAmount
(uint256) - the local supply cap for the wrapper.
SynthWrapped
Gets fired after user wraps synth
Parameters
synthMarketId
(uint256) - Id of the market.amountWrapped
(uint256) - amount of synth wrapped.fees
(struct OrderFees.Data) - breakdown of all the fees incurred for the transaction.feesCollected
(uint256) - fees collected by the configured FeeCollector for the market (rest of the fees are deposited to market manager).
SynthUnwrapped
Gets fired after user unwraps synth
Parameters
synthMarketId
(uint256) - Id of the market.amountUnwrapped
(uint256) - amount of synth unwrapped.fees
(struct OrderFees.Data) - breakdown of all the fees incurred for the transaction.feesCollected
(uint256) - fees collected by the configured FeeCollector for the market (rest of the fees are deposited to market manager).
Perps Market
IAccountEvents
CollateralDeducted
Gets fired when some collateral is deducted from the account for paying fees or liquidations.
Parameters
account
(uint256) - Id of the account being deducted.synthMarketId
(uint128) - Id of the synth deducted.amount
(uint256) - Amount of synth market deducted from the account.
Async Order Cancel Module
cancelOrder
Cancels an order when price exceeds the acceptable price. Uses the onchain benchmark price at commitment time.
Parameters
accountId
(uint128) - Id of the account used for the trade.
OrderCancelled
Gets fired when an order is cancelled.
Parameters
marketId
(uint128) - Id of the market used for the trade.accountId
(uint128) - Id of the account used for the trade.desiredPrice
(uint256) - Price at which the order was cancelled.fillPrice
(uint256) - Price at which the order was cancelled.sizeDelta
(int128) - Size delta from order.settlementReward
(uint256) - Amount of fees collected by the settler.trackingCode
(bytes32) - Optional code for integrator tracking purposes.settler
(address) - address of the settler of the order.
Async Order Module
commitOrder
Commit an async order via this function
Parameters
commitment
(struct AsyncOrder.OrderCommitmentRequest) - Order commitment data (see AsyncOrder.OrderCommitmentRequest struct).
Returns
retOrder
(struct AsyncOrder.Data) - order details (see AsyncOrder.Data struct).fees
(uint256) - order fees (protocol + settler)
getOrder
Get async order claim details
Parameters
accountId
(uint128) - id of the account.
Returns
order
(struct AsyncOrder.Data) - async order claim details (see AsyncOrder.Data struct).
computeOrderFees
Simulates what the order fee would be for the given market with the specified size.
Note that this does not include the settlement reward fee, which is based on the strategy type used
Parameters
marketId
(uint128) - id of the market.sizeDelta
(int128) - size of position.
Returns
orderFees
(uint256) - incurred fees.fillPrice
(uint256) - price at which the order would be filled.
computeOrderFeesWithPrice
Simulates what the order fee would be for the given market with the specified size.
Note that this does not include the settlement reward fee, which is based on the strategy type used
Parameters
marketId
(uint128) - id of the market.sizeDelta
(int128) - size of position.price
(uint256) - price of the market.
Returns
orderFees
(uint256) - incurred fees.fillPrice
(uint256) - price at which the order would be filled.
getSettlementRewardCost
Gets the settlement cost including keeper rewards and keeper costs.
Parameters
marketId
(uint128) - Id of the market.settlementStrategyId
(uint128) - Order size.
Returns
[0]
(uint256) - settlement cost.
requiredMarginForOrder
For a given market, account id, and a position size, returns the required total account margin for this order to succeed
Useful for integrators to determine if an order will succeed or fail
Parameters
marketId
(uint128) - id of the market.accountId
(uint128) - id of the trader account.sizeDelta
(int128) - size of position.
Returns
requiredMargin
(uint256) - margin required for the order to succeed.
requiredMarginForOrderWithPrice
For a given market, account id, and a position size, and expected price returns the required total account margin for this order to succeed
Useful for integrators to determine if an order will succeed or fail faking different price scenarios
Parameters
marketId
(uint128) - id of the market.accountId
(uint128) - id of the trader account.sizeDelta
(int128) - size of position.price
(uint256) - price of the market.
Returns
requiredMargin
(uint256) - margin required for the order to succeed.
OrderCommitted
Gets fired when a new order is committed.
Parameters
marketId
(uint128) - Id of the market used for the trade.accountId
(uint128) - Id of the account used for the trade.orderType
(enum SettlementStrategy.Type) - Should send 0 (at time of writing) that correlates to the transaction type enum defined in SettlementStrategy.Type.sizeDelta
(int128) - requested change in size of the order sent by the user.acceptablePrice
(uint256) - maximum or minimum, depending on the sizeDelta direction, accepted price to settle the order, set by the user.commitmentTime
(uint256) - Time at which the order was committed.expectedPriceTime
(uint256) -settlementTime
(uint256) - start time of the settlement window.expirationTime
(uint256) - Time at which the order expired.trackingCode
(bytes32) - Optional code for integrator tracking purposes.sender
(address) - address of the sender of the order. Authorized to commit by account owner.
PreviousOrderExpired
Gets fired when a new order is committed while a previous one was expired.
Parameters
marketId
(uint128) - Id of the market used for the trade.accountId
(uint128) - Id of the account used for the trade.sizeDelta
(int128) - requested change in size of the order sent by the user.acceptablePrice
(uint256) - maximum or minimum, depending on the sizeDelta direction, accepted price to settle the order, set by the user.commitmentTime
(uint256) - Time at which the order was committed.trackingCode
(bytes32) - Optional code for integrator tracking purposes.
Async Order Settlement Pyth Module
settleOrder
Settles an offchain order using the offchain retrieved data from pyth.
Parameters
accountId
(uint128) - The account id to settle the order
OrderSettled
Gets fired when a new order is settled.
Parameters
marketId
(uint128) - Id of the market used for the trade.accountId
(uint128) - Id of the account used for the trade.fillPrice
(uint256) - Price at which the order was settled.pnl
(int256) - Pnl of the previous closed position.accruedFunding
(int256) - Accrued funding of the previous closed position.sizeDelta
(int128) - Size delta from order.newSize
(int128) - New size of the position after settlement.totalFees
(uint256) - Amount of fees collected by the protocol.referralFees
(uint256) - Amount of fees collected by the referrer.collectedFees
(uint256) - Amount of fees collected by fee collector.settlementReward
(uint256) - reward to sender for settling order.trackingCode
(bytes32) - Optional code for integrator tracking purposes.settler
(address) - address of the settler of the order.
InterestCharged
Gets fired after order settles and includes the interest charged to the account.
Parameters
accountId
(uint128) - Id of the account used for the trade.interest
(uint256) - interest charges
Global Perps Market Module
setCollateralConfiguration
Sets the max collateral amount for a specific synth market.
Parameters
synthMarketId
(uint128) - Synth market id, 0 for snxUSD.maxCollateralAmount
(uint256) - Max collateral amount to set for the synth market id.
getCollateralConfiguration
Gets the max collateral amount for a specific synth market.
Parameters
synthMarketId
(uint128) - Synth market id, 0 for snxUSD.
Returns
maxCollateralAmount
(uint256) - max collateral amount of the specified synth market id
getSupportedCollaterals
Gets the list of supported collaterals.
Returns
supportedCollaterals
(uint256[]) - list of supported collateral ids. By supported collateral we mean a collateral which max is greater than zero
setSynthDeductionPriority
Sets the synth deduction priority ordered list.
The synth deduction priority is used to determine the order in which synths are deducted from an account. Id 0 is snxUSD and should be first in the list.
Parameters
newSynthDeductionPriority
(uint128[]) - Ordered array of synth market ids for deduction priority.
getSynthDeductionPriority
Gets the synth deduction priority ordered list.
The synth deduction priority is used to determine the order in which synths are deducted from an account. Id 0 is snxUSD and should be first in the list.
Returns
[0]
(uint128[]) - synthDeductionPriority Ordered array of synth market ids for deduction priority.
setKeeperRewardGuards
Sets the keeper reward guard (min and max).
Parameters
minKeeperRewardUsd
(uint256) - Minimum keeper reward expressed as USD value.minKeeperProfitRatioD18
(uint256) - Minimum keeper profit ratio used together with minKeeperRewardUsd to calculate the minimum.maxKeeperRewardUsd
(uint256) - Maximum keeper reward expressed as USD value.maxKeeperScalingRatioD18
(uint256) - Scaling used to calculate the Maximum keeper reward together with maxKeeperRewardUsd.
getKeeperRewardGuards
Gets the keeper reward guard (min and max).
Returns
minKeeperRewardUsd
(uint256) - Minimum keeper reward expressed as USD value.minKeeperProfitRatioD18
(uint256) - Minimum keeper profit ratio used together with minKeeperRewardUsd to calculate the minimum.maxKeeperRewardUsd
(uint256) - Maximum keeper reward expressed as USD value.maxKeeperScalingRatioD18
(uint256) - Scaling used to calculate the Maximum keeper reward together with maxKeeperRewardUsd.
totalGlobalCollateralValue
Gets the total collateral value of all deposited collateral from all traders.
Returns
totalCollateralValue
(uint256) - value of all collateral
setFeeCollector
Sets the fee collector contract.
must conform to the IFeeCollector interface
Parameters
feeCollector
(address) - address of the fee collector contract
getFeeCollector
Gets the configured feeCollector contract
Returns
feeCollector
(address) - address of the fee collector contract
setPerAccountCaps
Set or update the max number of Positions and Collaterals per Account
Parameters
maxPositionsPerAccount
(uint128) - The max number of concurrent Positions per AccountmaxCollateralsPerAccount
(uint128) - The max number of concurrent Collaterals per Account
getPerAccountCaps
get the max number of Positions and Collaterals per Account
Parameters
updateReferrerShare
Update the referral share percentage for a referrer
Parameters
referrer
(address) - The address of the referrershareRatioD18
(uint256) - The new share percentage for the referrer
getReferrerShare
get the referral share percentage for the specified referrer
Parameters
referrer
(address) - The address of the referrer
Returns
shareRatioD18
(uint256) - The configured share percentage for the referrer
updateKeeperCostNodeId
Set node id for keeper cost
Parameters
keeperCostNodeId
(bytes32) - the node id
getKeeperCostNodeId
Get the node id for keeper cost
Returns
keeperCostNodeId
(bytes32) - the node id
getMarkets
get all existing market ids
Returns
marketIds
(uint256[]) - an array of existing market ids
setInterestRateParameters
Sets the interest rate parameters
Parameters
lowUtilizationInterestRateGradient
(uint128) - interest rate gradient applied to utilization prior to hitting the gradient breakpointinterestRateGradientBreakpoint
(uint128) - breakpoint at which the interest rate gradient changes from low to highhighUtilizationInterestRateGradient
(uint128) - interest rate gradient applied to utilization after hitting the gradient breakpoint
getInterestRateParameters
Gets the interest rate parameters
Returns
lowUtilizationInterestRateGradient
(uint128) -interestRateGradientBreakpoint
(uint128) -highUtilizationInterestRateGradient
(uint128) -
updateInterestRate
Update the market interest rate based on current utilization of the super market against backing collateral
this is a convenience method to manually update interest rate if too much time has passed since last update. interest rate gets automatically updated when a trade is made or when a position is liquidated InterestRateUpdated event is emitted
InterestRateUpdated
Gets fired when the interest rate is updated.
Parameters
superMarketId
(uint128) - global super market idinterestRate
(uint128) - new computed interest rate
CollateralConfigurationSet
Gets fired when max collateral amount for synth for all the markets is set by owner.
Parameters
synthMarketId
(uint128) - Synth market id, 0 for snxUSD.maxCollateralAmount
(uint256) - max amount that was set for the synth
SynthDeductionPrioritySet
Gets fired when the synth deduction priority is updated by owner.
Parameters
newSynthDeductionPriority
(uint128[]) - new synth id priority order for deductions.
KeeperRewardGuardsSet
Gets fired when keeper reward guard is set or updated.
Parameters
minKeeperRewardUsd
(uint256) - Minimum keeper reward expressed as USD value.minKeeperProfitRatioD18
(uint256) - Minimum keeper profit ratio used together with minKeeperRewardUsd to calculate the minimum.maxKeeperRewardUsd
(uint256) - Maximum keeper reward expressed as USD value.maxKeeperScalingRatioD18
(uint256) - Scaling used to calculate the Maximum keeper reward together with maxKeeperRewardUsd.
FeeCollectorSet
emitted when custom fee collector is set
Parameters
feeCollector
(address) - the address of the fee collector to set.
ReferrerShareUpdated
Emitted when the share percentage for a referrer address has been updated.
Parameters
referrer
(address) - The address of the referrershareRatioD18
(uint256) - The new share ratio for the referrer
InterestRateParametersSet
Emitted when interest rate parameters are set
Parameters
lowUtilizationInterestRateGradient
(uint256) - interest rate gradient applied to utilization prior to hitting the gradient breakpointinterestRateGradientBreakpoint
(uint256) - breakpoint at which the interest rate gradient changes from low to highhighUtilizationInterestRateGradient
(uint256) - interest rate gradient applied to utilization after hitting the gradient breakpoint
PerAccountCapsSet
Gets fired when the max number of Positions and Collaterals per Account are set by owner.
Parameters
maxPositionsPerAccount
(uint128) - The max number of concurrent Positions per AccountmaxCollateralsPerAccount
(uint128) - The max number of concurrent Collaterals per Account
KeeperCostNodeIdUpdated
Gets fired when feed id for keeper cost node id is updated.
Parameters
keeperCostNodeId
(bytes32) - oracle node id
Liquidation Module
liquidate
Liquidates an account.
according to the current situation and account size it can be a partial or full liquidation.
Parameters
accountId
(uint128) - Id of the account to liquidate.
Returns
liquidationReward
(uint256) - total reward sent to liquidator.
liquidateFlagged
Liquidates up to maxNumberOfAccounts flagged accounts.
Parameters
maxNumberOfAccounts
(uint256) - max number of accounts to liquidate.
Returns
liquidationReward
(uint256) - total reward sent to liquidator.
liquidateFlaggedAccounts
Liquidates the listed flagged accounts.
if any of the accounts is not flagged for liquidation it will be skipped.
Parameters
accountIds
(uint128[]) - list of account ids to liquidate.
Returns
liquidationReward
(uint256) - total reward sent to liquidator.
flaggedAccounts
Returns the list of flagged accounts.
Returns
accountIds
(uint256[]) - list of flagged accounts.
canLiquidate
Returns if an account is eligible for liquidation.
Returns
isEligible
(bool) -
liquidationCapacity
Current liquidation capacity for the market
Returns
capacity
(uint256) - market can liquidate up to this #maxLiquidationInWindow
(uint256) - max amount allowed to liquidate based on the current market configurationlatestLiquidationTimestamp
(uint256) - timestamp of the last liquidation of the market
PositionLiquidated
Gets fired when an account position is liquidated .
Parameters
accountId
(uint128) - Id of the account liquidated.marketId
(uint128) - Id of the position's market.amountLiquidated
(uint256) - amount liquidated.currentPositionSize
(int128) - position size after liquidation.
AccountFlaggedForLiquidation
Gets fired when an account is flagged for liquidation.
Parameters
accountId
(uint128) - Id of the account flagged.availableMargin
(int256) - available margin after flagging.requiredMaintenanceMargin
(uint256) - required maintenance margin which caused the flagging.liquidationReward
(uint256) - reward for fully liquidating account paid when liquidation occurs.flagReward
(uint256) - reward to keeper for flagging the account
AccountLiquidationAttempt
Gets fired when an account is liquidated.
this event is fired once per liquidation tx after the each position that can be liquidated at the time was liquidated.
Parameters
accountId
(uint128) - Id of the account liquidated.reward
(uint256) - total reward sent to liquidator.fullLiquidation
(bool) - flag indicating if it was a partial or full liquidation.
Market Configuration Module
addSettlementStrategy
Add a new settlement strategy with this function.
Parameters
marketId
(uint128) - id of the market to add the settlement strategy.strategy
(struct SettlementStrategy.Data) - strategy details (see SettlementStrategy.Data struct).
Returns
strategyId
(uint256) - id of the new settlement strategy.
setSettlementStrategy
updates a settlement strategy for a market with this function.
Parameters
marketId
(uint128) - id of the market.strategyId
(uint256) - the specific strategy id.strategy
(struct SettlementStrategy.Data) - strategy details (see SettlementStrategy.Data struct).
setOrderFees
Set order fees for a market with this function.
Parameters
marketId
(uint128) - id of the market to set order fees.makerFeeRatio
(uint256) - the maker fee ratio.takerFeeRatio
(uint256) - the taker fee ratio.
updatePriceData
Set node id for perps market
Parameters
perpsMarketId
(uint128) - id of the market to set price feed.feedId
(bytes32) - the node feed idstrictStalenessTolerance
(uint256) - strict price tolerance in seconds (used for liquidations primarily)
setFundingParameters
Set funding parameters for a market with this function.
Parameters
marketId
(uint128) - id of the market to set funding parameters.skewScale
(uint256) - the skew scale.maxFundingVelocity
(uint256) - the max funding velocity.
setMaxLiquidationParameters
Set liquidation parameters for a market with this function.
Parameters
marketId
(uint128) - id of the market to set liquidation parameters.maxLiquidationLimitAccumulationMultiplier
(uint256) - the max liquidation limit accumulation multiplier.maxSecondsInLiquidationWindow
(uint256) - the max seconds in liquidation window (used together with the acc multiplier to get max liquidation per window).maxLiquidationPd
(uint256) - max allowed pd when calculating max liquidation amountendorsedLiquidator
(address) - address of the endorsed liquidator who can fully liquidate accounts without any restriction
setLiquidationParameters
Set liquidation parameters for a market with this function.
Parameters
marketId
(uint128) - id of the market to set liquidation parameters.initialMarginRatioD18
(uint256) - the initial margin ratio (as decimal with 18 digits precision).minimumInitialMarginRatioD18
(uint256) - the minimum initial margin ratio (as decimal with 18 digits precision).maintenanceMarginScalarD18
(uint256) - the maintenance margin scalar relative to the initial margin ratio (as decimal with 18 digits precision).flagRewardRatioD18
(uint256) - the flag reward ratio (as decimal with 18 digits precision).minimumPositionMargin
(uint256) - the minimum position margin.
setMaxMarketSize
Set the max size of an specific market with this function.
This controls the maximum open interest a market can have on either side (Long | Short). So the total Open Interest (with zero skew) for a market can be up to max market size * 2.
Parameters
marketId
(uint128) - id of the market to set the max market value.maxMarketSize
(uint256) - the max market size in market asset units.maxMarketValue
(uint256) - the max market size in market USD value.
setLockedOiRatio
Set the locked OI Ratio for a market with this function.
Parameters
marketId
(uint128) - id of the market to set locked OI ratio.lockedOiRatioD18
(uint256) - the locked OI ratio skew scale (as decimal with 18 digits precision).
setSettlementStrategyEnabled
Enable or disable a settlement strategy for a market with this function.
Parameters
marketId
(uint128) - id of the market.strategyId
(uint256) - the specific strategy.enabled
(bool) - whether the strategy is enabled or disabled.
getSettlementStrategy
Gets the settlement strategy details.
Parameters
marketId
(uint128) - id of the market.strategyId
(uint256) - id of the settlement strategy.
Returns
settlementStrategy
(struct SettlementStrategy.Data) - strategy details (see SettlementStrategy.Data struct).
getMaxLiquidationParameters
Gets liquidation parameters details of a market.
Parameters
marketId
(uint128) - id of the market.
Returns
maxLiquidationLimitAccumulationMultiplier
(uint256) - the max liquidation limit accumulation multiplier.maxSecondsInLiquidationWindow
(uint256) - the max seconds in liquidation window (used together with the acc multiplier to get max liquidation per window).maxLiquidationPd
(uint256) - max allowed pd when calculating max liquidation amountendorsedLiquidator
(address) - address of the endorsed liquidator who can fully liquidate accounts without any restriction
getLiquidationParameters
Gets liquidation parameters details of a market.
Parameters
marketId
(uint128) - id of the market.
Returns
initialMarginRatioD18
(uint256) - the initial margin ratio (as decimal with 18 digits precision).minimumInitialMarginRatioD18
(uint256) - the minimum initial margin ratio (as decimal with 18 digits precision).maintenanceMarginScalarD18
(uint256) - the maintenance margin scalar relative to the initial margin ratio (as decimal with 18 digits precision).flagRewardRatioD18
(uint256) - the flag reward ratio (as decimal with 18 digits precision).minimumPositionMargin
(uint256) - the minimum position margin.
getFundingParameters
Gets funding parameters of a market.
Parameters
marketId
(uint128) - id of the market.
Returns
skewScale
(uint256) - the skew scale.maxFundingVelocity
(uint256) - the max funding velocity.
getMaxMarketSize
Gets the max size of an specific market.
Parameters
marketId
(uint128) - id of the market.
Returns
maxMarketSize
(uint256) - the max market size in market asset units.maxMarketValue
(uint256) - the max market size in market USD value.
getOrderFees
Gets the order fees of a market.
Parameters
marketId
(uint128) - id of the market.
Returns
makerFeeRatio
(uint256) - the maker fee ratio.takerFeeRatio
(uint256) - the taker fee ratio.
getLockedOiRatio
Gets the locked OI ratio of a market.
Parameters
marketId
(uint128) - id of the market.
Returns
lockedOiRatioD18
(uint256) - the locked OI ratio skew scale (as decimal with 18 digits precision).
getPriceData
Set node id for perps market
Parameters
perpsMarketId
(uint128) - id of the market to set price feed.
Returns
feedId
(bytes32) - the node feed id to get pricestrictStalenessTolerance
(uint256) -
SettlementStrategyAdded
Gets fired when new settlement strategy is added.
Parameters
marketId
(uint128) - adds settlement strategy to this specific market.strategy
(struct SettlementStrategy.Data) - the strategy configuration.strategyId
(uint256) - the newly created settlement strategy id.
SettlementStrategySet
Gets fired when new settlement strategy is updated.
Parameters
marketId
(uint128) - adds settlement strategy to this specific market.strategyId
(uint256) - the newly created settlement strategy id.strategy
(struct SettlementStrategy.Data) - the strategy configuration.
MarketPriceDataUpdated
Gets fired when feed id for perps market is updated.
Parameters
marketId
(uint128) - id of perps marketfeedId
(bytes32) - oracle node idstrictStalenessTolerance
(uint256) - strict price tolerance in seconds (used for liquidations primarily)
OrderFeesSet
Gets fired when order fees are updated.
Parameters
marketId
(uint128) - udpates fees to this specific market.makerFeeRatio
(uint256) - the maker fee ratio.takerFeeRatio
(uint256) - the taker fee ratio.
FundingParametersSet
Gets fired when funding parameters are updated.
Parameters
marketId
(uint128) - udpates funding parameters to this specific market.skewScale
(uint256) - the skew scale.maxFundingVelocity
(uint256) - the max funding velocity.
MaxLiquidationParametersSet
Gets fired when parameters for max liquidation are set
Parameters
marketId
(uint128) - updates funding parameters to this specific market.maxLiquidationLimitAccumulationMultiplier
(uint256) - the max liquidation limit accumulation multiplier.maxSecondsInLiquidationWindow
(uint256) - the max seconds in liquidation window (used together with the acc multiplier to get max liquidation per window).maxLiquidationPd
(uint256) -endorsedLiquidator
(address) -
LiquidationParametersSet
Gets fired when liquidation parameters are updated.
Parameters
marketId
(uint128) - udpates funding parameters to this specific market.initialMarginRatioD18
(uint256) - the initial margin ratio (as decimal with 18 digits precision).maintenanceMarginRatioD18
(uint256) - the maintenance margin ratio (as decimal with 18 digits precision).minimumInitialMarginRatioD18
(uint256) -flagRewardRatioD18
(uint256) - the flag reward ratio (as decimal with 18 digits precision).minimumPositionMargin
(uint256) - the minimum position margin.
MaxMarketSizeSet
Gets fired when max market value is updated.
Parameters
marketId
(uint128) - udpates funding parameters to this specific market.maxMarketSize
(uint256) - the max market value in units.maxMarketValue
(uint256) - the max market value USD denominated.
LockedOiRatioSet
Gets fired when locked oi ratio is updated.
Parameters
marketId
(uint128) - udpates funding parameters to this specific market.lockedOiRatioD18
(uint256) - the locked OI ratio skew scale (as decimal with 18 digits precision).
IMarketEvents
MarketUpdated
Gets fired when the size of a market is updated by new orders or liquidations.
Parameters
marketId
(uint128) - Id of the market used for the trade.price
(uint256) - Price at the time of this event.skew
(int256) - Market skew at the time of the trade. Positive values mean more longs.size
(uint256) - Size of the entire market after settlement.sizeDelta
(int256) - Change in market size during this update.currentFundingRate
(int256) - The current funding rate of this market (0.001 = 0.1% per day)currentFundingVelocity
(int256) - The current rate of change of the funding rate (0.001 = +0.1% per day)interestRate
(uint128) - Current supermarket interest rate based on updated market OI.
Perps Account Module
modifyCollateral
Modify the collateral delegated to the account.
Parameters
accountId
(uint128) - Id of the account.synthMarketId
(uint128) - Id of the synth market used as collateral. Synth market id, 0 for snxUSD.amountDelta
(int256) - requested change in amount of collateral delegated to the account.
getCollateralAmount
Gets the account's collateral value for a specific collateral.
Parameters
accountId
(uint128) - Id of the account.synthMarketId
(uint128) - Id of the synth market used as collateral. Synth market id, 0 for snxUSD.
Returns
[0]
(uint256) - collateralValue collateral value of the account.
getAccountCollateralIds
Gets the account's collaterals ids
Parameters
accountId
(uint128) - Id of the account.
getAccountOpenPositions
Gets all markets that a given account id has a position in
Parameters
accountId
(uint128) - Id of the account.
totalCollateralValue
Gets the account's total collateral value.
Parameters
accountId
(uint128) - Id of the account.
Returns
[0]
(uint256) - collateralValue total collateral value of the account. USD denominated.
totalAccountOpenInterest
Gets the account's total open interest value.
Parameters
accountId
(uint128) - Id of the account.
Returns
[0]
(uint256) - openInterestValue total open interest value of the account.
getOpenPosition
Gets the details of an open position.
Parameters
accountId
(uint128) - Id of the account.marketId
(uint128) - Id of the position market.
Returns
totalPnl
(int256) - pnl of the entire position including funding.accruedFunding
(int256) - accrued funding of the position.positionSize
(int128) - size of the position.owedInterest
(uint256) - interest owed due to open position.
getOpenPositionSize
Gets an account open position data for a given account id and market id this function doesn't have any price staleness requirement
Parameters
accountId
(uint128) - Id of the account.marketId
(uint128) - Id of the position market.
getAvailableMargin
Gets the available margin of an account. It can be negative due to pnl.
Parameters
accountId
(uint128) - Id of the account.
Returns
availableMargin
(int256) - available margin of the position.
getWithdrawableMargin
Gets the exact withdrawable amount a trader has available from this account while holding the account's current positions.
Parameters
accountId
(uint128) - Id of the account.
Returns
withdrawableMargin
(int256) - available margin to withdraw.
getRequiredMargins
Gets the initial/maintenance margins across all positions that an account has open.
Note that requiredInitialMargin and requiredMaintenanceMargin includes the liquidation rewards, in case you want the value without it you need to substract maxLiquidationReward.
Parameters
accountId
(uint128) - Id of the account.
Returns
requiredInitialMargin
(uint256) - initial margin req (used when withdrawing collateral).requiredMaintenanceMargin
(uint256) - maintenance margin req (used to determine liquidation threshold).maxLiquidationReward
(uint256) - max liquidation reward the keeper would receive if account was fully liquidated. Note here that the accumulated rewards are checked against the global max/min configured liquidation rewards.
CollateralModified
Gets fired when an account colateral is modified.
Parameters
accountId
(uint128) - Id of the account.synthMarketId
(uint128) - Id of the synth market used as collateral. Synth market id, 0 for snxUSD.amountDelta
(int256) - requested change in amount of collateral delegated to the account.sender
(address) - address of the sender of the size modification. Authorized by account owner.
Perps Market Factory Module
initializeFactory
Initializes the factory.
this function should be called only once.
Returns
[0]
(uint128) - globalPerpsMarketId Id of the global perps market id.
setPerpsMarketName
Sets the perps market name.
Parameters
marketName
(string) - the new perps market name.
createMarket
Creates a new market.
Parameters
requestedMarketId
(uint128) - id of the market to create.marketName
(string) - name of the market to create.marketSymbol
(string) - symbol of the market to create.
Returns
[0]
(uint128) - perpsMarketId Id of the created perps market.
interestRate
Returns the current market interest rate
Returns
rate
(uint128) -
utilizationRate
Returns the super market utilization rate
The rate is the minimumCredit / delegatedCollateral available. Locked credit is the sum of all markets open interest * configured lockedOiRatio delegatedCollateral is the avaialble collateral value for markets to withdraw, delegated by LPs
Returns
rate
(uint256) -delegatedCollateral
(uint256) -lockedCredit
(uint256) - credit locked based on OI & lockedOiRatio
name
returns a human-readable name for a given market
reportedDebt
returns amount of USD that the market would try to mint if everything was withdrawn
minimumCredit
prevents reduction of available credit capacity by specifying this amount, for which withdrawals will be disallowed
supportsInterface
Determines if the contract in question supports the specified interface.
Parameters
interfaceID
(bytes4) - XOR of all selectors in the contract.
Returns
[0]
(bool) - True if the contract supports the specified interface.
FactoryInitialized
Gets fired when the factory is initialized.
Parameters
globalPerpsMarketId
(uint128) - the new global perps market id.
MarketCreated
Gets fired when a market is created.
Parameters
perpsMarketId
(uint128) - the newly created perps market id.marketName
(string) - the newly created perps market name.marketSymbol
(string) - the newly created perps market symbol.
Perps Market Module
metadata
Gets a market metadata.
Parameters
marketId
(uint128) - Id of the market.
Returns
name
(string) - Name of the market.symbol
(string) - Symbol of the market.
skew
Gets a market's skew.
Parameters
marketId
(uint128) - Id of the market.
Returns
[0]
(int256) - skew Skew of the market.
size
Gets a market's size.
Parameters
marketId
(uint128) - Id of the market.
Returns
[0]
(uint256) - size Size of the market.
maxOpenInterest
Gets a market's max open interest.
Parameters
marketId
(uint128) - Id of the market.
Returns
[0]
(uint256) - maxOpenInterest Max open interest of the market.
currentFundingRate
Gets a market's current funding rate.
Parameters
marketId
(uint128) - Id of the market.
Returns
[0]
(int256) - currentFundingRate Current funding rate of the market.
currentFundingVelocity
Gets a market's current funding velocity.
Parameters
marketId
(uint128) - Id of the market.
Returns
[0]
(int256) - currentFundingVelocity Current funding velocity of the market.
indexPrice
Gets a market's index price.
Parameters
marketId
(uint128) - Id of the market.
Returns
[0]
(uint256) - indexPrice Index price of the market.
fillPrice
Gets a market's fill price for a specific order size and index price.
Parameters
marketId
(uint128) - Id of the market.orderSize
(int128) - Order size.price
(uint256) - Index price.
Returns
[0]
(uint256) - price Fill price.
getMarketSummary
Given a marketId return a market's summary details in one call.
Parameters
marketId
(uint128) - Id of the market.
Returns
summary
(struct IPerpsMarketModule.MarketSummary) - Market summary (see MarketSummary).
Legacy Market
InitialModuleBundle
upgradeTo
Allows the proxy to be upgraded to a new implementation.
Will revert if newImplementation
is not upgradeable. The implementation of this function needs to be protected by some sort of access control such as onlyOwner
.
Parameters
newImplementation
(address) - The address of the proxy's new implementation.
simulateUpgradeTo
Function used to determine if a new implementation will be able to receive future upgrades in upgradeTo
.
This function will always revert, but will revert with different error messages. The function upgradeTo
uses this error to determine the future upgradeability of the implementation in question.
Parameters
newImplementation
(address) - The address of the new implementation being tested for future upgradeability.
getImplementation
Retrieves the current implementation of the proxy.
Returns
[0]
(address) - The address of the current implementation.
_upgradeTo
_implementationIsSterile
_proxyStore
upgradeTo
Allows the proxy to be upgraded to a new implementation.
Will revert if newImplementation
is not upgradeable. The implementation of this function needs to be protected by some sort of access control such as onlyOwner
.
Parameters
newImplementation
(address) - The address of the proxy's new implementation.
simulateUpgradeTo
Function used to determine if a new implementation will be able to receive future upgrades in upgradeTo
.
This function will always revert, but will revert with different error messages. The function upgradeTo
uses this error to determine the future upgradeability of the implementation in question.
Parameters
newImplementation
(address) - The address of the new implementation being tested for future upgradeability.
getImplementation
Retrieves the current implementation of the proxy.
Returns
[0]
(address) - The address of the current implementation.
constructor
constructor
acceptOwnership
Allows a nominated address to accept ownership of the contract.
Reverts if the caller is not nominated.
nominateNewOwner
Allows the current owner to nominate a new owner.
The nominated owner will have to call acceptOwnership
in a separate transaction in order to finalize the action and become the new contract owner.
Parameters
newNominatedOwner
(address) - The address that is to become nominated.
renounceNomination
Allows a nominated owner to reject the nomination.
owner
Returns the current owner of the contract.
nominatedOwner
Returns the current nominated owner of the contract.
Only one address can be nominated at a time.
acceptOwnership
Allows a nominated address to accept ownership of the contract.
Reverts if the caller is not nominated.
nominateNewOwner
Allows the current owner to nominate a new owner.
The nominated owner will have to call acceptOwnership
in a separate transaction in order to finalize the action and become the new contract owner.
Parameters
newNominatedOwner
(address) - The address that is to become nominated.
renounceNomination
Allows a nominated owner to reject the nomination.
owner
Returns the current owner of the contract.
nominatedOwner
Returns the current nominated owner of the contract.
Only one address can be nominated at a time.
Upgraded
Emitted when the implementation of the proxy has been upgraded.
Parameters
self
(address) - The address of the proxy whose implementation was upgraded.implementation
(address) - The address of the proxy's new implementation.
OwnerNominated
Emitted when an address has been nominated.
Parameters
newOwner
(address) - The address that has been nominated.
OwnerChanged
Emitted when the owner of the contract has changed.
Parameters
oldOwner
(address) - The previous owner of the contract.newOwner
(address) - The new owner of the contract.
LegacyMarket
constructor
setSystemAddresses
called by the owner to set the addresses of the v3 and v2x systems which are needed for calls in migrate
and convertUSD
Parameters
v2xResolverAddress
(contract IAddressResolver) - the v2xAddressResolver
contract address. LegacyMarket can use AddressResolver to get the address of any other v2x contract.v3SystemAddress
(contract IV3CoreProxy) - the v3 core proxy address
registerMarket
called by the owner to register this market with v3. This is an initialization call only.
reportedDebt
returns amount of USD that the market would try to mint if everything was withdrawn
name
returns a human-readable name for a given market
minimumCredit
prevents reduction of available credit capacity by specifying this amount, for which withdrawals will be disallowed
convertUSD
Called by anyone with {amount} sUSD to convert {amount} sUSD to {amount} snxUSD. The sUSD will be burned (thereby reducing the sUSD total supply and v2x system size), and snxUSD will be minted. Any user who has sUSD can call this function. If you have migrated to v3 and there is insufficient sUSD liquidity to convert, consider buying snxUSD on the open market, since that means most snxUSD has already been migrated. Requirements:
User must first approve() the legacy market contract to spend the user's sUSD
LegacyMarket must have already sufficient migrated collateral
Parameters
amount
(uint256) - the quantity to convert
migrate
Called by an SNX staker on v2x to convert their position to the equivalent on v3. This entails the following broad steps:
collect all their SNX collateral and debt from v2x
create a new staking account on v3 with the supplied {accountId}
put the collateral and debt into this newly created staking account
send the created staking account to the ERC2771Context._msgSender().
Parameters
accountId
(uint128) - the new account id that the user wants to have. can be any non-zero integer that is not already occupied.
migrateOnBehalf
Same as migrate
, but allows for the owner to forcefully migrate any v2x staker
Parameters
staker
(address) -accountId
(uint128) - the new account id that the user wants to have. can be any non-zero integer that is not already occupied.
_migrate
Migrates {staker} from V2 to {accountId} in V3.
_gatherFromV2
Moves the collateral and debt associated {staker} in the V2 system to this market.
setPauseStablecoinConversion
called by the owner to disable convertUSD
(ex. in the case of an emergency)
Parameters
paused
(bool) - whether or notconvertUSD
should be disable
setPauseMigration
called by the owner to disable migrate
(ex. in the case of an emergency)
Parameters
paused
(bool) - whether or notmigrate
should be disable
_calculateDebtValueMigrated
Returns the amount of dollar-denominated debt associated with {debtSharesMigrated} in the V2 system.
supportsInterface
Determines if the contract in question supports the specified interface.
Parameters
interfaceId
(bytes4) -
Returns
[0]
(bool) - True if the contract supports the specified interface.
upgradeTo
name
returns a human-readable name for a given market
reportedDebt
returns amount of USD that the market would try to mint if everything was withdrawn
minimumCredit
prevents reduction of available credit capacity by specifying this amount, for which withdrawals will be disallowed
supportsInterface
Determines if the contract in question supports the specified interface.
Parameters
interfaceID
(bytes4) - XOR of all selectors in the contract.
Returns
[0]
(bool) - True if the contract supports the specified interface.
simulateUpgradeTo
Function used to determine if a new implementation will be able to receive future upgrades in upgradeTo
.
This function will always revert, but will revert with different error messages. The function upgradeTo
uses this error to determine the future upgradeability of the implementation in question.
Parameters
newImplementation
(address) - The address of the new implementation being tested for future upgradeability.
getImplementation
Retrieves the current implementation of the proxy.
Returns
[0]
(address) - The address of the current implementation.
_upgradeTo
_implementationIsSterile
_proxyStore
upgradeTo
Allows the proxy to be upgraded to a new implementation.
Will revert if newImplementation
is not upgradeable. The implementation of this function needs to be protected by some sort of access control such as onlyOwner
.
Parameters
newImplementation
(address) - The address of the proxy's new implementation.
simulateUpgradeTo
Function used to determine if a new implementation will be able to receive future upgrades in upgradeTo
.
This function will always revert, but will revert with different error messages. The function upgradeTo
uses this error to determine the future upgradeability of the implementation in question.
Parameters
newImplementation
(address) - The address of the new implementation being tested for future upgradeability.
getImplementation
Retrieves the current implementation of the proxy.
Returns
[0]
(address) - The address of the current implementation.
constructor
acceptOwnership
Allows a nominated address to accept ownership of the contract.
Reverts if the caller is not nominated.
nominateNewOwner
Allows the current owner to nominate a new owner.
The nominated owner will have to call acceptOwnership
in a separate transaction in order to finalize the action and become the new contract owner.
Parameters
newNominatedOwner
(address) - The address that is to become nominated.
renounceNomination
Allows a nominated owner to reject the nomination.
owner
Returns the current owner of the contract.
nominatedOwner
Returns the current nominated owner of the contract.
Only one address can be nominated at a time.
acceptOwnership
Allows a nominated address to accept ownership of the contract.
Reverts if the caller is not nominated.
nominateNewOwner
Allows the current owner to nominate a new owner.
The nominated owner will have to call acceptOwnership
in a separate transaction in order to finalize the action and become the new contract owner.
Parameters
newNominatedOwner
(address) - The address that is to become nominated.
renounceNomination
Allows a nominated owner to reject the nomination.
owner
Returns the current owner of the contract.
nominatedOwner
Returns the current nominated owner of the contract.
Only one address can be nominated at a time.
convertUSD
Called by anyone with {amount} sUSD to convert {amount} sUSD to {amount} snxUSD. The sUSD will be burned (thereby reducing the sUSD total supply and v2x system size), and snxUSD will be minted. Any user who has sUSD can call this function. If you have migrated to v3 and there is insufficient sUSD liquidity to convert, consider buying snxUSD on the open market, since that means most snxUSD has already been migrated. Requirements:
User must first approve() the legacy market contract to spend the user's sUSD
LegacyMarket must have already sufficient migrated collateral
Parameters
amount
(uint256) - the quantity to convert
migrate
Called by an SNX staker on v2x to convert their position to the equivalent on v3. This entails the following broad steps:
collect all their SNX collateral and debt from v2x
create a new staking account on v3 with the supplied {accountId}
put the collateral and debt into this newly created staking account
send the created staking account to the ERC2771Context._msgSender().
Parameters
accountId
(uint128) - the new account id that the user wants to have. can be any non-zero integer that is not already occupied.
migrateOnBehalf
Same as migrate
, but allows for the owner to forcefully migrate any v2x staker
Parameters
staker
(address) -accountId
(uint128) - the new account id that the user wants to have. can be any non-zero integer that is not already occupied.
registerMarket
called by the owner to register this market with v3. This is an initialization call only.
setSystemAddresses
called by the owner to set the addresses of the v3 and v2x systems which are needed for calls in migrate
and convertUSD
Parameters
v2xResolverAddress
(contract IAddressResolver) - the v2xAddressResolver
contract address. LegacyMarket can use AddressResolver to get the address of any other v2x contract.v3SystemAddress
(contract IV3CoreProxy) - the v3 core proxy address
setPauseStablecoinConversion
called by the owner to disable convertUSD
(ex. in the case of an emergency)
Parameters
paused
(bool) - whether or notconvertUSD
should be disable
setPauseMigration
called by the owner to disable migrate
(ex. in the case of an emergency)
Parameters
paused
(bool) - whether or notmigrate
should be disable
MarketRegistered
Upgraded
Emitted when the implementation of the proxy has been upgraded.
Parameters
self
(address) - The address of the proxy whose implementation was upgraded.implementation
(address) - The address of the proxy's new implementation.
OwnerNominated
Emitted when an address has been nominated.
Parameters
newOwner
(address) - The address that has been nominated.
OwnerChanged
Emitted when the owner of the contract has changed.
Parameters
oldOwner
(address) - The previous owner of the contract.newOwner
(address) - The new owner of the contract.
AccountMigrated
Emitted after an account has been migrated from the (legacy) v2x system to v3
Parameters
staker
(address) - the address of the v2x staker that migratedaccountId
(uint256) - the new account idcollateralAmount
(uint256) - the amount of SNX migrated to v3debtAmount
(uint256) - the value of new debt now managed by v3
ConvertedUSD
Emitted after a call to convertUSD
, moving debt from v2x to v3.
Parameters
account
(address) - the address of the address which provided the sUSD for conversionamount
(uint256) - the amount of sUSD burnt, and the amount of snxUSD minted
PauseStablecoinConversionSet
Emitted after a call to setPauseStablecoinConversion
Parameters
sender
(address) - the address setting the stablecoin conversion pause statuspaused
(bool) - whether stablecoin conversion is being paused or unpaused
PauseMigrationSet
Emitted after a call to setPauseMigration
Parameters
sender
(address) - the address setting the migration pause statuspaused
(bool) - whether migration is being paused or unpaused
ILegacyMarket
convertUSD
Called by anyone with {amount} sUSD to convert {amount} sUSD to {amount} snxUSD. The sUSD will be burned (thereby reducing the sUSD total supply and v2x system size), and snxUSD will be minted. Any user who has sUSD can call this function. If you have migrated to v3 and there is insufficient sUSD liquidity to convert, consider buying snxUSD on the open market, since that means most snxUSD has already been migrated. Requirements:
User must first approve() the legacy market contract to spend the user's sUSD
LegacyMarket must have already sufficient migrated collateral
Parameters
amount
(uint256) - the quantity to convert
migrate
Called by an SNX staker on v2x to convert their position to the equivalent on v3. This entails the following broad steps:
collect all their SNX collateral and debt from v2x
create a new staking account on v3 with the supplied {accountId}
put the collateral and debt into this newly created staking account
send the created staking account to the ERC2771Context._msgSender().
Parameters
accountId
(uint128) - the new account id that the user wants to have. can be any non-zero integer that is not already occupied.
migrateOnBehalf
Same as migrate
, but allows for the owner to forcefully migrate any v2x staker
Parameters
staker
(address) -accountId
(uint128) - the new account id that the user wants to have. can be any non-zero integer that is not already occupied.
registerMarket
called by the owner to register this market with v3. This is an initialization call only.
setSystemAddresses
called by the owner to set the addresses of the v3 and v2x systems which are needed for calls in migrate
and convertUSD
Parameters
v2xResolverAddress
(contract IAddressResolver) - the v2xAddressResolver
contract address. LegacyMarket can use AddressResolver to get the address of any other v2x contract.v3SystemAddress
(contract IV3CoreProxy) - the v3 core proxy address
setPauseStablecoinConversion
called by the owner to disable convertUSD
(ex. in the case of an emergency)
Parameters
paused
(bool) - whether or notconvertUSD
should be disable
setPauseMigration
called by the owner to disable migrate
(ex. in the case of an emergency)
Parameters
paused
(bool) - whether or notmigrate
should be disable
AccountMigrated
Emitted after an account has been migrated from the (legacy) v2x system to v3
Parameters
staker
(address) - the address of the v2x staker that migratedaccountId
(uint256) - the new account idcollateralAmount
(uint256) - the amount of SNX migrated to v3debtAmount
(uint256) - the value of new debt now managed by v3
ConvertedUSD
Emitted after a call to convertUSD
, moving debt from v2x to v3.
Parameters
account
(address) - the address of the address which provided the sUSD for conversionamount
(uint256) - the amount of sUSD burnt, and the amount of snxUSD minted
PauseStablecoinConversionSet
Emitted after a call to setPauseStablecoinConversion
Parameters
sender
(address) - the address setting the stablecoin conversion pause statuspaused
(bool) - whether stablecoin conversion is being paused or unpaused
PauseMigrationSet
Emitted after a call to setPauseMigration
Parameters
sender
(address) - the address setting the migration pause statuspaused
(bool) - whether migration is being paused or unpaused
Governance
Council Token Module
isInitialized
Returns whether the token has been initialized.
Returns
[0]
(bool) - A boolean with the result of the query.
initialize
Initializes the token with name, symbol, and uri.
mint
Allows the owner to mint tokens.
Parameters
to
(address) - The address to receive the newly minted tokens.tokenId
(uint256) - The ID of the newly minted token
safeMint
Allows the owner to mint tokens. Verifies that the receiver can receive the token
Parameters
to
(address) - The address to receive the newly minted token.tokenId
(uint256) - The ID of the newly minted tokendata
(bytes) - any data which should be sent to the receiver
burn
Allows the owner to burn tokens.
Parameters
tokenId
(uint256) - The token to burn
setAllowance
Allows an address that holds tokens to provide allowance to another.
Parameters
tokenId
(uint256) - The token which should be allowed to spenderspender
(address) - The address that is given allowance.
setBaseTokenURI
Allows the owner to update the base token URI.
Parameters
uri
(string) - The new base token uri
totalSupply
Returns the total amount of tokens stored by the contract.
tokenOfOwnerByIndex
Returns a token ID owned by owner
at a given index
of its token list. Use along with {balanceOf} to enumerate all of owner
's tokens.
Requirements:
owner
must be a valid addressindex
must be less than the balance of the tokens for the owner
tokenByIndex
Returns a token ID at a given index
of all the tokens stored by the contract. Use along with {totalSupply} to enumerate all tokens.
Requirements:
index
must be less than the total supply of the tokens
balanceOf
Returns the number of tokens in owner
's account.
Requirements:
holder
must be a valid address
ownerOf
Returns the owner of the tokenId
token.
Requirements:
tokenId
must exist.
safeTransferFrom
Safely transfers tokenId
token from from
to to
.
Requirements:
from
cannot be the zero address.to
cannot be the zero address.tokenId
token must exist and be owned byfrom
.If the caller is not
from
, it must be approved to move this token by either {approve} or {setApprovalForAll}.If
to
refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
Emits a {Transfer} event.
safeTransferFrom
Safely transfers tokenId
token from from
to to
, checking first that contract recipients are aware of the ERC721 protocol to prevent tokens from being forever locked.
Requirements:
from
cannot be the zero address.to
cannot be the zero address.tokenId
token must exist and be owned byfrom
.If the caller is not
from
, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.If
to
refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
Emits a {Transfer} event.
transferFrom
Transfers tokenId
token from from
to to
.
WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
Requirements:
from
cannot be the zero address.to
cannot be the zero address.tokenId
token must be owned byfrom
.If the caller is not
from
, it must be approved to move this token by either {approve} or {setApprovalForAll}.
Emits a {Transfer} event.
approve
Gives permission to to
to transfer tokenId
token to another account. The approval is cleared when the token is transferred.
Only a single account can be approved at a time, so approving the zero address clears previous approvals.
Requirements:
The caller must own the token or be an approved operator.
tokenId
must exist.
Emits an {Approval} event.
setApprovalForAll
Approve or remove operator
as an operator for the caller. Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
Requirements:
The
operator
cannot be the caller.
Emits an {ApprovalForAll} event.
getApproved
Returns the account approved for tokenId
token.
Requirements:
tokenId
must exist.
isApprovedForAll
Returns if the operator
is allowed to manage all of the assets of owner
.
See {setApprovalForAll}
Transfer
Emitted when tokenId
token is transferred from from
to to
.
Approval
Emitted when owner
enables approved
to manage the tokenId
token.
ApprovalForAll
Emitted when owner
enables or disables (approved
) operator
to manage all of its assets.
IDebtShare
balanceOfOnPeriod
Election Inspector Module
getEpochStartDateForIndex
Returns the date in which the given epoch started
getEpochEndDateForIndex
Returns the date in which the given epoch ended
getNominationPeriodStartDateForIndex
Returns the date in which the Nomination period in the given epoch started
getVotingPeriodStartDateForIndex
Returns the date in which the Voting period in the given epoch started
wasNominated
Shows if a candidate was nominated in the given epoch
getNomineesAtEpoch
Returns a list of all nominated candidates in the given epoch
getBallotVotedAtEpoch
Returns the ballot id that user voted on in the given election
hasVotedInEpoch
Returns if user has voted in the given election
getBallotVotesInEpoch
Returns the number of votes given to a particular ballot in a given epoch
getBallotCandidatesInEpoch
Returns the list of candidates that a particular ballot has in a given epoch
getCandidateVotesInEpoch
Returns the number of votes a candidate received in a given epoch
getElectionWinnersInEpoch
Returns the winners of the given election
Election Module
initOrUpgradeElectionModule
Initializes the module and immediately starts the first epoch
isElectionModuleInitialized
Shows whether the module has been initialized
tweakEpochSchedule
Adjusts the current epoch schedule requiring that the current period remains Administration, and that changes are small (see setMaxDateAdjustmentTolerance)
modifyEpochSchedule
Adjusts the current epoch schedule requiring that the current period remains Administration
setMinEpochDurations
Determines minimum values for epoch schedule adjustments
setMaxDateAdjustmentTolerance
Determines adjustment size for tweakEpochSchedule
setDefaultBallotEvaluationBatchSize
Determines batch size when evaluate() is called with numBallots = 0
setNextEpochSeatCount
Determines the number of council members in the next epoch
setMinimumActiveMembers
Determines the minimum number of council members before triggering an emergency election
dismissMembers
Allows the owner to remove one or more council members, triggering an election if a threshold is met
nominate
Allows anyone to self-nominate during the Nomination period
withdrawNomination
Self-withdrawal of nominations during the Nomination period
cast
Allows anyone with vote power to vote on nominated candidates during the Voting period
withdrawVote
Allows votes to be withdraw
evaluate
Processes ballots in batches during the Evaluation period (after epochEndDate)
resolve
Shuffles NFTs and resolves an election after it has been evaluated
getMinEpochDurations
Exposes minimum durations required when adjusting epoch schedules
getMaxDateAdjustmenTolerance
Exposes maximum size of adjustments when calling tweakEpochSchedule
getDefaultBallotEvaluationBatchSize
Shows the default batch size when calling evaluate() with numBallots = 0
getNextEpochSeatCount
Shows the number of council members that the next epoch will have
getMinimumActiveMembers
Returns the minimum active members that the council needs to avoid an emergency election
getEpochIndex
Returns the index of the current epoch. The first epoch's index is 1
getEpochStartDate
Returns the date in which the current epoch started
getEpochEndDate
Returns the date in which the current epoch will end
getNominationPeriodStartDate
Returns the date in which the Nomination period in the current epoch will start
getVotingPeriodStartDate
Returns the date in which the Voting period in the current epoch will start
getCurrentPeriod
Returns the current period type: Administration, Nomination, Voting, Evaluation
isNominated
Shows if a candidate has been nominated in the current epoch
getNominees
Returns a list of all nominated candidates in the current epoch
calculateBallotId
Hashes a list of candidates (used for identifying and storing ballots)
getBallotVoted
Returns the ballot id that user voted on in the current election
hasVoted
Returns if user has voted in the current election
getVotePower
Returns the vote power of user in the current election
getBallotVotes
Returns the number of votes given to a particular ballot
getBallotCandidates
Returns the list of candidates that a particular ballot has
isElectionEvaluated
Returns whether all ballots in the current election have been counted
getCandidateVotes
Returns the number of votes a candidate received. Requires the election to be partially or totally evaluated
getElectionWinners
Returns the winners of the current election. Requires the election to be partially or totally evaluated
getCouncilToken
Returns the address of the council NFT token
getCouncilMembers
Returns the current NFT token holders
Synthetix Election Module
initOrUpgradeElectionModule
Initializes the module and immediately starts the first epoch
setDebtShareContract
Sets the Synthetix v2 DebtShare contract that determines vote power
getDebtShareContract
Returns the Synthetix v2 DebtShare contract that determines vote power
setDebtShareSnapshotId
Sets the Synthetix v2 DebtShare snapshot that determines vote power for this epoch
getDebtShareSnapshotId
Returns the Synthetix v2 DebtShare snapshot id set for this epoch
getDebtShare
Returns the Synthetix v2 debt share for the provided address, at this epoch's snapshot
setCrossChainDebtShareMerkleRoot
Allows the system owner to declare a merkle root for user debt shares on other chains for this epoch
getCrossChainDebtShareMerkleRoot
Returns the current epoch's merkle root for user debt shares on other chains
getCrossChainDebtShareMerkleRootBlockNumber
Returns the current epoch's merkle root block number
declareCrossChainDebtShare
Allows users to declare their Synthetix v2 debt shares on other chains
getDeclaredCrossChainDebtShare
Returns the Synthetix v2 debt shares for the provided address, at this epoch's snapshot, in other chains
declareAndCast
Declares cross chain debt shares and casts a vote
initOrUpgradeElectionModule
Initializes the module and immediately starts the first epoch
isElectionModuleInitialized
Shows whether the module has been initialized
tweakEpochSchedule
Adjusts the current epoch schedule requiring that the current period remains Administration, and that changes are small (see setMaxDateAdjustmentTolerance)
modifyEpochSchedule
Adjusts the current epoch schedule requiring that the current period remains Administration
setMinEpochDurations
Determines minimum values for epoch schedule adjustments
setMaxDateAdjustmentTolerance
Determines adjustment size for tweakEpochSchedule
setDefaultBallotEvaluationBatchSize
Determines batch size when evaluate() is called with numBallots = 0
setNextEpochSeatCount
Determines the number of council members in the next epoch
setMinimumActiveMembers
Determines the minimum number of council members before triggering an emergency election
dismissMembers
Allows the owner to remove one or more council members, triggering an election if a threshold is met
nominate
Allows anyone to self-nominate during the Nomination period
withdrawNomination
Self-withdrawal of nominations during the Nomination period
cast
Allows anyone with vote power to vote on nominated candidates during the Voting period
withdrawVote
Allows votes to be withdraw
evaluate
Processes ballots in batches during the Evaluation period (after epochEndDate)
resolve
Shuffles NFTs and resolves an election after it has been evaluated
getMinEpochDurations
Exposes minimum durations required when adjusting epoch schedules
getMaxDateAdjustmenTolerance
Exposes maximum size of adjustments when calling tweakEpochSchedule
getDefaultBallotEvaluationBatchSize
Shows the default batch size when calling evaluate() with numBallots = 0
getNextEpochSeatCount
Shows the number of council members that the next epoch will have
getMinimumActiveMembers
Returns the minimum active members that the council needs to avoid an emergency election
getEpochIndex
Returns the index of the current epoch. The first epoch's index is 1
getEpochStartDate
Returns the date in which the current epoch started
getEpochEndDate
Returns the date in which the current epoch will end
getNominationPeriodStartDate
Returns the date in which the Nomination period in the current epoch will start
getVotingPeriodStartDate
Returns the date in which the Voting period in the current epoch will start
getCurrentPeriod
Returns the current period type: Administration, Nomination, Voting, Evaluation
isNominated
Shows if a candidate has been nominated in the current epoch
getNominees
Returns a list of all nominated candidates in the current epoch
calculateBallotId
Hashes a list of candidates (used for identifying and storing ballots)
getBallotVoted
Returns the ballot id that user voted on in the current election
hasVoted
Returns if user has voted in the current election
getVotePower
Returns the vote power of user in the current election
getBallotVotes
Returns the number of votes given to a particular ballot
getBallotCandidates
Returns the list of candidates that a particular ballot has
isElectionEvaluated
Returns whether all ballots in the current election have been counted
getCandidateVotes
Returns the number of votes a candidate received. Requires the election to be partially or totally evaluated
getElectionWinners
Returns the winners of the current election. Requires the election to be partially or totally evaluated
getCouncilToken
Returns the address of the council NFT token
getCouncilMembers
Returns the current NFT token holders
Oracle Manager
Node Module
registerNode
Registers a node
Parameters
nodeType
(enum NodeDefinition.NodeType) - The nodeType assigned to this node.parameters
(bytes) - The parameters assigned to this node.parents
(bytes32[]) - The parents assigned to this node.
Returns
nodeId
(bytes32) - The id of the registered node.
getNodeId
Returns the ID of a node, whether or not it has been registered.
Parameters
nodeType
(enum NodeDefinition.NodeType) - The nodeType assigned to this node.parameters
(bytes) - The parameters assigned to this node.parents
(bytes32[]) - The parents assigned to this node.
Returns
nodeId
(bytes32) - The id of the node.
getNode
Returns a node's definition (type, parameters, and parents)
Parameters
nodeId
(bytes32) - The node ID
Returns
node
(struct NodeDefinition.Data) - The node's definition data
process
Returns a node current output data
Parameters
nodeId
(bytes32) - The node ID
Returns
node
(struct NodeOutput.Data) - The node's output data
processWithRuntime
Returns a node current output data
Parameters
nodeId
(bytes32) - The node IDruntimeKeys
(bytes32[]) - Keys corresponding to runtime values which could be used by the node graphruntimeValues
(bytes32[]) - The values used by the node graph
Returns
node
(struct NodeOutput.Data) - The node's output data
NodeRegistered
Emitted when registerNode
is called.
Parameters
nodeId
(bytes32) - The id of the registered node.nodeType
(enum NodeDefinition.NodeType) - The nodeType assigned to this node.parameters
(bytes) - The parameters assigned to this node.parents
(bytes32[]) - The parents assigned to this node.
ChainlinkNode
process
getTwapPrice
isValid
ConstantNode
process
isValid
ExternalNode
process
isValid
PriceDeviationCircuitBreakerNode
process
abs
isValid
ReducerNode
process
median
mean
recent
max
min
mul
div
mulDecimal
divDecimal
quickSort
isValid
StalenessCircuitBreakerNode
process
isValid
UniswapNode
process
getQuoteAtTick
isValid
PythNode
process
isValid
PythOffchainLookupNode
process
isValid
Last updated