UNPKG

@parifi/synthetix-sdk-ts

Version:

A Typescript SDK for interactions with the Synthetix protocol

1 lines 17 kB
{"version":3,"sources":["../../src/core/index.ts","../../src/constants/common.ts"],"sourcesContent":["import { Address, encodeFunctionData, formatEther, Hex, parseUnits } from 'viem';\nimport { SynthetixSdk } from '..';\nimport { ZERO_ADDRESS } from '../constants/common';\nimport { CoreRepository } from '../interface/Core';\nimport { OverrideParamsWrite, WriteReturnType } from '../interface/commonTypes';\nimport { Call3Value } from '../interface/contractTypes';\n\n/**\n * Class for interacting with Synthetix V3 core contracts\n * @remarks\n *\n */\nexport class Core implements CoreRepository {\n sdk: SynthetixSdk;\n defaultAccountId?: bigint;\n accountIds: bigint[];\n\n constructor(synthetixSdk: SynthetixSdk) {\n this.sdk = synthetixSdk;\n this.accountIds = [];\n }\n\n async initCore() {\n await this.getAccountIds();\n }\n\n /**\n * Returns the Owner wallet address for an account ID\n * @param accountId - Account ID\n * @returns string - Address of the account owning the accountId\n */\n public async getAccountOwner(accountId: bigint): Promise<Hex> {\n const coreProxy = await this.sdk.contracts.getCoreProxyInstance();\n const response = await this.sdk.utils.callErc7412({\n contractAddress: coreProxy.address,\n abi: coreProxy.abi,\n functionName: 'getAccountOwner',\n args: [accountId],\n });\n\n this.sdk.logger.info(`Core account Owner for id ${accountId} is ${response}`);\n\n return response as Hex;\n }\n\n /**\n * Get the address of the USD stablecoin token\n *\n * @returns Address of the USD stablecoin token\n */\n public async getUsdToken(): Promise<Hex> {\n const coreProxy = await this.sdk.contracts.getCoreProxyInstance();\n const response = await this.sdk.utils.callErc7412({\n contractAddress: coreProxy.address,\n abi: coreProxy.abi,\n functionName: 'getUsdToken',\n args: [],\n });\n\n this.sdk.logger.info('USD Token address: ', response);\n return response as Hex;\n }\n\n /**\n * Get the core account IDs owned by an address.\n * Fetches the account IDs for the given address by checking the balance of\n * the AccountProxy contract, which is an NFT owned by the address.\n * If no address is provided, uses the connected wallet address.\n * @param address The address to get accounts for. Uses connected address if not provided.\n * @param defaultAccountId The default account ID to set after fetching.\n * @returns A list of account IDs owned by the address\n */\n\n public async getAccountIds({\n address: accountAddress = this.sdk.accountAddress || ZERO_ADDRESS,\n accountId: defaultAccountId = undefined,\n }: {\n address?: string;\n accountId?: bigint;\n } = {}): Promise<bigint[]> {\n if (accountAddress == ZERO_ADDRESS) {\n throw new Error('Invalid address');\n }\n\n const accountProxy = await this.sdk.contracts.getAccountProxyInstance();\n const balance = await accountProxy.read.balanceOf([accountAddress]);\n this.sdk.logger.info('balance', balance);\n\n const argsList = [];\n\n for (let index = 0; index < Number(balance); index++) {\n argsList.push([accountAddress, index]);\n }\n const accountIds = (await this.sdk.utils.multicallErc7412({\n contractAddress: accountProxy.address,\n abi: accountProxy.abi,\n functionName: 'tokenOfOwnerByIndex',\n args: argsList,\n })) as unknown[] as bigint[];\n\n // Set Core account ids\n this.accountIds = accountIds;\n this.sdk.logger.info('accountIds', accountIds);\n if (defaultAccountId) {\n this.defaultAccountId = defaultAccountId;\n } else if (this.accountIds.length > 0) {\n this.defaultAccountId = this.accountIds[0];\n this.sdk.logger.info('Using default account id as ', this.defaultAccountId);\n }\n return accountIds;\n }\n\n /**\n * Get the available collateral for an account for a specified collateral type\n * of ``token_address``\n * Fetches the amount of undelegated collateral available for withdrawal\n * for a given token and account.\n * @param tokenAddress The address of the collateral token\n * @param accountId The ID of the account to check. Uses default if not provided.\n * @returns The available collateral as an ether value.\n */\n public async getAvailableCollateral({\n tokenAddress,\n accountId = this.defaultAccountId,\n }: {\n tokenAddress: Address;\n accountId?: bigint;\n }): Promise<string> {\n if (!accountId) throw new Error('Invalid account ID');\n\n const coreProxy = await this.sdk.contracts.getCoreProxyInstance();\n\n const availableCollateral = await this.sdk.utils.callErc7412({\n contractAddress: coreProxy.address,\n abi: coreProxy.abi,\n functionName: 'getAccountAvailableCollateral',\n args: [accountId, tokenAddress],\n });\n\n return formatEther(availableCollateral as bigint);\n }\n\n /**\n * Retrieves the unique system preferred pool\n * @returns poolId The id of the pool that is currently set as preferred in the system.\n */\n public async getPreferredPool(): Promise<bigint> {\n const coreProxy = await this.sdk.contracts.getCoreProxyInstance();\n\n const preferredPool = await this.sdk.utils.callErc7412({\n contractAddress: coreProxy.address,\n abi: coreProxy.abi,\n functionName: 'getPreferredPool',\n args: [],\n });\n this.sdk.logger.info(preferredPool);\n return preferredPool as bigint;\n }\n\n public async createAccount(\n accountId?: bigint,\n override: Omit<OverrideParamsWrite, 'useOracleCalls'> = { shouldRevertOnTxFailure: false },\n ): Promise<WriteReturnType> {\n const txArgs = [];\n if (accountId != undefined) {\n txArgs.push(accountId);\n }\n\n const coreProxy = await this.sdk.contracts.getCoreProxyInstance();\n const createAccountTx: Call3Value = {\n target: coreProxy.address,\n callData: encodeFunctionData({\n abi: coreProxy.abi,\n functionName: 'createAccount',\n args: txArgs,\n }),\n value: 0n,\n requireSuccess: true,\n };\n const txs = [createAccountTx];\n return this.sdk.utils.processTransactions(txs, { ...override, useOracleCalls: false });\n }\n\n public async deposit(\n {\n tokenAddress,\n amount,\n decimals = 18,\n accountId = this.defaultAccountId,\n }: {\n tokenAddress: string;\n amount: number;\n decimals: number;\n accountId?: bigint;\n },\n override: OverrideParamsWrite = { shouldRevertOnTxFailure: false },\n ): Promise<WriteReturnType> {\n if (!accountId) throw new Error('Invalid account ID');\n\n const amountInWei = parseUnits(amount.toString(), decimals);\n const coreProxy = await this.sdk.contracts.getCoreProxyInstance();\n\n const depositTx: Call3Value = {\n target: coreProxy.address,\n callData: encodeFunctionData({\n abi: coreProxy.abi,\n functionName: 'deposit',\n args: [accountId, tokenAddress, amountInWei],\n }),\n value: 0n,\n requireSuccess: true,\n };\n\n const txs = [depositTx];\n return this.sdk.utils.processTransactions(txs, override);\n }\n\n public async withdraw(\n {\n tokenAddress,\n amount,\n decimals = 18,\n accountId = this.defaultAccountId,\n }: {\n tokenAddress: string;\n amount: number;\n decimals: number;\n accountId?: bigint;\n },\n override: OverrideParamsWrite = { shouldRevertOnTxFailure: false },\n ): Promise<WriteReturnType> {\n if (!accountId) throw new Error('Account ID is required for withdrawal');\n\n const amountInWei = parseUnits(amount.toString(), decimals);\n const coreProxy = await this.sdk.contracts.getCoreProxyInstance();\n\n const withdrawTx: Call3Value = {\n target: coreProxy.address,\n callData: encodeFunctionData({\n abi: coreProxy.abi,\n functionName: 'withdraw',\n args: [accountId, tokenAddress, amountInWei],\n }),\n value: 0n,\n requireSuccess: true,\n };\n\n const txs = [withdrawTx];\n return this.sdk.utils.processTransactions(txs, override);\n }\n\n public async delegateCollateral(\n {\n tokenAddress,\n amount,\n poolId,\n leverage,\n accountId = this.defaultAccountId,\n }: {\n tokenAddress: string;\n amount: number;\n poolId: bigint;\n leverage: number;\n accountId?: bigint;\n },\n override: OverrideParamsWrite = { shouldRevertOnTxFailure: false },\n ): Promise<WriteReturnType> {\n if (!accountId) throw new Error('Invalid account ID');\n\n const amountInWei = parseUnits(amount.toString(), 18);\n const leverageInWei = parseUnits(leverage.toString(), 18);\n const coreProxy = await this.sdk.contracts.getCoreProxyInstance();\n\n const delegateCollateralTx: Call3Value = {\n target: coreProxy.address,\n callData: encodeFunctionData({\n abi: coreProxy.abi,\n functionName: 'delegateCollateral',\n args: [accountId, poolId, tokenAddress, amountInWei, leverageInWei],\n }),\n value: 0n,\n requireSuccess: true,\n };\n\n const txs = [delegateCollateralTx];\n return this.sdk.utils.processTransactions(txs, override);\n }\n\n public async mintUsd(\n {\n tokenAddress,\n amount,\n poolId,\n accountId = this.defaultAccountId,\n }: {\n tokenAddress: Address;\n amount: number;\n poolId: bigint;\n accountId?: bigint;\n },\n override: OverrideParamsWrite = { shouldRevertOnTxFailure: false },\n ): Promise<WriteReturnType> {\n if (!accountId) throw new Error('Invalid account ID');\n\n const amountInWei = parseUnits(amount.toString(), 18);\n const coreProxy = await this.sdk.contracts.getCoreProxyInstance();\n\n const mintUsdTx: Call3Value = {\n target: coreProxy.address,\n callData: encodeFunctionData({\n abi: coreProxy.abi,\n functionName: 'mintUsd',\n args: [accountId, poolId, tokenAddress, amountInWei],\n }),\n value: 0n,\n requireSuccess: true,\n };\n\n const txs = [mintUsdTx];\n return this.sdk.utils.processTransactions(txs, override);\n }\n}\n","import { Hex, zeroAddress } from 'viem';\nimport { MarketIdOrName } from '../interface/commonTypes';\nimport { SUPPORTED_CHAINS } from './chains';\n\nexport const ZERO_ADDRESS: Hex = zeroAddress;\n\nexport const SIG_ORACLE_DATA_REQUIRED = '0xcf2cabdf';\nexport const SIG_FEE_REQUIRED = '0x0e7186fb';\nexport const SIG_ERRORS = '0x0b42fd17';\n\n// for markets metadata it is requesting too much oracle updates\nexport const MAX_ERC7412_RETRIES = 80; // Limit the max failures to prevent infinite loops\n\n// List of market ids disabled by chainId\nexport const DISABLED_MARKETS: { [key: number]: number[] } = {\n 84532: [3, 6300],\n 8453: [6300],\n};\n\nexport const publicRpcEndpoints: { [key: number]: string } = {\n 8453: 'https://base.llamarpc.com',\n 84532: 'https://sepolia.base.org',\n 42161: 'https://arbitrum.llamarpc.com',\n 421614: 'https://sepolia-rollup.arbitrum.io/rpc',\n};\n\n// Logger constants\nexport type LOGGER_MESSAGE_TYPE = 'json' | 'pretty' | 'hidden';\n\n// 0: silly, 1: trace, 2: debug, 3: info, 4: warn, 5: error, 6: fatal\nexport const DEFAULT_LOGGER_LEVEL = 4; // https://tslog.js.org/#/?id=highlights to see more levels\nexport const CUSTOM_DECIMALS: Record<number, Record<MarketIdOrName, number>> = {\n [SUPPORTED_CHAINS.ARBITUM_SEPOLIA]: {\n 2: 6,\n USDC: 6,\n },\n [SUPPORTED_CHAINS.ARBITRUM]: {\n 2: 6,\n USDC: 6,\n },\n [SUPPORTED_CHAINS.BASE_SEPOLIA]: {\n 1: 6,\n USDC: 6,\n },\n [SUPPORTED_CHAINS.BASE]: {\n 1: 6,\n USDC: 6,\n },\n};\n"],"mappings":";AAAA,SAAkB,oBAAoB,aAAkB,kBAAkB;;;ACA1E,SAAc,mBAAmB;AAI1B,IAAM,eAAoB;AA2B1B,IAAM,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