@allbridge/bridge-core-sdk 3.27.0-alpha.2 → 3.27.0-alpha.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser/index.js +3 -3
- package/dist/browser/index.js.map +4 -4
- package/dist/cjs/index.js +3 -3
- package/dist/cjs/index.js.map +4 -4
- package/dist/esm/index.js +3 -3
- package/dist/esm/index.js.map +4 -4
- package/dist/src/chains/chain.enums.d.ts +7 -2
- package/dist/src/chains/chain.enums.js +5 -0
- package/dist/src/chains/chain.enums.js.map +1 -1
- package/dist/src/chains/index.js +6 -0
- package/dist/src/chains/index.js.map +1 -1
- package/dist/src/client/core-api/api-client.js +1 -0
- package/dist/src/client/core-api/api-client.js.map +1 -1
- package/dist/src/client/core-api/core-api-mapper.js +32 -0
- package/dist/src/client/core-api/core-api-mapper.js.map +1 -1
- package/dist/src/client/core-api/core-api.model.d.ts +13 -2
- package/dist/src/client/core-api/core-api.model.js.map +1 -1
- package/dist/src/configs/mainnet.js +1 -0
- package/dist/src/configs/mainnet.js.map +1 -1
- package/dist/src/index.d.ts +12 -4
- package/dist/src/index.js +11 -11
- package/dist/src/index.js.map +1 -1
- package/dist/src/models/index.d.ts +12 -4
- package/dist/src/models/index.js +4 -0
- package/dist/src/models/index.js.map +1 -1
- package/dist/src/services/bridge/alg/index.d.ts +1 -0
- package/dist/src/services/bridge/alg/index.js +79 -43
- package/dist/src/services/bridge/alg/index.js.map +1 -1
- package/dist/src/services/bridge/evm/index.d.ts +1 -0
- package/dist/src/services/bridge/evm/index.js +103 -33
- package/dist/src/services/bridge/evm/index.js.map +1 -1
- package/dist/src/services/bridge/index.d.ts +2 -2
- package/dist/src/services/bridge/index.js +15 -4
- package/dist/src/services/bridge/index.js.map +1 -1
- package/dist/src/services/bridge/models/bridge.model.d.ts +12 -4
- package/dist/src/services/bridge/models/bridge.model.js.map +1 -1
- package/dist/src/services/bridge/raw-bridge-transaction-builder.js +1 -1
- package/dist/src/services/bridge/raw-bridge-transaction-builder.js.map +1 -1
- package/dist/src/services/bridge/sol/index.d.ts +2 -2
- package/dist/src/services/bridge/sol/index.js +19 -11
- package/dist/src/services/bridge/sol/index.js.map +1 -1
- package/dist/src/services/bridge/sol/jupiter.d.ts +1 -1
- package/dist/src/services/bridge/sol/jupiter.js +2 -1
- package/dist/src/services/bridge/sol/jupiter.js.map +1 -1
- package/dist/src/services/bridge/srb/index.js +36 -28
- package/dist/src/services/bridge/srb/index.js.map +1 -1
- package/dist/src/services/bridge/stx/index.d.ts +16 -0
- package/dist/src/services/bridge/stx/index.js +136 -0
- package/dist/src/services/bridge/stx/index.js.map +1 -0
- package/dist/src/services/bridge/sui/index.js +166 -138
- package/dist/src/services/bridge/sui/index.js.map +1 -1
- package/dist/src/services/bridge/trx/index.js +98 -70
- package/dist/src/services/bridge/trx/index.js.map +1 -1
- package/dist/src/services/bridge/utils.d.ts +3 -1
- package/dist/src/services/bridge/utils.js +92 -8
- package/dist/src/services/bridge/utils.js.map +1 -1
- package/dist/src/services/liquidity-pool/alg/index.js +10 -17
- package/dist/src/services/liquidity-pool/alg/index.js.map +1 -1
- package/dist/src/services/liquidity-pool/index.js +5 -0
- package/dist/src/services/liquidity-pool/index.js.map +1 -1
- package/dist/src/services/liquidity-pool/sol/index.js +6 -3
- package/dist/src/services/liquidity-pool/sol/index.js.map +1 -1
- package/dist/src/services/liquidity-pool/stx/index.d.ts +21 -0
- package/dist/src/services/liquidity-pool/stx/index.js +141 -0
- package/dist/src/services/liquidity-pool/stx/index.js.map +1 -0
- package/dist/src/services/models/abi/PayerWithAbr.d.ts +203 -0
- package/dist/src/services/models/abi/PayerWithAbr.js +266 -0
- package/dist/src/services/models/abi/PayerWithAbr.js.map +1 -0
- package/dist/src/services/models/alg/BridgeClient.d.ts +158 -133
- package/dist/src/services/models/alg/BridgeClient.js +182 -130
- package/dist/src/services/models/alg/BridgeClient.js.map +1 -1
- package/dist/src/services/models/alg/PaddingUtilClient.d.ts +639 -0
- package/dist/src/services/models/alg/PaddingUtilClient.js +425 -0
- package/dist/src/services/models/alg/PaddingUtilClient.js.map +1 -0
- package/dist/src/services/models/alg/PoolClient.d.ts +204 -201
- package/dist/src/services/models/alg/PoolClient.js +234 -215
- package/dist/src/services/models/alg/PoolClient.js.map +1 -1
- package/dist/src/services/models/index.d.ts +16 -3
- package/dist/src/services/models/index.js.map +1 -1
- package/dist/src/services/models/stx/clarigen-types.d.ts +657 -0
- package/dist/src/services/models/stx/clarigen-types.js +2296 -0
- package/dist/src/services/models/stx/clarigen-types.js.map +1 -0
- package/dist/src/services/token/index.js +7 -2
- package/dist/src/services/token/index.js.map +1 -1
- package/dist/src/services/token/models/token.model.d.ts +4 -4
- package/dist/src/services/token/models/token.model.js.map +1 -1
- package/dist/src/services/token/stx/index.d.ts +20 -0
- package/dist/src/services/token/stx/index.js +59 -0
- package/dist/src/services/token/stx/index.js.map +1 -0
- package/dist/src/services/utils/alg/index.d.ts +1 -10
- package/dist/src/services/utils/alg/index.js +0 -20
- package/dist/src/services/utils/alg/index.js.map +1 -1
- package/dist/src/services/utils/sol/compute-budget.d.ts +2 -1
- package/dist/src/services/utils/sol/compute-budget.js +36 -18
- package/dist/src/services/utils/sol/compute-budget.js.map +1 -1
- package/dist/src/services/utils/sol/index.d.ts +2 -0
- package/dist/src/services/utils/sol/index.js +12 -0
- package/dist/src/services/utils/sol/index.js.map +1 -1
- package/dist/src/services/utils/stx/get-token-name.d.ts +2 -0
- package/dist/src/services/utils/stx/get-token-name.js +15 -0
- package/dist/src/services/utils/stx/get-token-name.js.map +1 -0
- package/dist/src/services/utils/stx/post-conditions.d.ts +3 -0
- package/dist/src/services/utils/stx/post-conditions.js +27 -0
- package/dist/src/services/utils/stx/post-conditions.js.map +1 -0
- package/dist/src/services/yield/index.js +4 -0
- package/dist/src/services/yield/index.js.map +1 -1
- package/dist/src/tokens-info/tokens-info.model.d.ts +21 -0
- package/dist/src/tokens-info/tokens-info.model.js.map +1 -1
- package/dist/src/utils/utils.d.ts +2 -0
- package/dist/src/utils/utils.js +11 -0
- package/dist/src/utils/utils.js.map +1 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/dist/src/version.js.map +1 -1
- package/package.json +6 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/services/bridge/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoDA,sCAiDC;AAED,0CAEC;AAED,kCAEC;AAED,oDAIC;AAED,oDAWC;AAED,sDAIC;AAED,0DAIC;AAWD,wDAcC;AAED,4BAEC;AAED,wCAMC;AAeD,kDA+CC;AA8BD,kDA8JC;AAqBD,4CAoCC;AAmBD,oDA+DC;AAED,oCAEC;AA1jBD,6CAA4C;AAC5C,sDAA+C;AAC/C,mDAA0D;AAC1D,mCAAwC;AACxC,8DAAsC;AACtC,qCAAgD;AAChD,yCAAsC;AACtC,yEAAiE;AAEjE,iDAO0B;AAC1B,yCAQsB;AAEtB,yDAAmH;AAwBnH,wBAAwB;AACxB,SAAgB,aAAa,CAAC,OAAe,EAAE,IAAe,EAAE,EAAa;IAC3E,IAAI,MAAc,CAAC;IACnB,QAAQ,IAAI,EAAE,CAAC;QACb,KAAK,kBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACnB,MAAM,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;YACvC,MAAM;QACR,CAAC;QACD,KAAK,kBAAS,CAAC,MAAM,CAAC,CAAC,CAAC;YACtB,MAAM,GAAG,IAAI,mBAAS,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,CAAC;YAC3C,MAAM;QACR,CAAC;QACD,KAAK,kBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACnB,MAAM,GAAG,qBAAqB,CAAC,OAAO,CAAC,CAAC;YACxC,MAAM;QACR,CAAC;QACD,KAAK,kBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YAC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,IAAA,qCAAuB,EAC3C,qBAAqB,CAAC,YAAY,CAAC,IAAI,EACvC,eAAM,CAAC,sBAAsB,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAC/D,CAAC,OAAO,EAAE;aACZ;YACD,QAAQ,EAAE;gBACR,CAAC,qBAAY,CAAC,GAAG,CAAC,EAAE,qBAAqB,CAAC,YAAY,CAAC,QAAQ;gBAC/D,CAAC,qBAAY,CAAC,KAAK,CAAC,EAAE,IAAA,qCAAuB,EAC3C,qBAAqB,CAAC,YAAY,CAAC,QAAQ,EAC3C,eAAM,CAAC,sBAAsB,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAC/D,CAAC,OAAO,EAAE;aACZ;SACF;QACD,YAAY,EAAE,uBAAuB,CAAC,YAAY;QAClD,sBAAsB,EAAE,uBAAuB,CAAC,sBAAsB;KACvE,CAAC;AACJ,CAAC;AAED,SAAgB,YAAY,CAAC,MAA+B;IAC1D,OAAO,MAAM,CAAC,WAAW,CAAC,WAAW,KAAK,MAAM,CAAC,gBAAgB,CAAC,WAAW,CAAC;AAChF,CAAC","sourcesContent":["import { PublicKey } from \"@solana/web3.js\";\nimport { Address } from \"@stellar/stellar-sdk\";\nimport algosdk, { Address as AlgoAddress } from \"algosdk\";\nimport { Big, BigSource } from \"big.js\";\nimport randomBytes from \"randombytes\";\nimport { utils as TronWebUtils } from \"tronweb\";\nimport { Chains } from \"../../chains\";\nimport { Messenger } from \"../../client/core-api/core-api.model\";\nimport { AllbridgeCoreClient } from \"../../client/core-api/core-client-base\";\nimport {\n AmountNotEnoughError,\n CCTPDoesNotSupportedError,\n ExtraGasMaxLimitExceededError,\n InvalidGasFeePaymentOptionError,\n OFTDoesNotSupportedError,\n SdkError,\n} from \"../../exceptions\";\nimport {\n AmountFormat,\n ChainType,\n ExtraGasMaxLimitResponse,\n ExtraGasMaxLimits,\n FeePaymentMethod,\n GasFeeOptions,\n SwapParams,\n} from \"../../models\";\nimport { ChainDetailsMap, TokenWithChainDetails } from \"../../tokens-info\";\nimport { convertAmountPrecision, convertFloatAmountToInt, convertIntAmountToFloat } from \"../../utils/calculation\";\nimport {\n SendParams,\n TxSendParams,\n TxSendParamsAlg,\n TxSendParamsEvm,\n TxSendParamsSol,\n TxSendParamsSrb,\n TxSendParamsSui,\n TxSendParamsTrx,\n TxSwapParams,\n TxSwapParamsEvm,\n TxSwapParamsSol,\n TxSwapParamsSrb,\n TxSwapParamsSui,\n TxSwapParamsTrx,\n} from \"./models\"; // 1. OVERLOADS\n\n// 1. OVERLOADS\nexport function formatAddress(address: string, from: ChainType, to: ChainType.EVM | ChainType.SUI): string;\nexport function formatAddress(address: string, from: ChainType, to: ChainType.TRX): Buffer;\nexport function formatAddress(address: string, from: ChainType, to: ChainType.SOLANA | ChainType.SRB): number[];\nexport function formatAddress(address: string, from: ChainType, to: ChainType): string | number[] | Buffer;\n\n// 2. COMMON Realization\nexport function formatAddress(address: string, from: ChainType, to: ChainType): string | number[] | Buffer {\n let buffer: Buffer;\n switch (from) {\n case ChainType.EVM: {\n buffer = evmAddressToBuffer32(address);\n break;\n }\n case ChainType.SOLANA: {\n buffer = new PublicKey(address).toBuffer();\n break;\n }\n case ChainType.TRX: {\n buffer = tronAddressToBuffer32(address);\n break;\n }\n case ChainType.SRB: {\n buffer = new Address(address).toBuffer();\n break;\n }\n case ChainType.SUI: {\n buffer = evmAddressToBuffer32(address);\n break;\n }\n case ChainType.ALG: {\n buffer = algAddressToBuffer32(address);\n break;\n }\n }\n\n switch (to) {\n case ChainType.EVM: {\n return \"0x\" + buffer.toString(\"hex\");\n }\n case ChainType.SOLANA: {\n return Array.from(buffer);\n }\n case ChainType.TRX: {\n return buffer;\n }\n case ChainType.SRB: {\n return buffer.toJSON().data;\n }\n case ChainType.SUI: {\n return \"0x\" + buffer.toString(\"hex\");\n }\n case ChainType.ALG: {\n return buffer;\n }\n }\n}\n\nexport function normalizeSuiHex(hex: string): string {\n return hex.replace(/^0x/i, \"\");\n}\n\nexport function hexToBuffer(hex: string): Buffer {\n return Buffer.from(hex.replace(/^0x/i, \"\"), \"hex\");\n}\n\nexport function evmAddressToBuffer32(address: string): Buffer {\n const length = 32;\n const buff = hexToBuffer(address);\n return Buffer.concat([Buffer.alloc(length - buff.length, 0), buff], length);\n}\n\nexport function algAddressToBuffer32(address: string): Buffer {\n if (algosdk.isValidAddress(address)) {\n return Buffer.from(AlgoAddress.fromString(address).publicKey);\n }\n\n if (/^\\d+$/.test(address)) {\n let hex = BigInt(address).toString(16);\n hex = hex.padStart(64, \"0\");\n return Buffer.from(hex, \"hex\");\n }\n throw new SdkError(`Unexpected Alg address: ${address}`);\n}\n\nexport function tronAddressToBuffer32(address: string): Buffer {\n const ethAddress = tronAddressToEthAddress(address);\n const buffer = hexToBuffer(ethAddress);\n return bufferToSize(buffer, 32);\n}\n\nexport function tronAddressToEthAddress(address: string): string {\n const bytes = TronWebUtils.crypto.decodeBase58Address(address);\n if (!bytes) return \"\";\n return TronWebUtils.bytes.byteArray2hexStr(bytes).replace(/^41/, \"0x\");\n}\n\nfunction bufferToSize(buffer: Buffer, size: number): Buffer {\n if (buffer.length >= size) {\n return buffer;\n }\n const result = Buffer.alloc(size, 0);\n buffer.copy(result, size - buffer.length);\n return result;\n}\n\nexport function getTokenByTokenAddress(\n chainDetailsMap: ChainDetailsMap,\n chainSymbol: string,\n tokenAddress: string\n): TokenWithChainDetails {\n const chainDetail = chainDetailsMap[chainSymbol];\n if (!chainDetail) {\n throw new SdkError(\"Cannot find chain detail for \" + chainSymbol);\n }\n const token = chainDetail.tokens.find((value) => value.tokenAddress.toUpperCase() === tokenAddress.toUpperCase());\n if (!token) {\n throw new SdkError(\"Cannot find token info about token \" + tokenAddress + \" on chain \" + chainSymbol);\n }\n return token;\n}\n\nexport function getNonce(): Buffer {\n return randomBytes(32);\n}\n\nexport function getNonceBigInt(): bigint {\n const bigint = randomBytes(32).readBigInt64BE();\n if (bigint < 0) {\n return bigint * -1n;\n }\n return bigint;\n}\n\n// 1. OVERLOADS\nexport function prepareTxSwapParams(\n bridgeChainType: ChainType.EVM | ChainType.SUI,\n params: SwapParams\n): TxSwapParamsEvm | TxSwapParamsSui;\nexport function prepareTxSwapParams(bridgeChainType: ChainType.TRX, params: SwapParams): TxSwapParamsTrx;\nexport function prepareTxSwapParams(\n bridgeChainType: ChainType.SOLANA | ChainType.SRB,\n params: SwapParams\n): TxSwapParamsSol | TxSwapParamsSrb;\nexport function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapParams): TxSwapParams;\n\n// 2. COMMON Realization\nexport function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapParams): TxSwapParams {\n const txSwapParams = {} as TxSwapParams;\n const sourceToken = params.sourceToken;\n txSwapParams.amount = convertFloatAmountToInt(params.amount, sourceToken.decimals).toFixed();\n txSwapParams.contractAddress = sourceToken.bridgeAddress;\n txSwapParams.fromAccountAddress = params.fromAccountAddress;\n switch (bridgeChainType) {\n case ChainType.SUI: {\n if (!sourceToken.originTokenAddress) {\n throw new SdkError(\"SUI sourceToken must contain 'originTokenAddress'\");\n }\n txSwapParams.fromTokenAddress = sourceToken.originTokenAddress;\n break;\n }\n case ChainType.ALG: {\n txSwapParams.fromTokenAddress = sourceToken.tokenAddress;\n break;\n }\n default: {\n txSwapParams.fromTokenAddress = formatAddress(sourceToken.tokenAddress, bridgeChainType, bridgeChainType);\n }\n }\n txSwapParams.toAccountAddress = params.toAccountAddress;\n switch (bridgeChainType) {\n case ChainType.SUI: {\n if (!params.destinationToken.originTokenAddress) {\n throw new SdkError(\"SUI destinationToken must contain 'originTokenAddress'\");\n }\n txSwapParams.toTokenAddress = params.destinationToken.originTokenAddress;\n break;\n }\n case ChainType.ALG: {\n txSwapParams.toTokenAddress = params.destinationToken.tokenAddress;\n break;\n }\n default: {\n txSwapParams.toTokenAddress = formatAddress(\n params.destinationToken.tokenAddress,\n bridgeChainType,\n bridgeChainType\n );\n }\n }\n txSwapParams.minimumReceiveAmount = params.minimumReceiveAmount\n ? convertFloatAmountToInt(params.minimumReceiveAmount, params.destinationToken.decimals).toFixed()\n : \"0\";\n return txSwapParams;\n}\n\n// 1. OVERLOADS\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.EVM | ChainType.SUI,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsEvm | TxSendParamsSui>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.TRX,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsTrx>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.ALG,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsAlg>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.SOLANA | ChainType.SRB,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsSol | TxSendParamsSrb>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParams>;\n\n// 2. COMMON Realization\nexport async function prepareTxSendParams(\n bridgeChainType: ChainType,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParams> {\n const txSendParams = {} as TxSendParams;\n\n txSendParams.fromChainId = params.sourceToken.allbridgeChainId;\n txSendParams.fromChainSymbol = params.sourceToken.chainSymbol;\n const toChainType = Chains.getChainProperty(params.destinationToken.chainSymbol).chainType;\n if (bridgeChainType === ChainType.SUI) {\n if (!params.sourceToken.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n txSendParams.fromTokenAddress = params.sourceToken.originTokenAddress;\n } else {\n txSendParams.fromTokenAddress = params.sourceToken.tokenAddress;\n }\n\n txSendParams.toChainId = params.destinationToken.allbridgeChainId;\n txSendParams.toTokenAddress = params.destinationToken.tokenAddress;\n\n if (params.gasFeePaymentMethod === FeePaymentMethod.WITH_STABLECOIN) {\n txSendParams.gasFeePaymentMethod = FeePaymentMethod.WITH_STABLECOIN;\n } else {\n // default FeePaymentMethod.WITH_NATIVE_CURRENCY\n txSendParams.gasFeePaymentMethod = FeePaymentMethod.WITH_NATIVE_CURRENCY;\n }\n const sourceToken = params.sourceToken;\n\n switch (params.messenger) {\n case Messenger.CCTP:\n if (!sourceToken.cctpAddress || !params.destinationToken.cctpAddress) {\n throw new CCTPDoesNotSupportedError(\"Such route does not support CCTP protocol\");\n }\n txSendParams.contractAddress = sourceToken.cctpAddress;\n break;\n case Messenger.CCTP_V2:\n if (!sourceToken.cctpV2Address || !params.destinationToken.cctpV2Address) {\n throw new CCTPDoesNotSupportedError(\"Such route does not support CCTP V2 protocol\");\n }\n txSendParams.contractAddress = sourceToken.cctpV2Address;\n\n break;\n case Messenger.OFT:\n if (\n !sourceToken.oftBridgeAddress ||\n !params.destinationToken.oftBridgeAddress ||\n sourceToken.oftId !== params.destinationToken.oftId\n ) {\n throw new OFTDoesNotSupportedError(\"Such route does not support OFT protocol\");\n }\n txSendParams.contractAddress = sourceToken.oftBridgeAddress;\n break;\n case Messenger.ALLBRIDGE:\n case Messenger.WORMHOLE:\n txSendParams.contractAddress = sourceToken.bridgeAddress;\n break;\n }\n\n txSendParams.messenger = params.messenger;\n txSendParams.fromAccountAddress = params.fromAccountAddress;\n txSendParams.amount = convertFloatAmountToInt(params.amount, sourceToken.decimals).toFixed();\n\n //Fee\n let { fee, feeFormat } = params;\n if (!fee) {\n const gasFeeOptions = await getGasFeeOptions(\n params.sourceToken,\n txSendParams.toChainId,\n txSendParams.messenger,\n api\n );\n\n const gasFeeOption = gasFeeOptions[txSendParams.gasFeePaymentMethod];\n if (!gasFeeOption) {\n throw new InvalidGasFeePaymentOptionError();\n }\n fee = gasFeeOption[AmountFormat.INT];\n feeFormat = AmountFormat.INT;\n }\n if (feeFormat == AmountFormat.FLOAT) {\n switch (txSendParams.gasFeePaymentMethod) {\n case FeePaymentMethod.WITH_NATIVE_CURRENCY:\n txSendParams.fee = convertFloatAmountToInt(fee, Chains.getChainDecimalsByType(sourceToken.chainType)).toFixed(\n 0\n );\n break;\n case FeePaymentMethod.WITH_STABLECOIN:\n txSendParams.fee = convertFloatAmountToInt(fee, sourceToken.decimals).toFixed(0);\n break;\n }\n } else {\n txSendParams.fee = fee;\n }\n\n //ExtraGas\n const { extraGas, extraGasFormat } = params;\n if (extraGas && +extraGas > 0) {\n const extraGasLimits = await getExtraGasMaxLimits(\n sourceToken,\n params.destinationToken,\n txSendParams.messenger,\n api\n );\n\n let extraGasDecimals: number;\n let extraGasDestRate: Big;\n switch (txSendParams.gasFeePaymentMethod) {\n case FeePaymentMethod.WITH_NATIVE_CURRENCY:\n extraGasDecimals = Chains.getChainDecimalsByType(sourceToken.chainType);\n extraGasDestRate = Big(extraGasLimits.exchangeRate);\n break;\n case FeePaymentMethod.WITH_STABLECOIN:\n extraGasDecimals = sourceToken.decimals;\n extraGasDestRate = Big(extraGasLimits.exchangeRate).div(extraGasLimits.sourceNativeTokenPrice);\n break;\n }\n\n switch (extraGasFormat ?? AmountFormat.INT) {\n case AmountFormat.FLOAT: {\n txSendParams.extraGas = convertFloatAmountToInt(extraGas, extraGasDecimals).toFixed(0);\n\n const extraGasDestFloat = extraGasDestRate.mul(extraGas);\n txSendParams.extraGasDest = convertFloatAmountToInt(\n extraGasDestFloat,\n Chains.getChainDecimalsByType(params.destinationToken.chainType)\n ).toFixed(0, Big.roundDown);\n break;\n }\n case AmountFormat.INT: {\n txSendParams.extraGas = extraGas;\n\n const extraGasFloat = convertIntAmountToFloat(\n txSendParams.extraGas,\n Chains.getChainDecimalsByType(sourceToken.chainType)\n );\n const extraGasDestFloat = extraGasDestRate.mul(extraGasFloat);\n txSendParams.extraGasDest = convertFloatAmountToInt(\n extraGasDestFloat,\n Chains.getChainDecimalsByType(params.destinationToken.chainType)\n ).toFixed(0, Big.roundDown);\n break;\n }\n }\n\n validateExtraGasNotExceeded(txSendParams.extraGas, txSendParams.gasFeePaymentMethod, extraGasLimits);\n }\n\n if (![ChainType.SUI, ChainType.ALG].includes(bridgeChainType)) {\n txSendParams.fromTokenAddress = formatAddress(txSendParams.fromTokenAddress, bridgeChainType, bridgeChainType);\n }\n txSendParams.toAccountAddress = formatAddress(params.toAccountAddress, toChainType, bridgeChainType);\n txSendParams.toTokenAddress = formatAddress(txSendParams.toTokenAddress, toChainType, bridgeChainType);\n if (txSendParams.gasFeePaymentMethod == FeePaymentMethod.WITH_STABLECOIN) {\n validateAmountEnough(txSendParams.amount, sourceToken.decimals, txSendParams.fee, txSendParams.extraGas);\n }\n return txSendParams;\n}\n\nfunction validateAmountEnough(\n amountInt: BigSource,\n decimals: number,\n feeInt: BigSource,\n extraGasInt: BigSource | undefined\n) {\n const amountTotal = Big(amountInt)\n .minus(feeInt)\n .minus(extraGasInt ?? 0);\n if (amountTotal.lte(0)) {\n throw new AmountNotEnoughError(\n `Amount not enough to pay fee, ${convertIntAmountToFloat(\n Big(amountTotal).minus(1).neg(),\n decimals\n ).toFixed()} stables is missing`\n );\n }\n}\n\nexport async function getGasFeeOptions(\n sourceChainToken: TokenWithChainDetails,\n destinationAllbridgeChainId: number,\n messenger: Messenger,\n api: AllbridgeCoreClient\n): Promise<GasFeeOptions> {\n const transactionCostResponse = await api.getReceiveTransactionCost({\n sourceChainId: sourceChainToken.allbridgeChainId,\n destinationChainId: destinationAllbridgeChainId,\n messenger,\n sourceToken: sourceChainToken.tokenAddress,\n });\n\n const gasFeeOptions: GasFeeOptions = {\n [FeePaymentMethod.WITH_NATIVE_CURRENCY]: {\n [AmountFormat.INT]: transactionCostResponse.fee,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n transactionCostResponse.fee,\n Chains.getChainDecimalsByType(sourceChainToken.chainType)\n ).toFixed(),\n },\n adminFeeShareWithExtras: transactionCostResponse.adminFeeShareWithExtras,\n };\n if (transactionCostResponse.sourceNativeTokenPrice) {\n const gasFeeIntWithStables = convertAmountPrecision(\n new Big(transactionCostResponse.fee).mul(transactionCostResponse.sourceNativeTokenPrice),\n Chains.getChainDecimalsByType(sourceChainToken.chainType),\n sourceChainToken.decimals\n ).toFixed(0, Big.roundUp);\n gasFeeOptions[FeePaymentMethod.WITH_STABLECOIN] = {\n [AmountFormat.INT]: gasFeeIntWithStables,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(gasFeeIntWithStables, sourceChainToken.decimals).toFixed(),\n };\n }\n\n return gasFeeOptions;\n}\n\nfunction validateExtraGasNotExceeded(\n extraGasInt: string,\n gasFeePaymentMethod: FeePaymentMethod,\n extraGasLimits: ExtraGasMaxLimitResponse\n) {\n const extraGasMaxLimit = extraGasLimits.extraGasMax[gasFeePaymentMethod];\n if (!extraGasMaxLimit) {\n throw new InvalidGasFeePaymentOptionError(`Impossible to pay extra gas by '${gasFeePaymentMethod}' payment method`);\n }\n const extraGasMaxIntLimit = extraGasMaxLimit[AmountFormat.INT];\n if (Big(extraGasInt).gt(extraGasMaxIntLimit)) {\n throw new ExtraGasMaxLimitExceededError(\n `Extra gas ${extraGasInt} in int format, exceeded limit ${extraGasMaxIntLimit} for '${gasFeePaymentMethod}' payment method`\n );\n }\n}\n\nexport async function getExtraGasMaxLimits(\n sourceChainToken: TokenWithChainDetails,\n destinationChainToken: TokenWithChainDetails,\n messenger: Messenger,\n api: AllbridgeCoreClient\n): Promise<ExtraGasMaxLimitResponse> {\n const extraGasMaxLimits: ExtraGasMaxLimits = {};\n const transactionCostResponse = await api.getReceiveTransactionCost({\n sourceChainId: sourceChainToken.allbridgeChainId,\n destinationChainId: destinationChainToken.allbridgeChainId,\n messenger,\n sourceToken: sourceChainToken.tokenAddress,\n });\n const maxAmount = destinationChainToken.txCostAmount.maxAmount;\n const maxAmountFloat = convertIntAmountToFloat(\n maxAmount,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed();\n const maxAmountFloatInSourceNative = Big(maxAmountFloat)\n .div(transactionCostResponse.exchangeRate)\n .toFixed(Chains.getChainDecimalsByType(sourceChainToken.chainType), Big.roundDown);\n const maxAmountInSourceNative = convertFloatAmountToInt(\n maxAmountFloatInSourceNative,\n Chains.getChainDecimalsByType(sourceChainToken.chainType)\n ).toFixed(0);\n extraGasMaxLimits[FeePaymentMethod.WITH_NATIVE_CURRENCY] = {\n [AmountFormat.INT]: maxAmountInSourceNative,\n [AmountFormat.FLOAT]: maxAmountFloatInSourceNative,\n };\n if (transactionCostResponse.sourceNativeTokenPrice) {\n const maxAmountFloatInStable = Big(maxAmountFloatInSourceNative)\n .mul(transactionCostResponse.sourceNativeTokenPrice)\n .toFixed(sourceChainToken.decimals, Big.roundDown);\n extraGasMaxLimits[FeePaymentMethod.WITH_STABLECOIN] = {\n [AmountFormat.INT]: convertFloatAmountToInt(maxAmountFloatInStable, sourceChainToken.decimals).toFixed(0),\n [AmountFormat.FLOAT]: maxAmountFloatInStable,\n };\n }\n return {\n extraGasMax: extraGasMaxLimits,\n destinationChain: {\n gasAmountMax: {\n [AmountFormat.INT]: maxAmount,\n [AmountFormat.FLOAT]: maxAmountFloat,\n },\n swap: {\n [AmountFormat.INT]: destinationChainToken.txCostAmount.swap,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n destinationChainToken.txCostAmount.swap,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed(),\n },\n transfer: {\n [AmountFormat.INT]: destinationChainToken.txCostAmount.transfer,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n destinationChainToken.txCostAmount.transfer,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed(),\n },\n },\n exchangeRate: transactionCostResponse.exchangeRate,\n sourceNativeTokenPrice: transactionCostResponse.sourceNativeTokenPrice,\n };\n}\n\nexport function isSendParams(params: SwapParams | SendParams): params is SendParams {\n return params.sourceToken.chainSymbol !== params.destinationToken.chainSymbol;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/services/bridge/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,sCAwDC;AAED,0CAEC;AAED,kCAEC;AAED,oDAIC;AAED,oDAWC;AAED,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D,CAAC,qBAAY,CAAC,KAAK,CAAC,EAAE,IAAA,qCAAuB,EAC3C,qBAAqB,CAAC,YAAY,CAAC,IAAI,EACvC,eAAM,CAAC,sBAAsB,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAC/D,CAAC,OAAO,EAAE;aACZ;YACD,QAAQ,EAAE;gBACR,CAAC,qBAAY,CAAC,GAAG,CAAC,EAAE,qBAAqB,CAAC,YAAY,CAAC,QAAQ;gBAC/D,CAAC,qBAAY,CAAC,KAAK,CAAC,EAAE,IAAA,qCAAuB,EAC3C,qBAAqB,CAAC,YAAY,CAAC,QAAQ,EAC3C,eAAM,CAAC,sBAAsB,CAAC,qBAAqB,CAAC,SAAS,CAAC,CAC/D,CAAC,OAAO,EAAE;aACZ;SACF;QACD,YAAY,EAAE,uBAAuB,CAAC,YAAY;QAClD,eAAe,EAAE,YAAY,CAAC,CAAC,CAAC,uBAAuB,CAAC,eAAe,CAAC,CAAC,CAAC,SAAS;QACnF,sBAAsB,EAAE,uBAAuB,CAAC,sBAAsB;KACvE,CAAC;AACJ,CAAC;AAED,SAAgB,YAAY,CAAC,MAA+B;IAC1D,OAAO,MAAM,CAAC,WAAW,CAAC,WAAW,KAAK,MAAM,CAAC,gBAAgB,CAAC,WAAW,CAAC;AAChF,CAAC","sourcesContent":["import { PublicKey } from \"@solana/web3.js\";\nimport { ContractIdString, createAddress, parseContractId } from \"@stacks/transactions\";\nimport { Address } from \"@stellar/stellar-sdk\";\nimport algosdk, { Address as AlgoAddress } from \"algosdk\";\nimport { Big, BigSource } from \"big.js\";\nimport randomBytes from \"randombytes\";\nimport { utils as TronWebUtils } from \"tronweb\";\nimport { Web3 } from \"web3\";\nimport { Chains } from \"../../chains\";\nimport { Messenger } from \"../../client/core-api/core-api.model\";\nimport { AllbridgeCoreClient } from \"../../client/core-api/core-client-base\";\nimport {\n AmountNotEnoughError,\n CCTPDoesNotSupportedError,\n ExtraGasMaxLimitExceededError,\n InvalidGasFeePaymentOptionError,\n OFTDoesNotSupportedError,\n SdkError,\n} from \"../../exceptions\";\nimport {\n AmountFormat,\n ChainType,\n ExtraGasMaxLimitResponse,\n ExtraGasMaxLimits,\n FeePaymentMethod,\n GasFeeOptions,\n SwapParams,\n} from \"../../models\";\nimport { ChainDetailsMap, TokenWithChainDetails } from \"../../tokens-info\";\nimport { convertAmountPrecision, convertFloatAmountToInt, convertIntAmountToFloat } from \"../../utils/calculation\";\nimport { assertNever } from \"../../utils/utils\";\nimport {\n SendParams,\n TxSendParams,\n TxSendParamsAlg,\n TxSendParamsEvm,\n TxSendParamsSol,\n TxSendParamsSrb,\n TxSendParamsStx,\n TxSendParamsSui,\n TxSendParamsTrx,\n TxSwapParams,\n TxSwapParamsEvm,\n TxSwapParamsSol,\n TxSwapParamsSrb,\n TxSwapParamsSui,\n TxSwapParamsTrx,\n} from \"./models\";\n\n// 1. OVERLOADS\nexport function formatAddress(address: string, from: ChainType, to: ChainType.EVM | ChainType.SUI): string;\nexport function formatAddress(address: string, from: ChainType, to: ChainType.TRX): Buffer;\nexport function formatAddress(address: string, from: ChainType, to: ChainType.SOLANA | ChainType.SRB): number[];\nexport function formatAddress(address: string, from: ChainType, to: ChainType): string | number[] | Buffer;\n\n// 2. COMMON Realization\nexport function formatAddress(address: string, from: ChainType, to: ChainType): string | number[] | Buffer {\n let buffer: Buffer;\n switch (from) {\n case ChainType.EVM: {\n buffer = evmAddressToBuffer32(address);\n break;\n }\n case ChainType.SOLANA: {\n buffer = new PublicKey(address).toBuffer();\n break;\n }\n case ChainType.TRX: {\n buffer = tronAddressToBuffer32(address);\n break;\n }\n case ChainType.SRB: {\n buffer = new Address(address).toBuffer();\n break;\n }\n case ChainType.SUI: {\n buffer = evmAddressToBuffer32(address);\n break;\n }\n case ChainType.ALG: {\n buffer = algAddressToBuffer32(address);\n break;\n }\n case ChainType.STX: {\n buffer = stxAddressToBuffer32(address);\n break;\n }\n }\n\n switch (to) {\n case ChainType.EVM: {\n return \"0x\" + buffer.toString(\"hex\");\n }\n case ChainType.SOLANA: {\n return Array.from(buffer);\n }\n case ChainType.TRX: {\n return buffer;\n }\n case ChainType.SRB: {\n return buffer.toJSON().data;\n }\n case ChainType.SUI: {\n return \"0x\" + buffer.toString(\"hex\");\n }\n case ChainType.ALG: {\n return buffer;\n }\n case ChainType.STX: {\n return buffer;\n }\n }\n}\n\nexport function normalizeSuiHex(hex: string): string {\n return hex.replace(/^0x/i, \"\");\n}\n\nexport function hexToBuffer(hex: string): Buffer {\n return Buffer.from(hex.replace(/^0x/i, \"\"), \"hex\");\n}\n\nexport function evmAddressToBuffer32(address: string): Buffer {\n const length = 32;\n const buff = hexToBuffer(address);\n return Buffer.concat([Buffer.alloc(length - buff.length, 0), buff], length);\n}\n\nexport function algAddressToBuffer32(address: string): Buffer {\n if (algosdk.isValidAddress(address)) {\n return Buffer.from(AlgoAddress.fromString(address).publicKey);\n }\n\n if (/^\\d+$/.test(address)) {\n let hex = BigInt(address).toString(16);\n hex = hex.padStart(64, \"0\");\n return Buffer.from(hex, \"hex\");\n }\n throw new SdkError(`Unexpected Alg address: ${address}`);\n}\n\nexport function stxAddressToBuffer32(address: string): Buffer {\n if (address.includes(\".\")) {\n const [addr, name] = parseContractId(address as ContractIdString);\n if (!addr || !name) {\n throw new SdkError(`Unexpected Alg address: ${address}`);\n }\n const hashBytes = Buffer.from(createAddress(addr).hash160, \"hex\");\n const hash = Web3.utils.keccak256(Buffer.concat([hashBytes, Buffer.from(name)]));\n return hexToBuffer(hash);\n }\n\n const hashBytes = Buffer.from(createAddress(address).hash160, \"hex\");\n return bufferToSize(hashBytes, 32);\n}\n\nexport function tronAddressToBuffer32(address: string): Buffer {\n const ethAddress = tronAddressToEthAddress(address);\n const buffer = hexToBuffer(ethAddress);\n return bufferToSize(buffer, 32);\n}\n\nexport function tronAddressToEthAddress(address: string): string {\n const bytes = TronWebUtils.crypto.decodeBase58Address(address);\n if (!bytes) return \"\";\n return TronWebUtils.bytes.byteArray2hexStr(bytes).replace(/^41/, \"0x\");\n}\n\nfunction bufferToSize(buffer: Buffer, size: number): Buffer {\n if (buffer.length >= size) {\n return buffer;\n }\n const result = Buffer.alloc(size, 0);\n buffer.copy(result, size - buffer.length);\n return result;\n}\n\nexport function getTokenByTokenAddress(\n chainDetailsMap: ChainDetailsMap,\n chainSymbol: string,\n tokenAddress: string\n): TokenWithChainDetails {\n const chainDetail = chainDetailsMap[chainSymbol];\n if (!chainDetail) {\n throw new SdkError(\"Cannot find chain detail for \" + chainSymbol);\n }\n const token = chainDetail.tokens.find((value) => value.tokenAddress.toUpperCase() === tokenAddress.toUpperCase());\n if (!token) {\n throw new SdkError(\"Cannot find token info about token \" + tokenAddress + \" on chain \" + chainSymbol);\n }\n return token;\n}\n\nexport function getNonce(): Buffer {\n return randomBytes(32);\n}\n\nexport function getNonceBigInt(): bigint {\n const bigint = randomBytes(32).readBigInt64BE();\n if (bigint < 0) {\n return bigint * -1n;\n }\n return bigint;\n}\n\n// 1. OVERLOADS\nexport function prepareTxSwapParams(\n bridgeChainType: ChainType.EVM | ChainType.SUI,\n params: SwapParams\n): TxSwapParamsEvm | TxSwapParamsSui;\nexport function prepareTxSwapParams(bridgeChainType: ChainType.TRX, params: SwapParams): TxSwapParamsTrx;\nexport function prepareTxSwapParams(\n bridgeChainType: ChainType.SOLANA | ChainType.SRB,\n params: SwapParams\n): TxSwapParamsSol | TxSwapParamsSrb;\nexport function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapParams): TxSwapParams;\n\n// 2. COMMON Realization\nexport function prepareTxSwapParams(bridgeChainType: ChainType, params: SwapParams): TxSwapParams {\n const txSwapParams = {} as TxSwapParams;\n const sourceToken = params.sourceToken;\n txSwapParams.amount = convertFloatAmountToInt(params.amount, sourceToken.decimals).toFixed();\n txSwapParams.contractAddress = sourceToken.bridgeAddress;\n txSwapParams.fromAccountAddress = params.fromAccountAddress;\n switch (bridgeChainType) {\n case ChainType.SUI: {\n if (!sourceToken.originTokenAddress) {\n throw new SdkError(\"SUI sourceToken must contain 'originTokenAddress'\");\n }\n txSwapParams.fromTokenAddress = sourceToken.originTokenAddress;\n break;\n }\n case ChainType.ALG: {\n txSwapParams.fromTokenAddress = sourceToken.tokenAddress;\n break;\n }\n default: {\n txSwapParams.fromTokenAddress = formatAddress(sourceToken.tokenAddress, bridgeChainType, bridgeChainType);\n }\n }\n txSwapParams.toAccountAddress = params.toAccountAddress;\n switch (bridgeChainType) {\n case ChainType.SUI: {\n if (!params.destinationToken.originTokenAddress) {\n throw new SdkError(\"SUI destinationToken must contain 'originTokenAddress'\");\n }\n txSwapParams.toTokenAddress = params.destinationToken.originTokenAddress;\n break;\n }\n case ChainType.ALG: {\n txSwapParams.toTokenAddress = params.destinationToken.tokenAddress;\n break;\n }\n default: {\n txSwapParams.toTokenAddress = formatAddress(\n params.destinationToken.tokenAddress,\n bridgeChainType,\n bridgeChainType\n );\n }\n }\n txSwapParams.minimumReceiveAmount = params.minimumReceiveAmount\n ? convertFloatAmountToInt(params.minimumReceiveAmount, params.destinationToken.decimals).toFixed()\n : \"0\";\n return txSwapParams;\n}\n\n// 1. OVERLOADS\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.EVM | ChainType.SUI,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsEvm | TxSendParamsSui>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.TRX,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsTrx>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.ALG,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsAlg>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.STX,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsStx>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType.SOLANA | ChainType.SRB,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParamsSol | TxSendParamsSrb>;\nexport function prepareTxSendParams(\n bridgeChainType: ChainType,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParams>;\n\n// 2. COMMON Realization\nexport async function prepareTxSendParams(\n bridgeChainType: ChainType,\n params: SendParams,\n api: AllbridgeCoreClient\n): Promise<TxSendParams> {\n const txSendParams = {} as TxSendParams;\n\n txSendParams.fromChainId = params.sourceToken.allbridgeChainId;\n txSendParams.fromChainSymbol = params.sourceToken.chainSymbol;\n const toChainType = Chains.getChainProperty(params.destinationToken.chainSymbol).chainType;\n if (bridgeChainType === ChainType.SUI) {\n if (!params.sourceToken.originTokenAddress) {\n throw new SdkError(\"SUI token must contain 'originTokenAddress'\");\n }\n txSendParams.fromTokenAddress = params.sourceToken.originTokenAddress;\n } else {\n txSendParams.fromTokenAddress = params.sourceToken.tokenAddress;\n }\n\n txSendParams.toChainId = params.destinationToken.allbridgeChainId;\n txSendParams.toTokenAddress = params.destinationToken.tokenAddress;\n\n txSendParams.gasFeePaymentMethod = params.gasFeePaymentMethod ?? FeePaymentMethod.WITH_NATIVE_CURRENCY;\n if (txSendParams.gasFeePaymentMethod === FeePaymentMethod.WITH_ARB) {\n if (!params.sourceToken.abrPayer) {\n throw new SdkError(\"Source token must contain 'abrPayer' for ARB0 payment method\");\n }\n }\n\n const sourceToken = params.sourceToken;\n\n switch (params.messenger) {\n case Messenger.CCTP:\n if (!sourceToken.cctpAddress || !params.destinationToken.cctpAddress) {\n throw new CCTPDoesNotSupportedError(\"Such route does not support CCTP protocol\");\n }\n txSendParams.contractAddress = sourceToken.cctpAddress;\n break;\n case Messenger.CCTP_V2:\n if (!sourceToken.cctpV2Address || !params.destinationToken.cctpV2Address) {\n throw new CCTPDoesNotSupportedError(\"Such route does not support CCTP V2 protocol\");\n }\n txSendParams.contractAddress = sourceToken.cctpV2Address;\n\n break;\n case Messenger.OFT:\n if (\n !sourceToken.oftBridgeAddress ||\n !params.destinationToken.oftBridgeAddress ||\n sourceToken.oftId !== params.destinationToken.oftId\n ) {\n throw new OFTDoesNotSupportedError(\"Such route does not support OFT protocol\");\n }\n txSendParams.contractAddress = sourceToken.oftBridgeAddress;\n break;\n case Messenger.ALLBRIDGE:\n case Messenger.WORMHOLE:\n txSendParams.contractAddress = sourceToken.bridgeAddress;\n break;\n }\n\n txSendParams.messenger = params.messenger;\n txSendParams.fromAccountAddress = params.fromAccountAddress;\n txSendParams.amount = convertFloatAmountToInt(params.amount, sourceToken.decimals).toFixed();\n\n //Fee\n let { fee, feeFormat } = params;\n if (!fee) {\n const gasFeeOptions = await getGasFeeOptions(\n params.sourceToken,\n txSendParams.toChainId,\n txSendParams.messenger,\n api\n );\n\n const gasFeeOption = gasFeeOptions[txSendParams.gasFeePaymentMethod];\n if (!gasFeeOption) {\n throw new InvalidGasFeePaymentOptionError();\n }\n fee = gasFeeOption[AmountFormat.INT];\n feeFormat = AmountFormat.INT;\n }\n if (feeFormat == AmountFormat.FLOAT) {\n switch (txSendParams.gasFeePaymentMethod) {\n case FeePaymentMethod.WITH_NATIVE_CURRENCY:\n txSendParams.fee = convertFloatAmountToInt(fee, Chains.getChainDecimalsByType(sourceToken.chainType)).toFixed(\n 0\n );\n break;\n case FeePaymentMethod.WITH_STABLECOIN:\n txSendParams.fee = convertFloatAmountToInt(fee, sourceToken.decimals).toFixed(0);\n break;\n case FeePaymentMethod.WITH_ARB:\n if (!sourceToken.abrPayer) {\n throw new SdkError(\"Source token must contain 'abrPayer' for ARB0 payment method\");\n }\n txSendParams.fee = convertFloatAmountToInt(fee, sourceToken.abrPayer.abrToken.decimals).toFixed(0);\n break;\n default: {\n return assertNever(txSendParams.gasFeePaymentMethod, \"Unhandled FeePaymentMethod\");\n }\n }\n } else {\n txSendParams.fee = fee;\n }\n\n //ExtraGas\n const { extraGas, extraGasFormat } = params;\n if (extraGas && +extraGas > 0) {\n const extraGasLimits = await getExtraGasMaxLimits(\n sourceToken,\n params.destinationToken,\n txSendParams.messenger,\n api\n );\n\n let extraGasDecimals: number;\n let extraGasDestRate: Big;\n switch (txSendParams.gasFeePaymentMethod) {\n case FeePaymentMethod.WITH_NATIVE_CURRENCY:\n extraGasDecimals = Chains.getChainDecimalsByType(sourceToken.chainType);\n extraGasDestRate = Big(extraGasLimits.exchangeRate);\n break;\n case FeePaymentMethod.WITH_STABLECOIN:\n extraGasDecimals = sourceToken.decimals;\n extraGasDestRate = Big(extraGasLimits.exchangeRate).div(extraGasLimits.sourceNativeTokenPrice);\n break;\n case FeePaymentMethod.WITH_ARB:\n if (!sourceToken.abrPayer) {\n throw new SdkError(\"Source token must contain 'abrPayer' for ARB0 payment method\");\n }\n if (!extraGasLimits.abrExchangeRate) {\n throw new SdkError(\"Cannot transfer WITH_ARB option\");\n }\n extraGasDecimals = sourceToken.abrPayer.abrToken.decimals;\n extraGasDestRate = Big(extraGasLimits.exchangeRate).div(extraGasLimits.abrExchangeRate);\n break;\n default: {\n return assertNever(txSendParams.gasFeePaymentMethod, \"Unhandled FeePaymentMethod\");\n }\n }\n\n switch (extraGasFormat ?? AmountFormat.INT) {\n case AmountFormat.FLOAT: {\n txSendParams.extraGas = convertFloatAmountToInt(extraGas, extraGasDecimals).toFixed(0);\n\n const extraGasDestFloat = extraGasDestRate.mul(extraGas);\n txSendParams.extraGasDest = convertFloatAmountToInt(\n extraGasDestFloat,\n Chains.getChainDecimalsByType(params.destinationToken.chainType)\n ).toFixed(0, Big.roundDown);\n break;\n }\n case AmountFormat.INT: {\n txSendParams.extraGas = extraGas;\n\n const extraGasFloat = convertIntAmountToFloat(\n txSendParams.extraGas,\n Chains.getChainDecimalsByType(sourceToken.chainType)\n );\n const extraGasDestFloat = extraGasDestRate.mul(extraGasFloat);\n txSendParams.extraGasDest = convertFloatAmountToInt(\n extraGasDestFloat,\n Chains.getChainDecimalsByType(params.destinationToken.chainType)\n ).toFixed(0, Big.roundDown);\n break;\n }\n }\n validateExtraGasNotExceeded(txSendParams.extraGas, txSendParams.gasFeePaymentMethod, extraGasLimits);\n }\n\n if (![ChainType.SUI, ChainType.ALG].includes(bridgeChainType)) {\n txSendParams.fromTokenAddress = formatAddress(txSendParams.fromTokenAddress, bridgeChainType, bridgeChainType);\n }\n txSendParams.toAccountAddress = formatAddress(params.toAccountAddress, toChainType, bridgeChainType);\n txSendParams.toTokenAddress = formatAddress(txSendParams.toTokenAddress, toChainType, bridgeChainType);\n\n switch (txSendParams.gasFeePaymentMethod) {\n case FeePaymentMethod.WITH_NATIVE_CURRENCY:\n break;\n case FeePaymentMethod.WITH_STABLECOIN:\n validateAmountEnough(txSendParams.amount, sourceToken.decimals, txSendParams.fee, txSendParams.extraGas);\n break;\n case FeePaymentMethod.WITH_ARB: {\n const { abrExchangeRate } = await api.getReceiveTransactionCost({\n sourceChainId: txSendParams.fromChainId,\n destinationChainId: txSendParams.toChainId,\n messenger: txSendParams.messenger,\n sourceToken: params.sourceToken.tokenAddress,\n });\n txSendParams.abrExchangeRate = abrExchangeRate;\n break;\n }\n default:\n return assertNever(txSendParams.gasFeePaymentMethod, \"Unhandled FeePaymentMethod\");\n }\n return txSendParams;\n}\n\nfunction validateAmountEnough(\n amountInt: BigSource,\n decimals: number,\n feeInt: BigSource,\n extraGasInt: BigSource | undefined\n) {\n const amountTotal = Big(amountInt)\n .minus(feeInt)\n .minus(extraGasInt ?? 0);\n if (amountTotal.lte(0)) {\n throw new AmountNotEnoughError(\n `Amount not enough to pay fee, ${convertIntAmountToFloat(\n Big(amountTotal).minus(1).neg(),\n decimals\n ).toFixed()} stables is missing`\n );\n }\n}\n\nexport async function getGasFeeOptions(\n sourceChainToken: TokenWithChainDetails,\n destinationAllbridgeChainId: number,\n messenger: Messenger,\n api: AllbridgeCoreClient\n): Promise<GasFeeOptions> {\n const transactionCostResponse = await api.getReceiveTransactionCost({\n sourceChainId: sourceChainToken.allbridgeChainId,\n destinationChainId: destinationAllbridgeChainId,\n messenger,\n sourceToken: sourceChainToken.tokenAddress,\n });\n\n const gasFeeOptions: GasFeeOptions = {\n [FeePaymentMethod.WITH_NATIVE_CURRENCY]: {\n [AmountFormat.INT]: transactionCostResponse.fee,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n transactionCostResponse.fee,\n Chains.getChainDecimalsByType(sourceChainToken.chainType)\n ).toFixed(),\n },\n adminFeeShareWithExtras: transactionCostResponse.adminFeeShareWithExtras,\n };\n\n if (transactionCostResponse.sourceNativeTokenPrice) {\n const gasFeeIntWithStables = convertAmountPrecision(\n new Big(transactionCostResponse.fee).mul(transactionCostResponse.sourceNativeTokenPrice),\n Chains.getChainDecimalsByType(sourceChainToken.chainType),\n sourceChainToken.decimals\n ).toFixed(0, Big.roundUp);\n gasFeeOptions[FeePaymentMethod.WITH_STABLECOIN] = {\n [AmountFormat.INT]: gasFeeIntWithStables,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(gasFeeIntWithStables, sourceChainToken.decimals).toFixed(),\n };\n }\n\n if (\n transactionCostResponse.abrExchangeRate &&\n sourceChainToken.abrPayer &&\n sourceChainToken.abrPayer.payerAvailability[messenger]\n ) {\n const gasFeeIntWithStables = convertAmountPrecision(\n new Big(transactionCostResponse.fee).mul(transactionCostResponse.abrExchangeRate),\n Chains.getChainDecimalsByType(sourceChainToken.chainType),\n sourceChainToken.abrPayer.abrToken.decimals\n ).toFixed(0, Big.roundUp);\n gasFeeOptions[FeePaymentMethod.WITH_ARB] = {\n [AmountFormat.INT]: gasFeeIntWithStables,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n gasFeeIntWithStables,\n sourceChainToken.abrPayer.abrToken.decimals\n ).toFixed(),\n };\n }\n\n return gasFeeOptions;\n}\n\nfunction validateExtraGasNotExceeded(\n extraGasInt: string,\n gasFeePaymentMethod: FeePaymentMethod,\n extraGasLimits: ExtraGasMaxLimitResponse\n) {\n const extraGasMaxLimit = extraGasLimits.extraGasMax[gasFeePaymentMethod];\n if (!extraGasMaxLimit) {\n throw new InvalidGasFeePaymentOptionError(`Impossible to pay extra gas by '${gasFeePaymentMethod}' payment method`);\n }\n const extraGasMaxIntLimit = extraGasMaxLimit[AmountFormat.INT];\n if (Big(extraGasInt).gt(extraGasMaxIntLimit)) {\n throw new ExtraGasMaxLimitExceededError(\n `Extra gas ${extraGasInt} in int format, exceeded limit ${extraGasMaxIntLimit} for '${gasFeePaymentMethod}' payment method`\n );\n }\n}\n\nexport async function getExtraGasMaxLimits(\n sourceChainToken: TokenWithChainDetails,\n destinationChainToken: TokenWithChainDetails,\n messenger: Messenger,\n api: AllbridgeCoreClient\n): Promise<ExtraGasMaxLimitResponse> {\n const extraGasMaxLimits: ExtraGasMaxLimits = {};\n const transactionCostResponse = await api.getReceiveTransactionCost({\n sourceChainId: sourceChainToken.allbridgeChainId,\n destinationChainId: destinationChainToken.allbridgeChainId,\n messenger,\n sourceToken: sourceChainToken.tokenAddress,\n });\n const maxAmount = destinationChainToken.txCostAmount.maxAmount;\n const maxAmountFloat = convertIntAmountToFloat(\n maxAmount,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed();\n const maxAmountFloatInSourceNative = Big(maxAmountFloat)\n .div(transactionCostResponse.exchangeRate)\n .toFixed(Chains.getChainDecimalsByType(sourceChainToken.chainType), Big.roundDown);\n const maxAmountInSourceNative = convertFloatAmountToInt(\n maxAmountFloatInSourceNative,\n Chains.getChainDecimalsByType(sourceChainToken.chainType)\n ).toFixed(0);\n extraGasMaxLimits[FeePaymentMethod.WITH_NATIVE_CURRENCY] = {\n [AmountFormat.INT]: maxAmountInSourceNative,\n [AmountFormat.FLOAT]: maxAmountFloatInSourceNative,\n };\n\n if (transactionCostResponse.sourceNativeTokenPrice) {\n const maxAmountFloatInStable = Big(maxAmountFloatInSourceNative)\n .mul(transactionCostResponse.sourceNativeTokenPrice)\n .toFixed(sourceChainToken.decimals, Big.roundDown);\n extraGasMaxLimits[FeePaymentMethod.WITH_STABLECOIN] = {\n [AmountFormat.INT]: convertFloatAmountToInt(maxAmountFloatInStable, sourceChainToken.decimals).toFixed(0),\n [AmountFormat.FLOAT]: maxAmountFloatInStable,\n };\n }\n\n let abrAvailable;\n if (\n transactionCostResponse.abrExchangeRate &&\n sourceChainToken.abrPayer &&\n sourceChainToken.abrPayer.payerAvailability[messenger]\n ) {\n abrAvailable = true;\n const maxAmountFloatInStable = Big(maxAmountFloatInSourceNative)\n .mul(transactionCostResponse.abrExchangeRate)\n .toFixed(sourceChainToken.abrPayer.abrToken.decimals, Big.roundDown);\n extraGasMaxLimits[FeePaymentMethod.WITH_ARB] = {\n [AmountFormat.INT]: convertFloatAmountToInt(\n maxAmountFloatInStable,\n sourceChainToken.abrPayer.abrToken.decimals\n ).toFixed(0),\n [AmountFormat.FLOAT]: maxAmountFloatInStable,\n };\n }\n\n return {\n extraGasMax: extraGasMaxLimits,\n destinationChain: {\n gasAmountMax: {\n [AmountFormat.INT]: maxAmount,\n [AmountFormat.FLOAT]: maxAmountFloat,\n },\n swap: {\n [AmountFormat.INT]: destinationChainToken.txCostAmount.swap,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n destinationChainToken.txCostAmount.swap,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed(),\n },\n transfer: {\n [AmountFormat.INT]: destinationChainToken.txCostAmount.transfer,\n [AmountFormat.FLOAT]: convertIntAmountToFloat(\n destinationChainToken.txCostAmount.transfer,\n Chains.getChainDecimalsByType(destinationChainToken.chainType)\n ).toFixed(),\n },\n },\n exchangeRate: transactionCostResponse.exchangeRate,\n abrExchangeRate: abrAvailable ? transactionCostResponse.abrExchangeRate : undefined,\n sourceNativeTokenPrice: transactionCostResponse.sourceNativeTokenPrice,\n };\n}\n\nexport function isSendParams(params: SwapParams | SendParams): params is SendParams {\n return params.sourceToken.chainSymbol !== params.destinationToken.chainSymbol;\n}\n"]}
|
|
@@ -41,23 +41,22 @@ class AlgPoolService extends models_1.ChainPoolService {
|
|
|
41
41
|
const poolId = BigInt(params.token.poolAddress);
|
|
42
42
|
const pool = this.getPool(poolId);
|
|
43
43
|
const isOptedIn = await (0, alg_1.checkAppOptIn)(poolId, userAccount, this.algorand);
|
|
44
|
+
const onComplete = isOptedIn
|
|
45
|
+
? algosdk_1.OnApplicationComplete.NoOpOC
|
|
46
|
+
: algosdk_1.OnApplicationComplete.OptInOC;
|
|
44
47
|
const composer = this.algorand.newGroup();
|
|
45
|
-
|
|
46
|
-
composer.addAppCallMethodCall(await pool.params.optIn.optInToApplication({ args: [], sender: userAccount }));
|
|
47
|
-
}
|
|
48
|
-
composer.addAssetTransfer({
|
|
48
|
+
const assetTransfer = await this.algorand.createTransaction.assetTransfer({
|
|
49
49
|
assetId: assetId,
|
|
50
50
|
amount: amount,
|
|
51
51
|
sender: userAccount,
|
|
52
52
|
receiver: pool.appAddress,
|
|
53
53
|
});
|
|
54
|
-
composer.addAppCallMethodCall(await pool.params.deposit({
|
|
55
|
-
|
|
56
|
-
composer,
|
|
57
|
-
appId: poolId,
|
|
54
|
+
composer.addAppCallMethodCall(await pool.params.deposit({
|
|
55
|
+
args: { assetTransferRef: assetTransfer },
|
|
58
56
|
sender: userAccount,
|
|
59
|
-
|
|
60
|
-
|
|
57
|
+
onComplete: onComplete,
|
|
58
|
+
extraFee: (0, alg_1.feeForInner)(5),
|
|
59
|
+
}));
|
|
61
60
|
let { transactions } = await composer.buildTransactions();
|
|
62
61
|
transactions = (0, algosdk_1.assignGroupID)(transactions);
|
|
63
62
|
return (0, alg_1.encodeTxs)(...transactions);
|
|
@@ -72,15 +71,9 @@ class AlgPoolService extends models_1.ChainPoolService {
|
|
|
72
71
|
composer.addAppCallMethodCall(await pool.params.withdraw({
|
|
73
72
|
args: { amountLp: amount },
|
|
74
73
|
sender: userAccount,
|
|
75
|
-
extraFee: (0, alg_1.feeForInner)(2),
|
|
76
74
|
assetReferences: [assetId],
|
|
75
|
+
extraFee: (0, alg_1.feeForInner)(7),
|
|
77
76
|
}));
|
|
78
|
-
(0, alg_1.addBudgetNoops)({
|
|
79
|
-
composer,
|
|
80
|
-
appId: poolId,
|
|
81
|
-
sender: userAccount,
|
|
82
|
-
count: 4,
|
|
83
|
-
});
|
|
84
77
|
let { transactions } = await composer.buildTransactions();
|
|
85
78
|
transactions = (0, algosdk_1.assignGroupID)(transactions);
|
|
86
79
|
return (0, alg_1.encodeTxs)(...transactions);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/services/liquidity-pool/alg/index.ts"],"names":[],"mappings":";;;AACA,qCAAuD;AACvD,6DAAwD;AAExD,oDAA+C;AAE/C,4DAAwE;AAExE,4DAAyD;AACzD,yCAAwF;AACxF,sCAMmB;AAEnB,MAAa,cAAe,SAAQ,yBAAgB;IAKzC;IACA;IALT,SAAS,GAAkB,uBAAS,CAAC,GAAG,CAAC;IACjC,CAAC,GAAG,EAAE,CAAC;IAEf,YACS,QAAwB,EACxB,GAAwB;QAE/B,KAAK,EAAE,CAAC;QAHD,aAAQ,GAAR,QAAQ,CAAgB;QACxB,QAAG,GAAH,GAAG,CAAqB;IAGjC,CAAC;IAED,KAAK,CAAC,+BAA+B,CAAC,MAA4B;QAChE,MAAM,WAAW,GAAG,MAAM,CAAC,cAAc,CAAC;QAC1C,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QAClD,MAAM,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QAChD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;QAElC,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC;QAC1C,QAAQ,CAAC,oBAAoB,CAC3B,MAAM,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC;YAC7B,IAAI,EAAE,EAAE;YACR,MAAM,EAAE,WAAW;YACnB,QAAQ,EAAE,IAAA,iBAAW,EAAC,CAAC,CAAC;YACxB,eAAe,EAAE,CAAC,OAAO,CAAC;SAC3B,CAAC,CACH,CAAC;QACF,IAAI,EAAE,YAAY,EAAE,GAAG,MAAM,QAAQ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CAAC,QAAQ,CAAC,MAAM,CAAC,qBAAqB,CAAC,uBAAU,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF;AAjJD,wCAiJC","sourcesContent":["import { AlgorandClient } from \"@algorandfoundation/algokit-utils\";\nimport { assignGroupID, bytesToBigInt } from \"algosdk\";\nimport { ChainType } from \"../../../chains/chain.enums\";\nimport { AllbridgeCoreClient } from \"../../../client/core-api/core-client-base\";\nimport { SdkError } from \"../../../exceptions\";\nimport { PoolInfo, TokenWithChainDetails } from \"../../../tokens-info\";\nimport { calculatePoolInfoImbalance } from \"../../../utils/calculation\";\nimport { RawTransaction } from \"../../models\";\nimport { PoolClient } from \"../../models/alg/PoolClient\";\nimport { addBudgetNoops, checkAppOptIn, encodeTxs, feeForInner } from \"../../utils/alg\";\nimport {\n ChainPoolService,\n LiquidityPoolsParams,\n LiquidityPoolsParamsWithAmount,\n UserBalance,\n UserBalanceInfo,\n} from \"../models\";\n\nexport class AlgPoolService extends ChainPoolService {\n chainType: ChainType.ALG = ChainType.ALG;\n private P = 48;\n\n constructor(\n public algorand: AlgorandClient,\n public api: AllbridgeCoreClient\n ) {\n super();\n }\n\n async buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawTransaction> {\n const userAccount = params.accountAddress;\n const assetId = BigInt(params.token.tokenAddress);\n const poolId = BigInt(params.token.poolAddress);\n const pool = this.getPool(poolId);\n\n const composer = this.algorand.newGroup();\n composer.addAppCallMethodCall(\n await pool.params.claimRewards({\n args: [],\n sender: userAccount,\n extraFee: feeForInner(1),\n assetReferences: [assetId],\n })\n );\n let { transactions } = await composer.buildTransactions();\n transactions = assignGroupID(transactions);\n return encodeTxs(...transactions);\n }\n\n async buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const userAccount = params.accountAddress;\n const amount = BigInt(params.amount);\n const assetId = BigInt(params.token.tokenAddress);\n const poolId = BigInt(params.token.poolAddress);\n const pool = this.getPool(poolId);\n\n const isOptedIn = await checkAppOptIn(poolId, userAccount, this.algorand);\n\n const composer = this.algorand.newGroup();\n\n if (!isOptedIn) {\n composer.addAppCallMethodCall(await pool.params.optIn.optInToApplication({ args: [], sender: userAccount }));\n }\n\n composer.addAssetTransfer({\n assetId: assetId,\n amount: amount,\n sender: userAccount,\n receiver: pool.appAddress,\n });\n composer.addAppCallMethodCall(\n await pool.params.deposit({ args: [], sender: userAccount, extraFee: feeForInner(1) })\n );\n addBudgetNoops({\n composer,\n appId: poolId,\n sender: userAccount,\n count: 4,\n });\n let { transactions } = await composer.buildTransactions();\n transactions = assignGroupID(transactions);\n return encodeTxs(...transactions);\n }\n\n async buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const userAccount = params.accountAddress;\n const amount = BigInt(params.amount);\n const assetId = BigInt(params.token.tokenAddress);\n const poolId = BigInt(params.token.poolAddress);\n const pool = this.getPool(poolId);\n\n const composer = this.algorand.newGroup();\n composer.addAppCallMethodCall(\n await pool.params.withdraw({\n args: { amountLp: amount },\n sender: userAccount,\n extraFee: feeForInner(2),\n assetReferences: [assetId],\n })\n );\n addBudgetNoops({\n composer,\n appId: poolId,\n sender: userAccount,\n count: 4,\n });\n let { transactions } = await composer.buildTransactions();\n transactions = assignGroupID(transactions);\n return encodeTxs(...transactions);\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo> {\n const pool = this.getPool(BigInt(token.poolAddress));\n const all = await pool.state.global.getAll();\n const aValue = all.a?.toString();\n const dValue = all.d?.toString();\n const tokenBalance = all.tokenBalance?.toString();\n const vUsdBalance = all.vUsdBalance?.toString();\n const totalLpAmount = all.totalSupply?.toString();\n const accRewardPerShareP = bytesToBigInt(all.accRewardPerShareP?.asByteArray() ?? Uint8Array.from([])).toString();\n if (aValue && dValue && tokenBalance && vUsdBalance && totalLpAmount && accRewardPerShareP) {\n const imbalance = calculatePoolInfoImbalance({ tokenBalance, vUsdBalance });\n return {\n aValue,\n dValue,\n tokenBalance,\n vUsdBalance,\n totalLpAmount,\n accRewardPerShareP,\n p: this.P,\n imbalance,\n };\n }\n throw new SdkError(\"Unable to pool info from chain\");\n }\n\n async getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo> {\n const appId = BigInt(token.poolAddress);\n const pool = this.getPool(appId);\n try {\n const { balance, userRewardDebt } = await pool.state.local(accountAddress).getAll();\n if (balance !== undefined && userRewardDebt !== undefined) {\n return new UserBalance({\n lpAmount: balance.toString(),\n rewardDebt: userRewardDebt.toString(),\n });\n }\n } catch (ignoreError) {\n const info = await this.algorand.account.getInformation(accountAddress);\n const localStates = info.appsLocalState;\n if (localStates) {\n const isOptedIn = localStates.find(({ id: id }) => id === appId);\n if (!isOptedIn) {\n return new UserBalance({ lpAmount: \"0\", rewardDebt: \"0\" });\n }\n }\n }\n throw new SdkError(\"Unable to get user balance\");\n }\n\n private getPool(appId: bigint): PoolClient {\n return this.algorand.client.getTypedAppClientById(PoolClient, { appId });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/services/liquidity-pool/alg/index.ts"],"names":[],"mappings":";;;AACA,qCAA8E;AAC9E,6DAAwD;AAExD,oDAA+C;AAE/C,4DAAwE;AAExE,4DAAyD;AACzD,yCAAwE;AACxE,sCAMmB;AAEnB,MAAa,cAAe,SAAQ,yBAAgB;IAKzC;IACA;IALT,SAAS,GAAkB,uBAAS,CAAC,GAAG,CAAC;IACjC,CAAC,GAAG,EAAE,CAAC;IAEf,YACS,QAAwB,EACxB,GAAwB;QAE/B,KAAK,EAAE,CAAC;QAHD,aAAQ,GAAR,QAAQ,CAAgB;QACxB,QAAG,GAAH,GAAG,CAAqB;IAGjC,CAAC;IAED,KAAK,CAAC,+BAA+B,CAAC,MAA4B;QAChE,MAAM,WAAW,GAAG,MAAM,CAAC,cAAc,CAAC;QAC1C,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC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AC,CAAC;gBACjE,IAAI,CAAC,SAAS,EAAE,CAAC;oBACf,OAAO,IAAI,oBAAW,CAAC,EAAE,QAAQ,EAAE,GAAG,EAAE,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC;gBAC7D,CAAC;YACH,CAAC;QACH,CAAC;QACD,MAAM,IAAI,qBAAQ,CAAC,4BAA4B,CAAC,CAAC;IACnD,CAAC;IAEO,OAAO,CAAC,KAAa;QAC3B,OAAO,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,qBAAqB,CAAC,uBAAU,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;IAC3E,CAAC;CACF;AA5ID,wCA4IC","sourcesContent":["import { AlgorandClient } from \"@algorandfoundation/algokit-utils\";\nimport { assignGroupID, bytesToBigInt, OnApplicationComplete } from \"algosdk\";\nimport { ChainType } from \"../../../chains/chain.enums\";\nimport { AllbridgeCoreClient } from \"../../../client/core-api/core-client-base\";\nimport { SdkError } from \"../../../exceptions\";\nimport { PoolInfo, TokenWithChainDetails } from \"../../../tokens-info\";\nimport { calculatePoolInfoImbalance } from \"../../../utils/calculation\";\nimport { RawTransaction } from \"../../models\";\nimport { PoolClient } from \"../../models/alg/PoolClient\";\nimport { checkAppOptIn, encodeTxs, feeForInner } from \"../../utils/alg\";\nimport {\n ChainPoolService,\n LiquidityPoolsParams,\n LiquidityPoolsParamsWithAmount,\n UserBalance,\n UserBalanceInfo,\n} from \"../models\";\n\nexport class AlgPoolService extends ChainPoolService {\n chainType: ChainType.ALG = ChainType.ALG;\n private P = 48;\n\n constructor(\n public algorand: AlgorandClient,\n public api: AllbridgeCoreClient\n ) {\n super();\n }\n\n async buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawTransaction> {\n const userAccount = params.accountAddress;\n const assetId = BigInt(params.token.tokenAddress);\n const poolId = BigInt(params.token.poolAddress);\n const pool = this.getPool(poolId);\n\n const composer = this.algorand.newGroup();\n composer.addAppCallMethodCall(\n await pool.params.claimRewards({\n args: [],\n sender: userAccount,\n extraFee: feeForInner(1),\n assetReferences: [assetId],\n })\n );\n let { transactions } = await composer.buildTransactions();\n transactions = assignGroupID(transactions);\n return encodeTxs(...transactions);\n }\n\n async buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const userAccount = params.accountAddress;\n const amount = BigInt(params.amount);\n const assetId = BigInt(params.token.tokenAddress);\n const poolId = BigInt(params.token.poolAddress);\n const pool = this.getPool(poolId);\n\n const isOptedIn = await checkAppOptIn(poolId, userAccount, this.algorand);\n\n const onComplete: OnApplicationComplete.OptInOC | OnApplicationComplete.NoOpOC = isOptedIn\n ? OnApplicationComplete.NoOpOC\n : OnApplicationComplete.OptInOC;\n\n const composer = this.algorand.newGroup();\n\n const assetTransfer = await this.algorand.createTransaction.assetTransfer({\n assetId: assetId,\n amount: amount,\n sender: userAccount,\n receiver: pool.appAddress,\n });\n composer.addAppCallMethodCall(\n await pool.params.deposit({\n args: { assetTransferRef: assetTransfer },\n sender: userAccount,\n onComplete: onComplete,\n extraFee: feeForInner(5),\n })\n );\n\n let { transactions } = await composer.buildTransactions();\n transactions = assignGroupID(transactions);\n return encodeTxs(...transactions);\n }\n\n async buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const userAccount = params.accountAddress;\n const amount = BigInt(params.amount);\n const assetId = BigInt(params.token.tokenAddress);\n const poolId = BigInt(params.token.poolAddress);\n const pool = this.getPool(poolId);\n\n const composer = this.algorand.newGroup();\n composer.addAppCallMethodCall(\n await pool.params.withdraw({\n args: { amountLp: amount },\n sender: userAccount,\n assetReferences: [assetId],\n extraFee: feeForInner(7),\n })\n );\n\n let { transactions } = await composer.buildTransactions();\n transactions = assignGroupID(transactions);\n return encodeTxs(...transactions);\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo> {\n const pool = this.getPool(BigInt(token.poolAddress));\n const all = await pool.state.global.getAll();\n const aValue = all.a?.toString();\n const dValue = all.d?.toString();\n const tokenBalance = all.tokenBalance?.toString();\n const vUsdBalance = all.vUsdBalance?.toString();\n const totalLpAmount = all.totalSupply?.toString();\n const accRewardPerShareP = bytesToBigInt(all.accRewardPerShareP?.asByteArray() ?? Uint8Array.from([])).toString();\n if (aValue && dValue && tokenBalance && vUsdBalance && totalLpAmount && accRewardPerShareP) {\n const imbalance = calculatePoolInfoImbalance({ tokenBalance, vUsdBalance });\n return {\n aValue,\n dValue,\n tokenBalance,\n vUsdBalance,\n totalLpAmount,\n accRewardPerShareP,\n p: this.P,\n imbalance,\n };\n }\n throw new SdkError(\"Unable to pool info from chain\");\n }\n\n async getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo> {\n const appId = BigInt(token.poolAddress);\n const pool = this.getPool(appId);\n try {\n const { balance, userRewardDebt } = await pool.state.local(accountAddress).getAll();\n if (balance !== undefined && userRewardDebt !== undefined) {\n return new UserBalance({\n lpAmount: balance.toString(),\n rewardDebt: userRewardDebt.toString(),\n });\n }\n } catch (ignoreError) {\n const info = await this.algorand.account.getInformation(accountAddress);\n const localStates = info.appsLocalState;\n if (localStates) {\n const isOptedIn = localStates.find(({ id: id }) => id === appId);\n if (!isOptedIn) {\n return new UserBalance({ lpAmount: \"0\", rewardDebt: \"0\" });\n }\n }\n }\n throw new SdkError(\"Unable to get user balance\");\n }\n\n private getPool(appId: bigint): PoolClient {\n return this.algorand.client.getTypedAppClientById(PoolClient, { appId });\n }\n}\n"]}
|
|
@@ -21,6 +21,7 @@ const evm_1 = require("./evm");
|
|
|
21
21
|
const raw_pool_transaction_builder_1 = require("./raw-pool-transaction-builder");
|
|
22
22
|
const sol_1 = require("./sol");
|
|
23
23
|
const srb_1 = require("./srb");
|
|
24
|
+
const stx_1 = require("./stx");
|
|
24
25
|
const sui_1 = require("./sui");
|
|
25
26
|
const trx_1 = require("./trx");
|
|
26
27
|
class DefaultLiquidityPoolService {
|
|
@@ -149,6 +150,10 @@ function getChainPoolService(chainSymbol, api, nodeRpcUrlsConfig, params, provid
|
|
|
149
150
|
return new alg_1.AlgPoolService(algorand, api);
|
|
150
151
|
}
|
|
151
152
|
}
|
|
153
|
+
case index_1.ChainType.STX: {
|
|
154
|
+
const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);
|
|
155
|
+
return new stx_1.StxPoolService(nodeRpcUrl, params, api);
|
|
156
|
+
}
|
|
152
157
|
}
|
|
153
158
|
}
|
|
154
159
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/services/liquidity-pool/index.ts"],"names":[],"mappings":";;;;;;AA0NA,kDAoDC;AA9QD,qEAAmE;AAEnE,mCAA6B;AAC7B,8DAAgC;AAChC,qCAAkC;AAClC,+BAAmD;AAEnD,yCAAsC;AAGtC,uCAAgF;AAEhF,yDAAuF;AACvF,iEAAqE;AACrE,6CAAiF;AAGjF,sDAAmF;AACnF,+BAAuC;AACvC,+BAAuC;AAEvC,iFAA6G;AAC7G,+BAA0C;AAC1C,+BAAuC;AACvC,+BAAuC;AACvC,+BAAwC;AA4FxC,MAAa,2BAA2B;IAK5B;IACA;IACA;IACA;IAPH,YAAY,CAA4B;IACvC,KAAK,CAAkB;IAE/B,YACU,GAAgC,EAChC,iBAAoC,EACpC,MAA+B,EAC/B,YAA0B;QAH1B,QAAG,GAAH,GAAG,CAA6B;QAChC,sBAAiB,GAAjB,iBAAiB,CAAmB;QACpC,WAAM,GAAN,MAAM,CAAyB;QAC/B,iBAAY,GAAZ,YAAY,CAAc;QAElC,IAAI,CAAC,YAAY,GAAG,IAAI,+DAAgC,CAAC,GAAG,EAAE,iBAAiB,EAAE,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;QAC5G,MAAM,GAAG,GAAG,MAAM,CAAC,qBAAqB,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,qBAAqB,GAAG,IAAI,CAAC,CA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k\";\nimport { Big } from \"big.js\";\nimport Cache from \"timed-cache\";\nimport { TronWeb } from \"tronweb\";\nimport { FMT_BYTES, FMT_NUMBER, Web3 } from \"web3\";\nimport { NodeRpcUrlsConfig } from \"..\";\nimport { Chains } from \"../../chains\";\nimport { AllbridgeCoreClient } from \"../../client/core-api/core-client-base\";\nimport { AllbridgeCoreClientFiltered } from \"../../client/core-api/core-client-filtered\";\nimport { AllbridgeCoreSdkOptions, ChainType, EssentialWeb3 } from \"../../index\";\nimport { PoolInfo, PoolKeyObject, TokenWithChainDetails } from \"../../tokens-info\";\nimport { convertIntAmountToFloat, fromSystemPrecision } from \"../../utils/calculation\";\nimport { SYSTEM_PRECISION } from \"../../utils/calculation/constants\";\nimport { validateAmountDecimals, validateAmountGtZero } from \"../../utils/utils\";\nimport { Provider, TransactionResponse } from \"../models\";\nimport { TokenService } from \"../token\";\nimport { depositAmountToVUsd, vUsdToWithdrawalAmount } from \"../utils/calculation\";\nimport { AlgPoolService } from \"./alg\";\nimport { EvmPoolService } from \"./evm\";\nimport { ApproveParams, ChainPoolService, CheckAllowanceParams, GetAllowanceParams, UserBalanceInfo } from \"./models\";\nimport { DefaultRawPoolTransactionBuilder, RawPoolTransactionBuilder } from \"./raw-pool-transaction-builder\";\nimport { SolanaPoolService } from \"./sol\";\nimport { SrbPoolService } from \"./srb\";\nimport { SuiPoolService } from \"./sui\";\nimport { TronPoolService } from \"./trx\";\n\nexport interface LiquidityPoolService {\n rawTxBuilder: RawPoolTransactionBuilder;\n\n /**\n * Get amount of tokens approved for poolInfo\n * @param provider - will be used to access the network\n * @param params See {@link GetAllowanceParams}\n * @returns the amount of approved tokens\n */\n getAllowance(provider: Provider, params: GetAllowanceParams): Promise<string>;\n\n /**\n * Get amount of tokens approved for poolInfo\n * @param params See {@link GetAllowanceParams}\n * @returns the amount of approved tokens\n */\n getAllowance(params: GetAllowanceParams): Promise<string>;\n\n /**\n * Check if the amount of approved tokens is enough\n * @param provider - will be used to access the network\n * @param params See {@link CheckAllowanceParams}\n * @returns true if the amount of approved tokens is enough to make a transfer\n */\n checkAllowance(provider: Provider, params: CheckAllowanceParams): Promise<boolean>;\n\n /**\n * Check if the amount of approved tokens is enough\n * @param params See {@link CheckAllowanceParams}\n * @returns true if the amount of approved tokens is enough to make a transfer\n */\n checkAllowance(params: CheckAllowanceParams): Promise<boolean>;\n\n /**\n * @deprecated Use {@link rawTxBuilder}.{@link RawPoolTransactionBuilder.approve}<p>\n * Approve tokens usage by another address on chains\n * <p>\n * For ETH/USDT: due to specificity of the USDT contract:<br/>\n * If the current allowance is not 0, this function will perform an additional transaction to set allowance to 0 before setting the new allowance value.\n * @param provider - will be used to access the network\n * @param approveData\n */\n approve(provider: Provider, approveData: ApproveParams): Promise<TransactionResponse>;\n\n /**\n * Calculates the amount of LP tokens that will be deposited\n * @param amount The float amount of tokens that will be sent\n * @param token\n * @param provider - will be used to access the network\n * @returns amount\n */\n getAmountToBeDeposited(amount: string, token: TokenWithChainDetails, provider?: Provider): Promise<string>;\n\n /**\n * Calculates the amount of tokens will be withdrawn\n * @param amount The float amount of tokens that will be sent\n * @param accountAddress\n * @param token\n * @param provider - will be used to access the network\n * @returns amount\n */\n getAmountToBeWithdrawn(\n amount: string,\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<string>;\n\n /**\n * Get User Balance Info on Liquidity poolInfo\n * @param accountAddress\n * @param token\n * @param provider\n * @returns UserBalanceInfo\n */\n getUserBalanceInfo(\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<UserBalanceInfo>;\n\n /**\n * Gets information about the poolInfo from chain\n * @param token\n * @param provider - will be used to access the network\n * @returns poolInfo\n */\n getPoolInfoFromChain(token: TokenWithChainDetails, provider?: Provider): Promise<Required<PoolInfo>>;\n}\n\nexport class DefaultLiquidityPoolService implements LiquidityPoolService {\n public rawTxBuilder: RawPoolTransactionBuilder;\n private cache: Cache<PoolInfo>;\n\n constructor(\n private api: AllbridgeCoreClientFiltered,\n private nodeRpcUrlsConfig: NodeRpcUrlsConfig,\n private params: AllbridgeCoreSdkOptions,\n private tokenService: TokenService\n ) {\n this.rawTxBuilder = new DefaultRawPoolTransactionBuilder(api, nodeRpcUrlsConfig, this.params, tokenService);\n const ttl = params.cachePoolInfoChainSec > 0 ? params.cachePoolInfoChainSec * 1000 : 20 * 1000;\n this.cache = new Cache<PoolInfo>({ defaultTtl: ttl });\n }\n\n async getAllowance(a: Provider | GetAllowanceParams, b?: GetAllowanceParams): Promise<string> {\n if (b) {\n const provider = a as Provider;\n const params = b;\n return await this.tokenService.getAllowance({ ...params, spender: params.token.poolAddress }, provider);\n } else {\n const params = a as GetAllowanceParams;\n return await this.tokenService.getAllowance({ ...params, spender: params.token.poolAddress });\n }\n }\n\n async checkAllowance(a: Provider | CheckAllowanceParams, b?: CheckAllowanceParams): Promise<boolean> {\n if (b) {\n const provider = a as Provider;\n const params = b;\n return this.tokenService.checkAllowance({ ...params, spender: params.token.poolAddress }, provider);\n } else {\n const params = a as CheckAllowanceParams;\n return this.tokenService.checkAllowance({ ...params, spender: params.token.poolAddress });\n }\n }\n\n async approve(provider: Provider, approveData: ApproveParams): Promise<TransactionResponse> {\n return this.tokenService.approve(provider, { ...approveData, spender: approveData.token.poolAddress });\n }\n\n async getAmountToBeDeposited(amount: string, token: TokenWithChainDetails, provider?: Provider): Promise<string> {\n validateAmountGtZero(amount);\n validateAmountDecimals(\"amount\", amount, token.decimals);\n const pool = await this.getPoolInfoFromChain(token, provider);\n const { vUsdBalance, tokenBalance, aValue, dValue } = pool;\n const vUsd = depositAmountToVUsd(amount, aValue, dValue, tokenBalance, vUsdBalance);\n return convertIntAmountToFloat(vUsd, SYSTEM_PRECISION).toFixed();\n }\n\n async getAmountToBeWithdrawn(\n amount: string,\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<string> {\n validateAmountGtZero(amount);\n validateAmountDecimals(\"amount\", amount, token.decimals);\n const pool = await this.getPoolInfoFromChain(token, provider);\n const tokenAmountInSP = vUsdToWithdrawalAmount(amount);\n const tokenAmount = fromSystemPrecision(tokenAmountInSP, token.decimals);\n const userBalanceInfo = await this.getUserBalanceInfo(accountAddress, token, provider);\n const earned = userBalanceInfo.earned(pool) || \"0\";\n const commonAmount = Big(tokenAmount).plus(earned).toFixed();\n return convertIntAmountToFloat(commonAmount, token.decimals).toFixed();\n }\n\n async getUserBalanceInfo(\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<UserBalanceInfo> {\n return getChainPoolService(\n token.chainSymbol,\n this.api,\n this.nodeRpcUrlsConfig,\n this.params,\n provider\n ).getUserBalanceInfo(accountAddress, token);\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails, provider?: Provider): Promise<PoolInfo> {\n const poolKey: PoolKeyObject = { chainSymbol: token.chainSymbol, poolAddress: token.poolAddress };\n const fromCache = this.cache.get(poolKey);\n if (fromCache) {\n return fromCache;\n } else {\n const poolInfo = await getChainPoolService(\n token.chainSymbol,\n this.api,\n this.nodeRpcUrlsConfig,\n this.params,\n provider\n ).getPoolInfoFromChain(token);\n this.cache.put(poolKey, poolInfo);\n this.api.cachePut({ chainSymbol: token.chainSymbol, poolAddress: token.poolAddress }, poolInfo);\n return poolInfo;\n }\n }\n}\n\nexport function getChainPoolService(\n chainSymbol: string,\n api: AllbridgeCoreClient,\n nodeRpcUrlsConfig: NodeRpcUrlsConfig,\n params: AllbridgeCoreSdkOptions,\n provider?: Provider\n): ChainPoolService {\n switch (Chains.getChainProperty(chainSymbol).chainType) {\n case ChainType.EVM: {\n if (provider) {\n return new EvmPoolService(provider as EssentialWeb3, api);\n } else {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const web3 = new Web3(nodeRpcUrl);\n web3.defaultReturnFormat = { number: FMT_NUMBER.STR, bytes: FMT_BYTES.HEX };\n return new EvmPoolService(web3, api);\n }\n }\n case ChainType.TRX: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const tronJsonRpc = params.tronJsonRpc;\n if (provider) {\n return new TronPoolService(provider as TronWeb, api, tronJsonRpc);\n } else {\n const tronWeb = new TronWeb({ fullHost: nodeRpcUrl });\n return new TronPoolService(tronWeb, api, tronJsonRpc);\n }\n }\n case ChainType.SOLANA: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n return new SolanaPoolService(nodeRpcUrl, api);\n }\n case ChainType.SRB: {\n return new SrbPoolService(nodeRpcUrlsConfig, params, api);\n }\n case ChainType.SUI: {\n return new SuiPoolService(nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol), api);\n }\n case ChainType.ALG: {\n if (provider) {\n const algod = provider as Algodv2;\n const algorand = AlgorandClient.fromClients({ algod });\n return new AlgPoolService(algorand, api);\n } else {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const algorand = AlgorandClient.fromConfig({\n algodConfig: { server: nodeRpcUrl },\n });\n return new AlgPoolService(algorand, api);\n }\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/services/liquidity-pool/index.ts"],"names":[],"mappings":";;;;;;AA2NA,kDAwDC;AAnRD,qEAAmE;AAEnE,mCAA6B;AAC7B,8DAAgC;AAChC,qCAAkC;AAClC,+BAAmD;AAEnD,yCAAsC;AAGtC,uCAAgF;AAEhF,yDAAuF;AACvF,iEAAqE;AACrE,6CAAiF;AAGjF,sDAAmF;AACnF,+BAAuC;AACvC,+BAAuC;AAEvC,iFAA6G;AAC7G,+BAA0C;AAC1C,+BAAuC;AACvC,+BAAuC;AACvC,+BAAuC;AACvC,+BAAwC;AA4FxC,MAAa,2BAA2B;IAK5B;IACA;IACA;IACA;IAPH,YAAY,CAA4B;IACvC,KAAK,CAAkB;IAE/B,YACU,GAAgC,EAChC,iBAAoC,EACpC,MAA+B,EAC/B,YAA0B;QAH1B,QAAG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MAAM,UAAU,GAAG,iBAAiB,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;gBAChE,MAAM,QAAQ,GAAG,8BAAc,CAAC,UAAU,CAAC;oBACzC,WAAW,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE;iBACpC,CAAC,CAAC;gBACH,OAAO,IAAI,oBAAc,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;YAC3C,CAAC;QACH,CAAC;QACD,KAAK,iBAAS,CAAC,GAAG,CAAC,CAAC,CAAC;YACnB,MAAM,UAAU,GAAG,iBAAiB,CAAC,aAAa,CAAC,WAAW,CAAC,CAAC;YAChE,OAAO,IAAI,oBAAc,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;QACrD,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { AlgorandClient } from \"@algorandfoundation/algokit-utils\";\nimport { Algodv2 } from \"algosdk\";\nimport { Big } from \"big.js\";\nimport Cache from \"timed-cache\";\nimport { TronWeb } from \"tronweb\";\nimport { FMT_BYTES, FMT_NUMBER, Web3 } from \"web3\";\nimport { NodeRpcUrlsConfig } from \"..\";\nimport { Chains } from \"../../chains\";\nimport { AllbridgeCoreClient } from \"../../client/core-api/core-client-base\";\nimport { AllbridgeCoreClientFiltered } from \"../../client/core-api/core-client-filtered\";\nimport { AllbridgeCoreSdkOptions, ChainType, EssentialWeb3 } from \"../../index\";\nimport { PoolInfo, PoolKeyObject, TokenWithChainDetails } from \"../../tokens-info\";\nimport { convertIntAmountToFloat, fromSystemPrecision } from \"../../utils/calculation\";\nimport { SYSTEM_PRECISION } from \"../../utils/calculation/constants\";\nimport { validateAmountDecimals, validateAmountGtZero } from \"../../utils/utils\";\nimport { Provider, TransactionResponse } from \"../models\";\nimport { TokenService } from \"../token\";\nimport { depositAmountToVUsd, vUsdToWithdrawalAmount } from \"../utils/calculation\";\nimport { AlgPoolService } from \"./alg\";\nimport { EvmPoolService } from \"./evm\";\nimport { ApproveParams, ChainPoolService, CheckAllowanceParams, GetAllowanceParams, UserBalanceInfo } from \"./models\";\nimport { DefaultRawPoolTransactionBuilder, RawPoolTransactionBuilder } from \"./raw-pool-transaction-builder\";\nimport { SolanaPoolService } from \"./sol\";\nimport { SrbPoolService } from \"./srb\";\nimport { StxPoolService } from \"./stx\";\nimport { SuiPoolService } from \"./sui\";\nimport { TronPoolService } from \"./trx\";\n\nexport interface LiquidityPoolService {\n rawTxBuilder: RawPoolTransactionBuilder;\n\n /**\n * Get amount of tokens approved for poolInfo\n * @param provider - will be used to access the network\n * @param params See {@link GetAllowanceParams}\n * @returns the amount of approved tokens\n */\n getAllowance(provider: Provider, params: GetAllowanceParams): Promise<string>;\n\n /**\n * Get amount of tokens approved for poolInfo\n * @param params See {@link GetAllowanceParams}\n * @returns the amount of approved tokens\n */\n getAllowance(params: GetAllowanceParams): Promise<string>;\n\n /**\n * Check if the amount of approved tokens is enough\n * @param provider - will be used to access the network\n * @param params See {@link CheckAllowanceParams}\n * @returns true if the amount of approved tokens is enough to make a transfer\n */\n checkAllowance(provider: Provider, params: CheckAllowanceParams): Promise<boolean>;\n\n /**\n * Check if the amount of approved tokens is enough\n * @param params See {@link CheckAllowanceParams}\n * @returns true if the amount of approved tokens is enough to make a transfer\n */\n checkAllowance(params: CheckAllowanceParams): Promise<boolean>;\n\n /**\n * @deprecated Use {@link rawTxBuilder}.{@link RawPoolTransactionBuilder.approve}<p>\n * Approve tokens usage by another address on chains\n * <p>\n * For ETH/USDT: due to specificity of the USDT contract:<br/>\n * If the current allowance is not 0, this function will perform an additional transaction to set allowance to 0 before setting the new allowance value.\n * @param provider - will be used to access the network\n * @param approveData\n */\n approve(provider: Provider, approveData: ApproveParams): Promise<TransactionResponse>;\n\n /**\n * Calculates the amount of LP tokens that will be deposited\n * @param amount The float amount of tokens that will be sent\n * @param token\n * @param provider - will be used to access the network\n * @returns amount\n */\n getAmountToBeDeposited(amount: string, token: TokenWithChainDetails, provider?: Provider): Promise<string>;\n\n /**\n * Calculates the amount of tokens will be withdrawn\n * @param amount The float amount of tokens that will be sent\n * @param accountAddress\n * @param token\n * @param provider - will be used to access the network\n * @returns amount\n */\n getAmountToBeWithdrawn(\n amount: string,\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<string>;\n\n /**\n * Get User Balance Info on Liquidity poolInfo\n * @param accountAddress\n * @param token\n * @param provider\n * @returns UserBalanceInfo\n */\n getUserBalanceInfo(\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<UserBalanceInfo>;\n\n /**\n * Gets information about the poolInfo from chain\n * @param token\n * @param provider - will be used to access the network\n * @returns poolInfo\n */\n getPoolInfoFromChain(token: TokenWithChainDetails, provider?: Provider): Promise<Required<PoolInfo>>;\n}\n\nexport class DefaultLiquidityPoolService implements LiquidityPoolService {\n public rawTxBuilder: RawPoolTransactionBuilder;\n private cache: Cache<PoolInfo>;\n\n constructor(\n private api: AllbridgeCoreClientFiltered,\n private nodeRpcUrlsConfig: NodeRpcUrlsConfig,\n private params: AllbridgeCoreSdkOptions,\n private tokenService: TokenService\n ) {\n this.rawTxBuilder = new DefaultRawPoolTransactionBuilder(api, nodeRpcUrlsConfig, this.params, tokenService);\n const ttl = params.cachePoolInfoChainSec > 0 ? params.cachePoolInfoChainSec * 1000 : 20 * 1000;\n this.cache = new Cache<PoolInfo>({ defaultTtl: ttl });\n }\n\n async getAllowance(a: Provider | GetAllowanceParams, b?: GetAllowanceParams): Promise<string> {\n if (b) {\n const provider = a as Provider;\n const params = b;\n return await this.tokenService.getAllowance({ ...params, spender: params.token.poolAddress }, provider);\n } else {\n const params = a as GetAllowanceParams;\n return await this.tokenService.getAllowance({ ...params, spender: params.token.poolAddress });\n }\n }\n\n async checkAllowance(a: Provider | CheckAllowanceParams, b?: CheckAllowanceParams): Promise<boolean> {\n if (b) {\n const provider = a as Provider;\n const params = b;\n return this.tokenService.checkAllowance({ ...params, spender: params.token.poolAddress }, provider);\n } else {\n const params = a as CheckAllowanceParams;\n return this.tokenService.checkAllowance({ ...params, spender: params.token.poolAddress });\n }\n }\n\n async approve(provider: Provider, approveData: ApproveParams): Promise<TransactionResponse> {\n return this.tokenService.approve(provider, { ...approveData, spender: approveData.token.poolAddress });\n }\n\n async getAmountToBeDeposited(amount: string, token: TokenWithChainDetails, provider?: Provider): Promise<string> {\n validateAmountGtZero(amount);\n validateAmountDecimals(\"amount\", amount, token.decimals);\n const pool = await this.getPoolInfoFromChain(token, provider);\n const { vUsdBalance, tokenBalance, aValue, dValue } = pool;\n const vUsd = depositAmountToVUsd(amount, aValue, dValue, tokenBalance, vUsdBalance);\n return convertIntAmountToFloat(vUsd, SYSTEM_PRECISION).toFixed();\n }\n\n async getAmountToBeWithdrawn(\n amount: string,\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<string> {\n validateAmountGtZero(amount);\n validateAmountDecimals(\"amount\", amount, token.decimals);\n const pool = await this.getPoolInfoFromChain(token, provider);\n const tokenAmountInSP = vUsdToWithdrawalAmount(amount);\n const tokenAmount = fromSystemPrecision(tokenAmountInSP, token.decimals);\n const userBalanceInfo = await this.getUserBalanceInfo(accountAddress, token, provider);\n const earned = userBalanceInfo.earned(pool) || \"0\";\n const commonAmount = Big(tokenAmount).plus(earned).toFixed();\n return convertIntAmountToFloat(commonAmount, token.decimals).toFixed();\n }\n\n async getUserBalanceInfo(\n accountAddress: string,\n token: TokenWithChainDetails,\n provider?: Provider\n ): Promise<UserBalanceInfo> {\n return getChainPoolService(\n token.chainSymbol,\n this.api,\n this.nodeRpcUrlsConfig,\n this.params,\n provider\n ).getUserBalanceInfo(accountAddress, token);\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails, provider?: Provider): Promise<PoolInfo> {\n const poolKey: PoolKeyObject = { chainSymbol: token.chainSymbol, poolAddress: token.poolAddress };\n const fromCache = this.cache.get(poolKey);\n if (fromCache) {\n return fromCache;\n } else {\n const poolInfo = await getChainPoolService(\n token.chainSymbol,\n this.api,\n this.nodeRpcUrlsConfig,\n this.params,\n provider\n ).getPoolInfoFromChain(token);\n this.cache.put(poolKey, poolInfo);\n this.api.cachePut({ chainSymbol: token.chainSymbol, poolAddress: token.poolAddress }, poolInfo);\n return poolInfo;\n }\n }\n}\n\nexport function getChainPoolService(\n chainSymbol: string,\n api: AllbridgeCoreClient,\n nodeRpcUrlsConfig: NodeRpcUrlsConfig,\n params: AllbridgeCoreSdkOptions,\n provider?: Provider\n): ChainPoolService {\n switch (Chains.getChainProperty(chainSymbol).chainType) {\n case ChainType.EVM: {\n if (provider) {\n return new EvmPoolService(provider as EssentialWeb3, api);\n } else {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const web3 = new Web3(nodeRpcUrl);\n web3.defaultReturnFormat = { number: FMT_NUMBER.STR, bytes: FMT_BYTES.HEX };\n return new EvmPoolService(web3, api);\n }\n }\n case ChainType.TRX: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const tronJsonRpc = params.tronJsonRpc;\n if (provider) {\n return new TronPoolService(provider as TronWeb, api, tronJsonRpc);\n } else {\n const tronWeb = new TronWeb({ fullHost: nodeRpcUrl });\n return new TronPoolService(tronWeb, api, tronJsonRpc);\n }\n }\n case ChainType.SOLANA: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n return new SolanaPoolService(nodeRpcUrl, api);\n }\n case ChainType.SRB: {\n return new SrbPoolService(nodeRpcUrlsConfig, params, api);\n }\n case ChainType.SUI: {\n return new SuiPoolService(nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol), api);\n }\n case ChainType.ALG: {\n if (provider) {\n const algod = provider as Algodv2;\n const algorand = AlgorandClient.fromClients({ algod });\n return new AlgPoolService(algorand, api);\n } else {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n const algorand = AlgorandClient.fromConfig({\n algodConfig: { server: nodeRpcUrl },\n });\n return new AlgPoolService(algorand, api);\n }\n }\n case ChainType.STX: {\n const nodeRpcUrl = nodeRpcUrlsConfig.getNodeRpcUrl(chainSymbol);\n return new StxPoolService(nodeRpcUrl, params, api);\n }\n }\n}\n"]}
|
|
@@ -57,33 +57,36 @@ class SolanaPoolService extends pool_1.ChainPoolService {
|
|
|
57
57
|
}
|
|
58
58
|
async buildRawTransactionDeposit(params) {
|
|
59
59
|
const { bridge, accounts, preInstructions } = await this.prepareDataForTransaction(params);
|
|
60
|
+
const feePayer = (0, sol_1.getFeePayer)(new web3_js_1.PublicKey(params.accountAddress), params.txFeeParams);
|
|
60
61
|
const tx = await bridge.methods
|
|
61
62
|
.deposit(new anchor_1.BN(params.amount))
|
|
62
63
|
.accounts(accounts)
|
|
63
64
|
.preInstructions(preInstructions)
|
|
64
65
|
.transaction();
|
|
65
66
|
tx.recentBlockhash = (await this.buildAnchorProvider(params.accountAddress).connection.getLatestBlockhash()).blockhash;
|
|
66
|
-
tx.feePayer =
|
|
67
|
+
tx.feePayer = feePayer;
|
|
67
68
|
await (0, compute_budget_1.addUnitLimitAndUnitPriceToTx)(tx, params.txFeeParams, this.solanaRpcUrl);
|
|
68
69
|
return tx;
|
|
69
70
|
}
|
|
70
71
|
async buildRawTransactionWithdraw(params) {
|
|
71
72
|
const { bridge, accounts, preInstructions } = await this.prepareDataForTransaction(params);
|
|
73
|
+
const feePayer = (0, sol_1.getFeePayer)(new web3_js_1.PublicKey(params.accountAddress), params.txFeeParams);
|
|
72
74
|
const tx = await bridge.methods
|
|
73
75
|
.withdraw(new anchor_1.BN(params.amount))
|
|
74
76
|
.accounts(accounts)
|
|
75
77
|
.preInstructions(preInstructions)
|
|
76
78
|
.transaction();
|
|
77
79
|
tx.recentBlockhash = (await this.buildAnchorProvider(params.accountAddress).connection.getLatestBlockhash()).blockhash;
|
|
78
|
-
tx.feePayer =
|
|
80
|
+
tx.feePayer = feePayer;
|
|
79
81
|
await (0, compute_budget_1.addUnitLimitAndUnitPriceToTx)(tx, params.txFeeParams, this.solanaRpcUrl);
|
|
80
82
|
return tx;
|
|
81
83
|
}
|
|
82
84
|
async buildRawTransactionClaimRewards(params) {
|
|
83
85
|
const { bridge, accounts, preInstructions } = await this.prepareDataForTransaction(params);
|
|
86
|
+
const feePayer = (0, sol_1.getFeePayer)(new web3_js_1.PublicKey(params.accountAddress), params.txFeeParams);
|
|
84
87
|
const tx = await bridge.methods.claimRewards().accounts(accounts).preInstructions(preInstructions).transaction();
|
|
85
88
|
tx.recentBlockhash = (await this.buildAnchorProvider(params.accountAddress).connection.getLatestBlockhash()).blockhash;
|
|
86
|
-
tx.feePayer =
|
|
89
|
+
tx.feePayer = feePayer;
|
|
87
90
|
await (0, compute_budget_1.addUnitLimitAndUnitPriceToTx)(tx, params.txFeeParams, this.solanaRpcUrl);
|
|
88
91
|
return tx;
|
|
89
92
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/services/liquidity-pool/sol/index.ts"],"names":[],"mappings":";;;AAAA,kDAAyF;AACzF,6CAAgF;AAChF,6DAAwD;AAGxD,4DAAwE;AAExE,0DAAuF;AACvF,yCAAsD;AACtD,uDAMkC;AAClC,mEAA8E;AAC9E,sCAA+G;AAC/G,yCAAkD;AAkBlD,MAAa,iBAAkB,SAAQ,uBAAgB;IAK5C;IACA;IALT,SAAS,GAAqB,uBAAS,CAAC,MAAM,CAAC;IACvC,CAAC,GAAG,EAAE,CAAC;IAEf,YACS,YAAoB,EACpB,GAAwB;QAE/B,KAAK,EAAE,CAAC;QAHD,iBAAY,GAAZ,YAAY,CAAQ;QACpB,QAAG,GAAH,GAAG,CAAqB;IAGjC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,cAAsB,EAAE,KAA4B;QAC3E,MAAM,QAAQ,GAAG,IAAI,CAAC,mBAAmB,CAAC,cAAc,CAAC,CAAC;QAC1D,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAA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B,CAAC,CAAC;QAC7D,CAAC;QAAC,OAAO,WAAW,EAAE,CAAC;YACrB,MAAM,WAAW,GAA2B,MAAM,MAAM,CAAC,OAAO;iBAC7D,kBAAkB,EAAE;iBACpB,QAAQ,CAAC;gBACR,IAAI,EAAE,gBAAgB;gBACtB,IAAI;gBACJ,WAAW,EAAE,kBAAkB;aAChC,CAAC;iBACD,WAAW,EAAE,CAAC;YACjB,eAAe,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACpC,CAAC;QAED,MAAM,QAAQ,GAAe;YAC3B,IAAI,EAAE,gBAAgB;YACtB,IAAI;YACJ,MAAM,EAAE,aAAa;YACrB,IAAI,EAAE,WAAW;YACjB,eAAe,EAAE,eAAe;YAChC,WAAW,EAAE,kBAAkB;YAC/B,SAAS;YACT,WAAW,EAAE,kBAAkB;SAChC,CAAC;QAEF,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC;IACvC,CAAC;CACF;AA/LD,8CA+LC","sourcesContent":["import { AnchorProvider, BN, Program, Provider, Spl, web3 } from \"@project-serum/anchor\";\nimport { Connection, PublicKey, TransactionInstruction } from \"@solana/web3.js\";\nimport { ChainType } from \"../../../chains/chain.enums\";\nimport { AllbridgeCoreClient } from \"../../../client/core-api/core-client-base\";\nimport { PoolInfo, TokenWithChainDetails } from \"../../../tokens-info\";\nimport { calculatePoolInfoImbalance } from \"../../../utils/calculation\";\nimport { RawTransaction } from \"../../models\";\nimport { Bridge as BridgeType, IDL as bridgeIdl } from \"../../models/sol/types/bridge\";\nimport { getTokenAccountData } from \"../../utils/sol\";\nimport {\n getAssociatedAccount,\n getAuthorityAccount,\n getBridgeTokenAccount,\n getConfigAccount,\n getUserDepositAccount,\n} from \"../../utils/sol/accounts\";\nimport { addUnitLimitAndUnitPriceToTx } from \"../../utils/sol/compute-budget\";\nimport { LiquidityPoolsParams, LiquidityPoolsParamsWithAmount, UserBalance, UserBalanceInfo } from \"../models\";\nimport { ChainPoolService } from \"../models/pool\";\n\ninterface LPAccounts {\n mint: PublicKey;\n user: PublicKey;\n config: PublicKey;\n pool: PublicKey;\n bridgeAuthority: PublicKey;\n userDeposit: PublicKey;\n userToken: PublicKey;\n bridgeToken: PublicKey;\n}\n\ninterface LPTransactionData {\n accounts: LPAccounts;\n preInstructions: TransactionInstruction[];\n}\n\nexport class SolanaPoolService extends ChainPoolService {\n chainType: ChainType.SOLANA = ChainType.SOLANA;\n private P = 48;\n\n constructor(\n public solanaRpcUrl: string,\n public api: AllbridgeCoreClient\n ) {\n super();\n }\n\n async getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo> {\n const provider = this.buildAnchorProvider(accountAddress);\n const bridge = this.getBridge(token.bridgeAddress, provider);\n const poolAccount = new PublicKey(token.poolAddress);\n const poolAccountInfo = await bridge.account.pool.fetch(poolAccount);\n try {\n const userDepositAccount = await getUserDepositAccount(\n new PublicKey(accountAddress),\n poolAccountInfo.mint,\n bridge.programId\n );\n const { lpAmount, rewardDebt } = await bridge.account.userDeposit.fetch(userDepositAccount);\n return new UserBalance({\n lpAmount: lpAmount.toString(),\n rewardDebt: rewardDebt.toString(),\n });\n } catch (ignoreError) {\n return new UserBalance({ lpAmount: \"0\", rewardDebt: \"0\" });\n }\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo> {\n const provider = this.buildAnchorProvider(token.bridgeAddress);\n const pool = await this.getBridge(token.bridgeAddress, provider).account.pool.fetch(token.poolAddress);\n const vUsdBalance = pool.vUsdBalance.toString();\n const tokenBalance = pool.tokenBalance.toString();\n const imbalance = calculatePoolInfoImbalance({ tokenBalance, vUsdBalance });\n return {\n dValue: pool.d.toString(),\n aValue: pool.a.toString(),\n totalLpAmount: pool.totalLpAmount.toString(),\n vUsdBalance,\n tokenBalance,\n accRewardPerShareP: pool.accRewardPerShareP.toString(),\n p: this.P,\n imbalance,\n };\n }\n\n async buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const { bridge, accounts, preInstructions } = await this.prepareDataForTransaction(params);\n\n const tx = await bridge.methods\n .deposit(new BN(params.amount))\n .accounts(accounts)\n .preInstructions(preInstructions)\n .transaction();\n tx.recentBlockhash = (\n await this.buildAnchorProvider(params.accountAddress).connection.getLatestBlockhash()\n ).blockhash;\n tx.feePayer = new PublicKey(params.accountAddress);\n await addUnitLimitAndUnitPriceToTx(tx, params.txFeeParams, this.solanaRpcUrl);\n return tx;\n }\n\n async buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const { bridge, accounts, preInstructions } = await this.prepareDataForTransaction(params);\n\n const tx = await bridge.methods\n .withdraw(new BN(params.amount))\n .accounts(accounts)\n .preInstructions(preInstructions)\n .transaction();\n tx.recentBlockhash = (\n await this.buildAnchorProvider(params.accountAddress).connection.getLatestBlockhash()\n ).blockhash;\n tx.feePayer = new PublicKey(params.accountAddress);\n await addUnitLimitAndUnitPriceToTx(tx, params.txFeeParams, this.solanaRpcUrl);\n return tx;\n }\n\n async buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawTransaction> {\n const { bridge, accounts, preInstructions } = await this.prepareDataForTransaction(params);\n\n const tx = await bridge.methods.claimRewards().accounts(accounts).preInstructions(preInstructions).transaction();\n tx.recentBlockhash = (\n await this.buildAnchorProvider(params.accountAddress).connection.getLatestBlockhash()\n ).blockhash;\n tx.feePayer = new PublicKey(params.accountAddress);\n await addUnitLimitAndUnitPriceToTx(tx, params.txFeeParams, this.solanaRpcUrl);\n return tx;\n }\n\n private async prepareDataForTransaction(params: LiquidityPoolsParams) {\n const provider = this.buildAnchorProvider(params.accountAddress);\n const bridge = this.getBridge(params.token.bridgeAddress, provider);\n\n const { accounts, preInstructions } = await this._getLPTransactionData(\n bridge,\n params.token.poolAddress,\n params.accountAddress,\n provider\n );\n return { bridge, accounts, preInstructions };\n }\n\n private getBridge(bridgeAddress: string, provider: Provider): Program<BridgeType> {\n return new Program<BridgeType>(bridgeIdl, bridgeAddress, provider);\n }\n\n private buildAnchorProvider(accountAddress: string): Provider {\n const connection = new Connection(this.solanaRpcUrl, \"confirmed\");\n\n const publicKey = new PublicKey(accountAddress);\n\n return new AnchorProvider(\n connection,\n // @ts-expect-error enough wallet for fetch actions\n { publicKey: publicKey },\n {\n preflightCommitment: \"confirmed\",\n commitment: \"confirmed\",\n }\n );\n }\n\n private async _getLPTransactionData(\n bridge: Program<BridgeType>,\n poolAddress: string,\n account: string,\n provider: Provider\n ): Promise<LPTransactionData> {\n const user = new PublicKey(account);\n const configAccount = await getConfigAccount(bridge.programId);\n const bridgeAuthority = await getAuthorityAccount(bridge.programId);\n const poolAccount = new PublicKey(poolAddress);\n const poolAccountInfo = await bridge.account.pool.fetch(poolAccount);\n const tokenMintAccount = poolAccountInfo.mint;\n const userToken = await getAssociatedAccount(user, tokenMintAccount);\n const bridgeTokenAccount = await getBridgeTokenAccount(tokenMintAccount, bridge.programId);\n const userDepositAccount = await getUserDepositAccount(user, tokenMintAccount, bridge.programId);\n\n const preInstructions: TransactionInstruction[] = [\n web3.ComputeBudgetProgram.setComputeUnitLimit({\n units: 1000000,\n }),\n ];\n\n try {\n await getTokenAccountData(userToken, provider);\n } catch (ignoreError) {\n const associatedProgram = Spl.associatedToken(provider);\n const createUserTokenInstruction: TransactionInstruction = await associatedProgram.methods\n .create()\n .accounts({\n mint: tokenMintAccount,\n owner: user,\n associatedAccount: userToken,\n })\n .instruction();\n preInstructions.push(createUserTokenInstruction);\n }\n\n try {\n await bridge.account.userDeposit.fetch(userDepositAccount);\n } catch (ignoreError) {\n const instruction: TransactionInstruction = await bridge.methods\n .initDepositAccount()\n .accounts({\n mint: tokenMintAccount,\n user,\n userDeposit: userDepositAccount,\n })\n .instruction();\n preInstructions.push(instruction);\n }\n\n const accounts: LPAccounts = {\n mint: tokenMintAccount,\n user,\n config: configAccount,\n pool: poolAccount,\n bridgeAuthority: bridgeAuthority,\n userDeposit: userDepositAccount,\n userToken,\n bridgeToken: bridgeTokenAccount,\n };\n\n return { accounts, preInstructions };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../src/services/liquidity-pool/sol/index.ts"],"names":[],"mappings":";;;AAAA,kDAAyF;AACzF,6CAAgF;AAChF,6DAAwD;AAGxD,4DAAwE;AAExE,0DAAuF;AACvF,yCAAmE;AACnE,uDAMkC;AAClC,mEAA8E;AAC9E,sCAA+G;AAC/G,yCAAkD;AAkBlD,MAAa,iBAAkB,SAAQ,uBAAgB;IAK5C;IACA;IALT,SAAS,GAAqB,uBAAS,CAAC,MAAM,CAAC;IACvC,CAAC,GAAG,EAAE,CAAC;IAEf,YACS,YAAoB,EACpB,GAAwB;QAE/B,KAAK,EAAE,CAAC;QAHD,iBAAY,GAAZ,YAAY,CAAQ;QACpB,QAAG,GAAH,GAAG,CAAqB;IAGjC,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,cAAsB,EAAE,KAA4B;QAC3E,MAAM,QAAQ,GAAG,IAAI,CAAC,mBAAmB,CAAC,cAAc,CAAC,CAAC;QAC1D,MAAM,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,aAAa,EAAE,QAAQ,CAAC,CAAC;QAC7D,MAAM,WAAW,GAAG,IAAI,mBAAS,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QACrD,MAAM,eAAe,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;QACrE,IAAI,CAAC;YACH,MAAM,kBAAkB,GAAG,MAAM,IAAA,gCAAqB,EACpD,IAAI,mBAAS,CAAC,cAAc,CAAC,EAC7B,eAAe,CAAC,IAAI,EACpB,MAAM,CAAC,SAAS,CACjB,CAAC;YACF,MAAM,EAAE,QAAQ,EAAE,UAAU,EAAE,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;YAC5F,OAAO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,WAAW,EAAE,CAAC;YACjB,eAAe,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACpC,CAAC;QAED,MAAM,QAAQ,GAAe;YAC3B,IAAI,EAAE,gBAAgB;YACtB,IAAI;YACJ,MAAM,EAAE,aAAa;YACrB,IAAI,EAAE,WAAW;YACjB,eAAe,EAAE,eAAe;YAChC,WAAW,EAAE,kBAAkB;YAC/B,SAAS;YACT,WAAW,EAAE,kBAAkB;SAChC,CAAC;QAEF,OAAO,EAAE,QAAQ,EAAE,eAAe,EAAE,CAAC;IACvC,CAAC;CACF;AArMD,8CAqMC","sourcesContent":["import { AnchorProvider, BN, Program, Provider, Spl, web3 } from \"@project-serum/anchor\";\nimport { Connection, PublicKey, TransactionInstruction } from \"@solana/web3.js\";\nimport { ChainType } from \"../../../chains/chain.enums\";\nimport { AllbridgeCoreClient } from \"../../../client/core-api/core-client-base\";\nimport { PoolInfo, TokenWithChainDetails } from \"../../../tokens-info\";\nimport { calculatePoolInfoImbalance } from \"../../../utils/calculation\";\nimport { RawTransaction } from \"../../models\";\nimport { Bridge as BridgeType, IDL as bridgeIdl } from \"../../models/sol/types/bridge\";\nimport { getFeePayer, getTokenAccountData } from \"../../utils/sol\";\nimport {\n getAssociatedAccount,\n getAuthorityAccount,\n getBridgeTokenAccount,\n getConfigAccount,\n getUserDepositAccount,\n} from \"../../utils/sol/accounts\";\nimport { addUnitLimitAndUnitPriceToTx } from \"../../utils/sol/compute-budget\";\nimport { LiquidityPoolsParams, LiquidityPoolsParamsWithAmount, UserBalance, UserBalanceInfo } from \"../models\";\nimport { ChainPoolService } from \"../models/pool\";\n\ninterface LPAccounts {\n mint: PublicKey;\n user: PublicKey;\n config: PublicKey;\n pool: PublicKey;\n bridgeAuthority: PublicKey;\n userDeposit: PublicKey;\n userToken: PublicKey;\n bridgeToken: PublicKey;\n}\n\ninterface LPTransactionData {\n accounts: LPAccounts;\n preInstructions: TransactionInstruction[];\n}\n\nexport class SolanaPoolService extends ChainPoolService {\n chainType: ChainType.SOLANA = ChainType.SOLANA;\n private P = 48;\n\n constructor(\n public solanaRpcUrl: string,\n public api: AllbridgeCoreClient\n ) {\n super();\n }\n\n async getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo> {\n const provider = this.buildAnchorProvider(accountAddress);\n const bridge = this.getBridge(token.bridgeAddress, provider);\n const poolAccount = new PublicKey(token.poolAddress);\n const poolAccountInfo = await bridge.account.pool.fetch(poolAccount);\n try {\n const userDepositAccount = await getUserDepositAccount(\n new PublicKey(accountAddress),\n poolAccountInfo.mint,\n bridge.programId\n );\n const { lpAmount, rewardDebt } = await bridge.account.userDeposit.fetch(userDepositAccount);\n return new UserBalance({\n lpAmount: lpAmount.toString(),\n rewardDebt: rewardDebt.toString(),\n });\n } catch (ignoreError) {\n return new UserBalance({ lpAmount: \"0\", rewardDebt: \"0\" });\n }\n }\n\n async getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo> {\n const provider = this.buildAnchorProvider(token.bridgeAddress);\n const pool = await this.getBridge(token.bridgeAddress, provider).account.pool.fetch(token.poolAddress);\n const vUsdBalance = pool.vUsdBalance.toString();\n const tokenBalance = pool.tokenBalance.toString();\n const imbalance = calculatePoolInfoImbalance({ tokenBalance, vUsdBalance });\n return {\n dValue: pool.d.toString(),\n aValue: pool.a.toString(),\n totalLpAmount: pool.totalLpAmount.toString(),\n vUsdBalance,\n tokenBalance,\n accRewardPerShareP: pool.accRewardPerShareP.toString(),\n p: this.P,\n imbalance,\n };\n }\n\n async buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const { bridge, accounts, preInstructions } = await this.prepareDataForTransaction(params);\n\n const feePayer = getFeePayer(new PublicKey(params.accountAddress), params.txFeeParams);\n\n const tx = await bridge.methods\n .deposit(new BN(params.amount))\n .accounts(accounts)\n .preInstructions(preInstructions)\n .transaction();\n tx.recentBlockhash = (\n await this.buildAnchorProvider(params.accountAddress).connection.getLatestBlockhash()\n ).blockhash;\n tx.feePayer = feePayer;\n await addUnitLimitAndUnitPriceToTx(tx, params.txFeeParams, this.solanaRpcUrl);\n return tx;\n }\n\n async buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawTransaction> {\n const { bridge, accounts, preInstructions } = await this.prepareDataForTransaction(params);\n\n const feePayer = getFeePayer(new PublicKey(params.accountAddress), params.txFeeParams);\n\n const tx = await bridge.methods\n .withdraw(new BN(params.amount))\n .accounts(accounts)\n .preInstructions(preInstructions)\n .transaction();\n tx.recentBlockhash = (\n await this.buildAnchorProvider(params.accountAddress).connection.getLatestBlockhash()\n ).blockhash;\n tx.feePayer = feePayer;\n await addUnitLimitAndUnitPriceToTx(tx, params.txFeeParams, this.solanaRpcUrl);\n return tx;\n }\n\n async buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawTransaction> {\n const { bridge, accounts, preInstructions } = await this.prepareDataForTransaction(params);\n\n const feePayer = getFeePayer(new PublicKey(params.accountAddress), params.txFeeParams);\n\n const tx = await bridge.methods.claimRewards().accounts(accounts).preInstructions(preInstructions).transaction();\n tx.recentBlockhash = (\n await this.buildAnchorProvider(params.accountAddress).connection.getLatestBlockhash()\n ).blockhash;\n tx.feePayer = feePayer;\n await addUnitLimitAndUnitPriceToTx(tx, params.txFeeParams, this.solanaRpcUrl);\n return tx;\n }\n\n private async prepareDataForTransaction(params: LiquidityPoolsParams) {\n const provider = this.buildAnchorProvider(params.accountAddress);\n const bridge = this.getBridge(params.token.bridgeAddress, provider);\n\n const { accounts, preInstructions } = await this._getLPTransactionData(\n bridge,\n params.token.poolAddress,\n params.accountAddress,\n provider\n );\n return { bridge, accounts, preInstructions };\n }\n\n private getBridge(bridgeAddress: string, provider: Provider): Program<BridgeType> {\n return new Program<BridgeType>(bridgeIdl, bridgeAddress, provider);\n }\n\n private buildAnchorProvider(accountAddress: string): Provider {\n const connection = new Connection(this.solanaRpcUrl, \"confirmed\");\n\n const publicKey = new PublicKey(accountAddress);\n\n return new AnchorProvider(\n connection,\n // @ts-expect-error enough wallet for fetch actions\n { publicKey: publicKey },\n {\n preflightCommitment: \"confirmed\",\n commitment: \"confirmed\",\n }\n );\n }\n\n private async _getLPTransactionData(\n bridge: Program<BridgeType>,\n poolAddress: string,\n account: string,\n provider: Provider\n ): Promise<LPTransactionData> {\n const user = new PublicKey(account);\n const configAccount = await getConfigAccount(bridge.programId);\n const bridgeAuthority = await getAuthorityAccount(bridge.programId);\n const poolAccount = new PublicKey(poolAddress);\n const poolAccountInfo = await bridge.account.pool.fetch(poolAccount);\n const tokenMintAccount = poolAccountInfo.mint;\n const userToken = await getAssociatedAccount(user, tokenMintAccount);\n const bridgeTokenAccount = await getBridgeTokenAccount(tokenMintAccount, bridge.programId);\n const userDepositAccount = await getUserDepositAccount(user, tokenMintAccount, bridge.programId);\n\n const preInstructions: TransactionInstruction[] = [\n web3.ComputeBudgetProgram.setComputeUnitLimit({\n units: 1000000,\n }),\n ];\n\n try {\n await getTokenAccountData(userToken, provider);\n } catch (ignoreError) {\n const associatedProgram = Spl.associatedToken(provider);\n const createUserTokenInstruction: TransactionInstruction = await associatedProgram.methods\n .create()\n .accounts({\n mint: tokenMintAccount,\n owner: user,\n associatedAccount: userToken,\n })\n .instruction();\n preInstructions.push(createUserTokenInstruction);\n }\n\n try {\n await bridge.account.userDeposit.fetch(userDepositAccount);\n } catch (ignoreError) {\n const instruction: TransactionInstruction = await bridge.methods\n .initDepositAccount()\n .accounts({\n mint: tokenMintAccount,\n user,\n userDeposit: userDepositAccount,\n })\n .instruction();\n preInstructions.push(instruction);\n }\n\n const accounts: LPAccounts = {\n mint: tokenMintAccount,\n user,\n config: configAccount,\n pool: poolAccount,\n bridgeAuthority: bridgeAuthority,\n userDeposit: userDepositAccount,\n userToken,\n bridgeToken: bridgeTokenAccount,\n };\n\n return { accounts, preInstructions };\n }\n}\n"]}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { ChainType } from "../../../chains/chain.enums";
|
|
2
|
+
import { AllbridgeCoreClient } from "../../../client/core-api/core-client-base";
|
|
3
|
+
import { AllbridgeCoreSdkOptions } from "../../../index";
|
|
4
|
+
import { PoolInfo, TokenWithChainDetails } from "../../../tokens-info";
|
|
5
|
+
import { RawStxTransaction } from "../../models";
|
|
6
|
+
import { ChainPoolService, LiquidityPoolsParams, LiquidityPoolsParamsWithAmount, UserBalanceInfo } from "../models";
|
|
7
|
+
export declare class StxPoolService extends ChainPoolService {
|
|
8
|
+
nodeRpcUrl: string;
|
|
9
|
+
params: AllbridgeCoreSdkOptions;
|
|
10
|
+
api: AllbridgeCoreClient;
|
|
11
|
+
chainType: ChainType.STX;
|
|
12
|
+
private P;
|
|
13
|
+
private A;
|
|
14
|
+
private client;
|
|
15
|
+
constructor(nodeRpcUrl: string, params: AllbridgeCoreSdkOptions, api: AllbridgeCoreClient);
|
|
16
|
+
getUserBalanceInfo(accountAddress: string, token: TokenWithChainDetails): Promise<UserBalanceInfo>;
|
|
17
|
+
getPoolInfoFromChain(token: TokenWithChainDetails): Promise<PoolInfo>;
|
|
18
|
+
buildRawTransactionDeposit(params: LiquidityPoolsParamsWithAmount): Promise<RawStxTransaction>;
|
|
19
|
+
buildRawTransactionWithdraw(params: LiquidityPoolsParamsWithAmount): Promise<RawStxTransaction>;
|
|
20
|
+
buildRawTransactionClaimRewards(params: LiquidityPoolsParams): Promise<RawStxTransaction>;
|
|
21
|
+
}
|