@swapkit/plugins 1.0.0-beta.0 → 1.0.0-beta.10
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/chainflip/index.cjs +2 -2
- package/dist/chainflip/index.cjs.map +4 -4
- package/dist/chainflip/index.js +2 -2
- package/dist/chainflip/index.js.map +4 -4
- package/dist/evm/index.cjs +2 -2
- package/dist/evm/index.cjs.map +3 -3
- package/dist/evm/index.js +2 -2
- package/dist/evm/index.js.map +3 -3
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +4 -3
- package/dist/index.js +2 -1
- package/dist/index.js.map +4 -3
- package/dist/radix/index.cjs.map +1 -1
- package/dist/radix/index.js.map +1 -1
- package/dist/solana/index.cjs +3 -0
- package/dist/solana/index.cjs.map +10 -0
- package/dist/solana/index.js +3 -0
- package/dist/solana/index.js.map +10 -0
- package/dist/thorchain/index.cjs +2 -2
- package/dist/thorchain/index.cjs.map +3 -3
- package/dist/thorchain/index.js +2 -2
- package/dist/thorchain/index.js.map +3 -3
- package/package.json +15 -13
- package/src/chainflip/broker.ts +12 -11
- package/src/chainflip/plugin.ts +3 -8
- package/src/evm/index.ts +1 -1
- package/src/index.ts +2 -3
- package/src/solana/index.ts +1 -0
- package/src/solana/plugin.ts +36 -0
- package/src/thorchain/plugin.ts +10 -11
- package/src/thorchain/types.ts +1 -16
- package/src/types.ts +16 -0
- package/src/utils.ts +30 -0
- package/dist/kado/index.cjs +0 -20
- package/dist/kado/index.cjs.map +0 -12
- package/dist/kado/index.js +0 -20
- package/dist/kado/index.js.map +0 -12
- package/src/kado/helpers.ts +0 -117
- package/src/kado/index.ts +0 -3
- package/src/kado/plugin.ts +0 -234
- package/src/kado/types.ts +0 -225
package/dist/thorchain/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as xx,b as
|
|
1
|
+
import{a as xx,b as Lx}from"../chunk-tvrdndbw.js";import{ApproveMode as A,AssetValue as B,Chain as Z,EVMChains as qx,FeeOption as S,MemoType as m,ProviderName as w,SwapKitError as X,createPlugin as c,getMemoForDeposit as v,getMemoForLeaveAndBond as zx,getMemoForNamePreferredAssetRegister as Hx,getMemoForNameRegister as Jx,getMemoForSaverDeposit as Qx,getMemoForSaverWithdraw as Rx,getMemoForUnbond as Ux,getMemoForWithdraw as Xx,getMinAmountByChain as b,wrapWithThrow as M}from"@swapkit/helpers";import{SwapKitApi as g}from"@swapkit/helpers/api";import{MayaArbitrumVaultAbi as Yx,MayaEthereumVaultAbi as Zx,TCAvalancheDepositABI as $x,TCBaseDepositABI as jx,TCBscDepositABI as kx,TCEthereumVaultAbi as Gx}from"@swapkit/helpers/contracts";import{Chain as e}from"@swapkit/helpers";function W({chain:R,address:N}){if(!N)return!1;switch(R){case e.Bitcoin:return!N.startsWith("bc1p");default:return!0}}function C({assetValue:R,from:N,memo:U="",...O}){return{...O,memo:U,from:N,assetValue:R}}var _x={[S.Average]:1.2,[S.Fast]:1.5,[S.Fastest]:2},Nx={[Z.Avalanche]:$x,[Z.Base]:jx,[Z.BinanceSmartChain]:kx,[Z.Ethereum]:Gx},Ox={[Z.Arbitrum]:Yx,[Z.Ethereum]:Zx},Px=c({name:"thorchain",methods:h(Z.THORChain),properties:{supportedSwapkitProviders:[w.THORCHAIN,w.THORCHAIN_STREAMING]}}),fx=c({name:"mayachain",methods:h(Z.Maya),properties:{supportedSwapkitProviders:[w.MAYACHAIN]}});function Ix(R){return async function N(U){if(R==="thorchain"&&U===Z.THORChain||R==="mayachain"&&U===Z.Maya)return{gas_rate:"0",router:"",address:"",halted:!1,chain:U};let $=(await g.thornode.getInboundAddresses(R)).find((D)=>D.chain===U);if(!$)throw new X("core_inbound_data_not_found");if($?.halted)throw new X("core_chain_halted");return $}}function h(R){return function N({getWallet:U}){let O=R===Z.Maya?"mayachain":"thorchain",$=Ix(O);async function D({assetValue:x,type:L="checkOnly"}){let H=(await $(x.chain)).router,q=x.chain,J=qx.includes(q);if(J&&x.isGasAsset||!J||x.isSynthetic)return Promise.resolve(L==="checkOnly"?!0:"approved");let Q=U(q);if(!Q)throw new X("core_wallet_connection_not_found");let Y=L==="checkOnly"?Q.isApproved:Q.approve;if(!(x.address&&Q.address))throw new X("core_approve_asset_address_or_from_not_found");return Y({amount:x.getBaseValue("bigint"),assetAddress:x.address,from:Q.address,spenderAddress:H})}async function F({assetValue:x,recipient:L,router:H,...q}){let J=O==="thorchain"?Nx:Ox,{chain:z,symbol:Q,ticker:Y}=x,P=U(z);if(!P)throw new X("core_wallet_connection_not_found");let{address:f}=P;if(!W({address:f,chain:z}))throw new X("core_transaction_invalid_sender_address");let _=C({from:f,assetValue:x,recipient:L,router:H,...q});try{let j=J?.[z];if(!j){let I=U(z);return R===z&&L===""?I.deposit(_):I.transfer(_)}let{getChecksumAddressFromAsset:k}=await import("@swapkit/toolboxes/evm");return U(z).call({abi:j,contractAddress:H||(await $(z)).router,funcName:"depositWithExpiry",funcParams:[L,k({chain:z,symbol:Q,ticker:Y},z),x.getBaseValue("string"),_.memo,q.expiration||Number.parseInt(`${(Date.now()+900000)/1000}`)],txOverrides:{from:_.from,value:x.isGasAsset?x.getBaseValue("bigint"):void 0}})}catch(j){let k=typeof j==="string"?j.toLowerCase():j?.message.toLowerCase(),E=k?.includes("insufficient funds"),I=k?.includes("gas"),K=k?.includes("server"),a=k?.includes("user rejected");throw new X(E?"core_transaction_deposit_insufficient_funds_error":I?"core_transaction_deposit_gas_error":K?"core_transaction_deposit_server_error":a?"core_transaction_user_rejected":"core_transaction_deposit_error",j)}}async function y({memo:x,assetValue:L}){let H=await g.thornode.getMimirInfo(O);if(H.HALTCHAINGLOBAL>=1||H.HALTTHORCHAIN>=1)throw new X("thorchain_chain_halted");return F({assetValue:L,recipient:"",memo:x})}async function G({assetValue:x,memo:L,feeOptionKey:H=S.Fast}){let{gas_rate:q="0",router:J,address:z}=await $(x.chain);return F({assetValue:x,recipient:z,memo:L,router:J,feeRate:Number.parseInt(q)*_x[H]})}function V({assetValue:x}){return D({assetValue:x,type:A.Approve})}function p({assetValue:x}){return D({assetValue:x,type:A.CheckOnly})}function n({assetValue:x,...L}){return y({assetValue:x,memo:Jx(L)})}function d({assetValue:x,payoutAddress:L,name:H,ownerAddress:q}){let J=L||U(x.chain)?.address;if(!J)throw new X("thorchain_preferred_asset_payout_required");return y({assetValue:B.from({chain:R}),memo:Hx({asset:x.toString(),chain:x.chain,name:H,owner:q,payout:J})})}function u({type:x,assetValue:L,address:H}){let q=x===m.UNBOND?Ux({address:H,unbondAmount:L.getBaseValue("number")}):zx({type:x,address:H}),J=x===m.BOND?L:b(R);return y({memo:q,assetValue:J})}async function r({baseAssetValue:x,assetValue:L}){if(x.lte(0)||L.lte(0))throw new X("core_transaction_create_liquidity_invalid_params");let H=U(L.chain).address,q=U(R).address,J=await M(()=>{return G({assetValue:x,memo:v({...L,address:H})})},"core_transaction_create_liquidity_base_error"),z=await M(()=>{return G({assetValue:L,memo:v({...L,address:q})})},"core_transaction_create_liquidity_asset_error");return{baseAssetTx:J,assetTx:z}}function o({assetValue:x,poolAddress:L,address:H,symmetric:q}){if(q&&!H)throw new X("core_transaction_add_liquidity_invalid_params");let J=v({chain:L.split(".")[0],symbol:L.split(".")[1],address:q?H:""});return G({assetValue:x,memo:J})}async function i({baseAssetValue:x,assetValue:L,baseAssetAddr:H,assetAddr:q,isPendingSymmAsset:J,mode:z="sym"}){let{chain:Q,symbol:Y}=L,P=z==="sym",f=x?.gt(0)&&(P||z==="baseAsset"),T=L?.gt(0)&&(P||z==="asset"),_=J||f,j=U(R).address,k=_?H||j:"",E=P||z==="asset"?q||U(Q).address:"";if(!(f||T))throw new X("core_transaction_add_liquidity_invalid_params");if(_&&!k)throw new X("core_transaction_add_liquidity_base_address");let I=f&&x?await M(()=>{return G({assetValue:x,memo:v({chain:Q,symbol:Y,address:E})})},"core_transaction_add_liquidity_base_error"):void 0,K=T&&L?await M(()=>{return G({assetValue:L,memo:v({chain:Q,symbol:Y,address:k})})},"core_transaction_add_liquidity_asset_error"):void 0;return{baseAssetTx:I,assetTx:K}}function l({assetValue:x,memo:L,percent:H,type:q}){let{chain:J,symbol:z}=x,Q=q==="add",Y=Q?Qx({symbol:z,chain:J}):Rx({basisPoints:Math.min(1e4,Math.round(H*100)),symbol:z,chain:J});return G({memo:L||Y,assetValue:Q?x:b(J)})}function t({memo:x,assetValue:L,percent:H,from:q,to:J}){let z=J==="baseAsset"&&q!=="baseAsset"?B.from({chain:R}):q==="sym"&&J==="sym"||q==="baseAsset"||q==="asset"?void 0:L,Q=b(q==="asset"?L.chain:R),Y=x||Xx({symbol:L.symbol,chain:L.chain,ticker:L.ticker,basisPoints:Math.min(1e4,Math.round(H*100)),targetAsset:z?.toString()});return G({assetValue:Q,memo:Y})}async function s({feeOptionKey:x,route:L}){let{memo:H,expiration:q,targetAddress:J}=L,z=await B.from({asyncTokenLookup:!0,asset:L.sellAsset,value:L.sellAmount});if(!z)throw new X("core_swap_asset_not_recognized");if(!W({address:L.destinationAddress,chain:B.from({asset:L.buyAsset}).chain}))throw new X("core_transaction_invalid_recipient_address");let{address:Y}=await $(z.chain);return F({expiration:Number(q),assetValue:z,memo:H,feeOptionKey:x,router:J,recipient:Y})}return{addLiquidity:i,addLiquidityPart:o,approveAssetValue:V,createLiquidity:r,deposit:F,depositToPool:G,getInboundDataByChain:$,isAssetValueApproved:p,nodeAction:u,registerName:n,registerPreferredAsset:d,savings:l,swap:s,withdraw:t}}}export{W as validateAddressType,Px as ThorchainPlugin,fx as MayachainPlugin};
|
|
2
2
|
|
|
3
|
-
//# debugId=
|
|
3
|
+
//# debugId=1C74BBA1E3F5AA4864756E2164756E21
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/thorchain/plugin.ts", "../src/thorchain/shared.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import {\n ApproveMode,\n type ApproveReturnType,\n AssetValue,\n Chain,\n type EVMChain,\n EVMChains,\n type ErrorKeys,\n FeeOption,\n MemoType,\n ProviderName,\n SwapKitError,\n type SwapKitPluginParams,\n type SwapParams,\n createPlugin,\n getMemoForDeposit,\n getMemoForLeaveAndBond,\n getMemoForNamePreferredAssetRegister,\n getMemoForNameRegister,\n getMemoForSaverDeposit,\n getMemoForSaverWithdraw,\n getMemoForUnbond,\n getMemoForWithdraw,\n getMinAmountByChain,\n wrapWithThrow,\n} from \"@swapkit/helpers\";\nimport { type QuoteResponseRoute, SwapKitApi, type THORNodeType } from \"@swapkit/helpers/api\";\nimport {\n MayaArbitrumVaultAbi,\n MayaEthereumVaultAbi,\n TCAvalancheDepositABI,\n TCBaseDepositABI,\n TCBscDepositABI,\n TCEthereumVaultAbi,\n} from \"@swapkit/helpers/contracts\";\n\nimport { prepareTxParams, validateAddressType } from \"./shared\";\nimport type {\n AddLiquidityParams,\n AddLiquidityPartParams,\n ApproveParams,\n CoreTxParams,\n CreateLiquidityParams,\n NodeActionParams,\n RegisterThornameParams,\n SavingsParams,\n SupportedChain,\n WithdrawParams,\n} from \"./types\";\n\nconst gasFeeMultiplier: Record<FeeOption, number> = {\n [FeeOption.Average]: 1.2,\n [FeeOption.Fast]: 1.5,\n [FeeOption.Fastest]: 2,\n};\n\nconst TCSpecificAbi = {\n [Chain.Avalanche]: TCAvalancheDepositABI,\n [Chain.Base]: TCBaseDepositABI,\n [Chain.BinanceSmartChain]: TCBscDepositABI,\n [Chain.Ethereum]: TCEthereumVaultAbi,\n};\n\nconst MayaSpecificAbi = {\n [Chain.Arbitrum]: MayaArbitrumVaultAbi,\n [Chain.Ethereum]: MayaEthereumVaultAbi,\n};\n\nexport const ThorchainPlugin = createPlugin({\n name: \"thorchain\",\n methods: createTCBasedPlugin(Chain.THORChain),\n properties: {\n supportedSwapkitProviders: [ProviderName.THORCHAIN, ProviderName.THORCHAIN_STREAMING],\n },\n});\n\nexport const MayachainPlugin = createPlugin({\n name: \"mayachain\",\n methods: createTCBasedPlugin(Chain.Maya),\n properties: {\n supportedSwapkitProviders: [ProviderName.MAYACHAIN],\n },\n});\n\nfunction getInboundDataFunction(type?: THORNodeType) {\n return async function getInboundDataByChain<T extends Chain>(chain: T) {\n if (\n (type === \"thorchain\" && chain === Chain.THORChain) ||\n (type === \"mayachain\" && chain === Chain.Maya)\n ) {\n return { gas_rate: \"0\", router: \"\", address: \"\", halted: false, chain };\n }\n\n const inboundData = await SwapKitApi.thornode.getInboundAddresses(type);\n const chainAddressData = inboundData.find((item) => item.chain === chain);\n\n if (!chainAddressData) throw new SwapKitError(\"core_inbound_data_not_found\");\n if (chainAddressData?.halted) throw new SwapKitError(\"core_chain_halted\");\n\n return chainAddressData;\n };\n}\n\ntype PluginChain = Chain.Maya | Chain.THORChain;\n\nfunction createTCBasedPlugin<T extends PluginChain>(pluginChain: T) {\n return function plugin({ getWallet }: SwapKitPluginParams) {\n const pluginType = pluginChain === Chain.Maya ? \"mayachain\" : \"thorchain\";\n const getInboundDataByChain = getInboundDataFunction(pluginType);\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor/split\n async function approve<T extends ApproveMode>({\n assetValue,\n type = \"checkOnly\" as T,\n }: { type: T; assetValue: AssetValue }) {\n const router = (await getInboundDataByChain(assetValue.chain)).router as string;\n\n const chain = assetValue.chain as EVMChain;\n\n const isEVMChain = EVMChains.includes(chain as EVMChain);\n const isNativeEVM = isEVMChain && assetValue.isGasAsset;\n\n if (isNativeEVM || !isEVMChain || assetValue.isSynthetic) {\n return Promise.resolve(type === \"checkOnly\" ? true : \"approved\") as ApproveReturnType<T>;\n }\n\n const wallet = getWallet(chain);\n\n if (!wallet) {\n throw new SwapKitError(\"core_wallet_connection_not_found\");\n }\n\n const walletAction = type === \"checkOnly\" ? wallet.isApproved : wallet.approve;\n\n if (!(assetValue.address && wallet.address)) {\n throw new SwapKitError(\"core_approve_asset_address_or_from_not_found\");\n }\n\n return walletAction({\n amount: assetValue.getBaseValue(\"bigint\"),\n assetAddress: assetValue.address,\n from: wallet.address,\n spenderAddress: router,\n });\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO refactor\n async function deposit({\n assetValue,\n recipient,\n router,\n ...rest\n }: CoreTxParams & { router?: string }) {\n const abis = pluginType === \"thorchain\" ? TCSpecificAbi : MayaSpecificAbi;\n const { chain, symbol, ticker } = assetValue;\n\n const wallet = getWallet(chain as SupportedChain);\n if (!wallet) {\n throw new SwapKitError(\"core_wallet_connection_not_found\");\n }\n const { address } = wallet;\n const isAddressValidated = validateAddressType({ address, chain });\n if (!isAddressValidated) {\n throw new SwapKitError(\"core_transaction_invalid_sender_address\");\n }\n\n const params = prepareTxParams({ from: address, assetValue, recipient, router, ...rest });\n\n try {\n const abi = abis?.[chain as keyof typeof abis];\n\n if (!abi) {\n const wallet = getWallet(chain as PluginChain);\n const shouldDeposit = pluginChain === chain && recipient === \"\";\n return shouldDeposit ? wallet.deposit(params) : wallet.transfer(params);\n }\n\n const { getChecksumAddressFromAsset } = await import(\"@swapkit/toolboxes/evm\");\n const wallet = getWallet(chain as EVMChain);\n\n return wallet.call<string>({\n abi,\n contractAddress: router || ((await getInboundDataByChain(chain)).router as string),\n funcName: \"depositWithExpiry\",\n funcParams: [\n recipient,\n getChecksumAddressFromAsset({ chain, symbol, ticker }, chain as EVMChain),\n assetValue.getBaseValue(\"string\"),\n params.memo,\n rest.expiration || Number.parseInt(`${(Date.now() + 15 * 60 * 1000) / 1000}`),\n ],\n txOverrides: {\n from: params.from,\n value: assetValue.isGasAsset ? assetValue.getBaseValue(\"bigint\") : undefined,\n },\n });\n } catch (error) {\n const errorMessage =\n // @ts-expect-error Fine to use error as string\n typeof error === \"string\" ? error.toLowerCase() : error?.message.toLowerCase();\n const isInsufficientFunds = errorMessage?.includes(\"insufficient funds\");\n const isGas = errorMessage?.includes(\"gas\");\n const isServer = errorMessage?.includes(\"server\");\n const isUserRejected = errorMessage?.includes(\"user rejected\");\n const errorKey: ErrorKeys = isInsufficientFunds\n ? \"core_transaction_deposit_insufficient_funds_error\"\n : isGas\n ? \"core_transaction_deposit_gas_error\"\n : isServer\n ? \"core_transaction_deposit_server_error\"\n : isUserRejected\n ? \"core_transaction_user_rejected\"\n : \"core_transaction_deposit_error\";\n\n throw new SwapKitError(errorKey, error);\n }\n }\n\n async function depositToProtocol({\n memo,\n assetValue,\n }: { assetValue: AssetValue; memo: string }) {\n const mimir = await SwapKitApi.thornode.getMimirInfo(pluginType);\n\n // check if trading is halted or not\n if (mimir.HALTCHAINGLOBAL >= 1 || mimir.HALTTHORCHAIN >= 1) {\n throw new SwapKitError(\"thorchain_chain_halted\");\n }\n\n return deposit({ assetValue, recipient: \"\", memo });\n }\n\n async function depositToPool({\n assetValue,\n memo,\n feeOptionKey = FeeOption.Fast,\n }: { assetValue: AssetValue; memo: string; feeOptionKey?: FeeOption }) {\n const {\n gas_rate = \"0\",\n router,\n address: poolAddress,\n } = await getInboundDataByChain(assetValue.chain);\n\n return deposit({\n assetValue,\n recipient: poolAddress,\n memo,\n router,\n feeRate: Number.parseInt(gas_rate) * gasFeeMultiplier[feeOptionKey],\n });\n }\n\n function approveAssetValue(params: ApproveParams) {\n return approve({ ...params, type: ApproveMode.Approve });\n }\n\n function isAssetValueApproved(params: ApproveParams) {\n return approve({ ...params, type: ApproveMode.CheckOnly });\n }\n\n function registerName({ assetValue, ...params }: RegisterThornameParams) {\n return depositToProtocol({ assetValue, memo: getMemoForNameRegister(params) });\n }\n\n function registerPreferredAsset({\n assetValue,\n payoutAddress,\n name,\n ownerAddress,\n }: {\n assetValue: AssetValue;\n payoutAddress?: string;\n name: string;\n ownerAddress: string;\n }) {\n const payout = payoutAddress || getWallet(assetValue.chain as SupportedChain)?.address;\n\n if (!payout) {\n throw new SwapKitError(\"thorchain_preferred_asset_payout_required\");\n }\n\n return depositToProtocol({\n assetValue: AssetValue.from({ chain: pluginChain }),\n memo: getMemoForNamePreferredAssetRegister({\n asset: assetValue.toString(),\n chain: assetValue.chain,\n name,\n owner: ownerAddress,\n payout,\n }),\n });\n }\n\n function nodeAction({ type, assetValue, address }: NodeActionParams) {\n const memo =\n type === MemoType.UNBOND\n ? getMemoForUnbond({ address, unbondAmount: assetValue.getBaseValue(\"number\") })\n : getMemoForLeaveAndBond({ type, address });\n\n const assetToTransfer =\n type === MemoType.BOND ? assetValue : getMinAmountByChain(pluginChain);\n return depositToProtocol({ memo, assetValue: assetToTransfer });\n }\n\n async function createLiquidity({ baseAssetValue, assetValue }: CreateLiquidityParams) {\n if (baseAssetValue.lte(0) || assetValue.lte(0)) {\n throw new SwapKitError(\"core_transaction_create_liquidity_invalid_params\");\n }\n\n const assetAddress = getWallet(assetValue.chain as SupportedChain).address;\n const baseAssetAddress = getWallet(pluginChain).address;\n\n const baseAssetTx = await wrapWithThrow(() => {\n return depositToPool({\n assetValue: baseAssetValue,\n memo: getMemoForDeposit({ ...assetValue, address: assetAddress }),\n });\n }, \"core_transaction_create_liquidity_base_error\");\n\n const assetTx = await wrapWithThrow(() => {\n return depositToPool({\n assetValue,\n memo: getMemoForDeposit({ ...assetValue, address: baseAssetAddress }),\n });\n }, \"core_transaction_create_liquidity_asset_error\");\n\n return { baseAssetTx, assetTx };\n }\n\n function addLiquidityPart({\n assetValue,\n poolAddress,\n address,\n symmetric,\n }: AddLiquidityPartParams) {\n if (symmetric && !address) {\n throw new SwapKitError(\"core_transaction_add_liquidity_invalid_params\");\n }\n const memo = getMemoForDeposit({\n chain: poolAddress.split(\".\")[0] as Chain,\n symbol: poolAddress.split(\".\")[1] as string,\n address: symmetric ? address : \"\",\n });\n\n return depositToPool({ assetValue, memo });\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: Refactor\n async function addLiquidity({\n baseAssetValue,\n assetValue,\n baseAssetAddr,\n assetAddr,\n isPendingSymmAsset,\n mode = \"sym\",\n }: AddLiquidityParams) {\n const { chain, symbol } = assetValue;\n const isSym = mode === \"sym\";\n const baseTransfer = baseAssetValue?.gt(0) && (isSym || mode === \"baseAsset\");\n const assetTransfer = assetValue?.gt(0) && (isSym || mode === \"asset\");\n const includeBaseAddress = isPendingSymmAsset || baseTransfer;\n const baseAssetWalletAddress = getWallet(pluginChain).address;\n\n const baseAddress = includeBaseAddress ? baseAssetAddr || baseAssetWalletAddress : \"\";\n const assetAddress =\n isSym || mode === \"asset\" ? assetAddr || getWallet(chain as SupportedChain).address : \"\";\n\n if (!(baseTransfer || assetTransfer)) {\n throw new SwapKitError(\"core_transaction_add_liquidity_invalid_params\");\n }\n if (includeBaseAddress && !baseAddress) {\n throw new SwapKitError(\"core_transaction_add_liquidity_base_address\");\n }\n\n const baseAssetTx =\n baseTransfer && baseAssetValue\n ? await wrapWithThrow(() => {\n return depositToPool({\n assetValue: baseAssetValue,\n memo: getMemoForDeposit({ chain, symbol, address: assetAddress }),\n });\n }, \"core_transaction_add_liquidity_base_error\")\n : undefined;\n\n const assetTx =\n assetTransfer && assetValue\n ? await wrapWithThrow(() => {\n return depositToPool({\n assetValue,\n memo: getMemoForDeposit({ chain, symbol, address: baseAddress }),\n });\n }, \"core_transaction_add_liquidity_asset_error\")\n : undefined;\n\n return { baseAssetTx, assetTx };\n }\n\n function savings({ assetValue, memo, percent, type }: SavingsParams) {\n const { chain, symbol } = assetValue;\n const isDeposit = type === \"add\";\n const memoString = isDeposit\n ? getMemoForSaverDeposit({ symbol, chain })\n : getMemoForSaverWithdraw({\n basisPoints: Math.min(10000, Math.round(percent * 100)),\n symbol,\n chain,\n });\n\n return depositToPool({\n memo: memo || memoString,\n assetValue: isDeposit ? assetValue : getMinAmountByChain(chain),\n });\n }\n\n function withdraw({ memo, assetValue, percent, from, to }: WithdrawParams) {\n const targetAsset =\n to === \"baseAsset\" && from !== \"baseAsset\"\n ? AssetValue.from({ chain: pluginChain })\n : (from === \"sym\" && to === \"sym\") || from === \"baseAsset\" || from === \"asset\"\n ? undefined\n : assetValue;\n\n const value = getMinAmountByChain(from === \"asset\" ? assetValue.chain : pluginChain);\n const memoString =\n memo ||\n getMemoForWithdraw({\n symbol: assetValue.symbol,\n chain: assetValue.chain,\n ticker: assetValue.ticker,\n basisPoints: Math.min(10000, Math.round(percent * 100)),\n targetAsset: targetAsset?.toString(),\n });\n\n return depositToPool({ assetValue: value, memo: memoString });\n }\n\n async function swap({\n feeOptionKey,\n route,\n }: SwapParams<typeof pluginType, QuoteResponseRoute>) {\n const { memo, expiration, targetAddress } = route;\n\n const assetValue = await AssetValue.from({\n asyncTokenLookup: true,\n asset: route.sellAsset,\n value: route.sellAmount,\n });\n\n if (!assetValue) {\n throw new SwapKitError(\"core_swap_asset_not_recognized\");\n }\n\n const isRecipientValidated = validateAddressType({\n address: route.destinationAddress,\n chain: AssetValue.from({ asset: route.buyAsset }).chain,\n });\n\n if (!isRecipientValidated) {\n throw new SwapKitError(\"core_transaction_invalid_recipient_address\");\n }\n\n const { address: recipient } = await getInboundDataByChain(assetValue.chain);\n\n return deposit({\n expiration: Number(expiration),\n assetValue,\n memo,\n feeOptionKey,\n router: targetAddress,\n recipient,\n });\n }\n\n return {\n addLiquidity,\n addLiquidityPart,\n approveAssetValue,\n createLiquidity,\n deposit,\n depositToPool,\n getInboundDataByChain,\n isAssetValueApproved,\n nodeAction,\n registerName,\n registerPreferredAsset,\n savings,\n swap,\n withdraw,\n };\n };\n}\n",
|
|
5
|
+
"import {\n ApproveMode,\n type ApproveReturnType,\n AssetValue,\n Chain,\n type CryptoChain,\n type EVMChain,\n EVMChains,\n type ErrorKeys,\n FeeOption,\n MemoType,\n ProviderName,\n SwapKitError,\n type SwapKitPluginParams,\n type SwapParams,\n createPlugin,\n getMemoForDeposit,\n getMemoForLeaveAndBond,\n getMemoForNamePreferredAssetRegister,\n getMemoForNameRegister,\n getMemoForSaverDeposit,\n getMemoForSaverWithdraw,\n getMemoForUnbond,\n getMemoForWithdraw,\n getMinAmountByChain,\n wrapWithThrow,\n} from \"@swapkit/helpers\";\nimport { type QuoteResponseRoute, SwapKitApi, type THORNodeType } from \"@swapkit/helpers/api\";\nimport {\n MayaArbitrumVaultAbi,\n MayaEthereumVaultAbi,\n TCAvalancheDepositABI,\n TCBaseDepositABI,\n TCBscDepositABI,\n TCEthereumVaultAbi,\n} from \"@swapkit/helpers/contracts\";\nimport { prepareTxParams, validateAddressType } from \"./shared\";\nimport type {\n AddLiquidityParams,\n AddLiquidityPartParams,\n CoreTxParams,\n CreateLiquidityParams,\n NodeActionParams,\n RegisterThornameParams,\n SavingsParams,\n WithdrawParams,\n} from \"./types\";\n\nconst gasFeeMultiplier: Record<FeeOption, number> = {\n [FeeOption.Average]: 1.2,\n [FeeOption.Fast]: 1.5,\n [FeeOption.Fastest]: 2,\n};\n\nconst TCSpecificAbi = {\n [Chain.Avalanche]: TCAvalancheDepositABI,\n [Chain.Base]: TCBaseDepositABI,\n [Chain.BinanceSmartChain]: TCBscDepositABI,\n [Chain.Ethereum]: TCEthereumVaultAbi,\n};\n\nconst MayaSpecificAbi = {\n [Chain.Arbitrum]: MayaArbitrumVaultAbi,\n [Chain.Ethereum]: MayaEthereumVaultAbi,\n};\n\nexport const ThorchainPlugin = createPlugin({\n name: \"thorchain\",\n methods: createTCBasedPlugin(Chain.THORChain),\n properties: {\n supportedSwapkitProviders: [ProviderName.THORCHAIN, ProviderName.THORCHAIN_STREAMING],\n },\n});\n\nexport const MayachainPlugin = createPlugin({\n name: \"mayachain\",\n methods: createTCBasedPlugin(Chain.Maya),\n properties: {\n supportedSwapkitProviders: [ProviderName.MAYACHAIN],\n },\n});\n\nfunction getInboundDataFunction(type?: THORNodeType) {\n return async function getInboundDataByChain<T extends Chain>(chain: T) {\n if (\n (type === \"thorchain\" && chain === Chain.THORChain) ||\n (type === \"mayachain\" && chain === Chain.Maya)\n ) {\n return { gas_rate: \"0\", router: \"\", address: \"\", halted: false, chain };\n }\n\n const inboundData = await SwapKitApi.thornode.getInboundAddresses(type);\n const chainAddressData = inboundData.find((item) => item.chain === chain);\n\n if (!chainAddressData) throw new SwapKitError(\"core_inbound_data_not_found\");\n if (chainAddressData?.halted) throw new SwapKitError(\"core_chain_halted\");\n\n return chainAddressData;\n };\n}\n\ntype PluginChain = Chain.Maya | Chain.THORChain;\n\nfunction createTCBasedPlugin<T extends PluginChain>(pluginChain: T) {\n return function plugin({ getWallet }: SwapKitPluginParams) {\n const pluginType = pluginChain === Chain.Maya ? \"mayachain\" : \"thorchain\";\n const getInboundDataByChain = getInboundDataFunction(pluginType);\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: refactor/split\n async function approve<T extends ApproveMode>({\n assetValue,\n type = \"checkOnly\" as T,\n }: { type: T; assetValue: AssetValue }) {\n const router = (await getInboundDataByChain(assetValue.chain)).router as string;\n\n const chain = assetValue.chain as EVMChain;\n\n const isEVMChain = EVMChains.includes(chain as EVMChain);\n const isNativeEVM = isEVMChain && assetValue.isGasAsset;\n\n if (isNativeEVM || !isEVMChain || assetValue.isSynthetic) {\n return Promise.resolve(type === \"checkOnly\" ? true : \"approved\") as ApproveReturnType<T>;\n }\n\n const wallet = getWallet(chain);\n\n if (!wallet) {\n throw new SwapKitError(\"core_wallet_connection_not_found\");\n }\n\n const walletAction = type === \"checkOnly\" ? wallet.isApproved : wallet.approve;\n\n if (!(assetValue.address && wallet.address)) {\n throw new SwapKitError(\"core_approve_asset_address_or_from_not_found\");\n }\n\n return walletAction({\n amount: assetValue.getBaseValue(\"bigint\"),\n assetAddress: assetValue.address,\n from: wallet.address,\n spenderAddress: router,\n });\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO refactor\n async function deposit({\n assetValue,\n recipient,\n router,\n ...rest\n }: CoreTxParams & { router?: string }) {\n const abis = pluginType === \"thorchain\" ? TCSpecificAbi : MayaSpecificAbi;\n const { chain, symbol, ticker } = assetValue;\n\n const wallet = getWallet(chain as CryptoChain);\n if (!wallet) {\n throw new SwapKitError(\"core_wallet_connection_not_found\");\n }\n const { address } = wallet;\n const isAddressValidated = validateAddressType({ address, chain });\n if (!isAddressValidated) {\n throw new SwapKitError(\"core_transaction_invalid_sender_address\");\n }\n\n const params = prepareTxParams({ from: address, assetValue, recipient, router, ...rest });\n\n try {\n const abi = abis?.[chain as keyof typeof abis];\n\n if (!abi) {\n const wallet = getWallet(chain as PluginChain);\n const shouldDeposit = pluginChain === chain && recipient === \"\";\n // @Towan: Is that the same action? :)\n return shouldDeposit ? wallet.deposit(params) : wallet.transfer(params);\n }\n\n const { getChecksumAddressFromAsset } = await import(\"@swapkit/toolboxes/evm\");\n const wallet = getWallet(chain as EVMChain);\n\n return wallet.call<string>({\n abi,\n contractAddress: router || ((await getInboundDataByChain(chain)).router as string),\n funcName: \"depositWithExpiry\",\n funcParams: [\n recipient,\n getChecksumAddressFromAsset({ chain, symbol, ticker }, chain as EVMChain),\n assetValue.getBaseValue(\"string\"),\n params.memo,\n rest.expiration || Number.parseInt(`${(Date.now() + 15 * 60 * 1000) / 1000}`),\n ],\n txOverrides: {\n from: params.from,\n value: assetValue.isGasAsset ? assetValue.getBaseValue(\"bigint\") : undefined,\n },\n });\n } catch (error) {\n const errorMessage =\n // @ts-expect-error Fine to use error as string\n typeof error === \"string\" ? error.toLowerCase() : error?.message.toLowerCase();\n const isInsufficientFunds = errorMessage?.includes(\"insufficient funds\");\n const isGas = errorMessage?.includes(\"gas\");\n const isServer = errorMessage?.includes(\"server\");\n const isUserRejected = errorMessage?.includes(\"user rejected\");\n const errorKey: ErrorKeys = isInsufficientFunds\n ? \"core_transaction_deposit_insufficient_funds_error\"\n : isGas\n ? \"core_transaction_deposit_gas_error\"\n : isServer\n ? \"core_transaction_deposit_server_error\"\n : isUserRejected\n ? \"core_transaction_user_rejected\"\n : \"core_transaction_deposit_error\";\n\n throw new SwapKitError(errorKey, error);\n }\n }\n\n async function depositToProtocol({\n memo,\n assetValue,\n }: { assetValue: AssetValue; memo: string }) {\n const mimir = await SwapKitApi.thornode.getMimirInfo(pluginType);\n\n // check if trading is halted or not\n if (mimir.HALTCHAINGLOBAL >= 1 || mimir.HALTTHORCHAIN >= 1) {\n throw new SwapKitError(\"thorchain_chain_halted\");\n }\n\n return deposit({ assetValue, recipient: \"\", memo });\n }\n\n async function depositToPool({\n assetValue,\n memo,\n feeOptionKey = FeeOption.Fast,\n }: { assetValue: AssetValue; memo: string; feeOptionKey?: FeeOption }) {\n const {\n gas_rate = \"0\",\n router,\n address: poolAddress,\n } = await getInboundDataByChain(assetValue.chain);\n\n return deposit({\n assetValue,\n recipient: poolAddress,\n memo,\n router,\n feeRate: Number.parseInt(gas_rate) * gasFeeMultiplier[feeOptionKey],\n });\n }\n\n function approveAssetValue({ assetValue }: { assetValue: AssetValue }) {\n return approve({ assetValue, type: ApproveMode.Approve });\n }\n\n function isAssetValueApproved({ assetValue }: { assetValue: AssetValue }) {\n return approve({ assetValue, type: ApproveMode.CheckOnly });\n }\n\n function registerName({ assetValue, ...params }: RegisterThornameParams) {\n return depositToProtocol({ assetValue, memo: getMemoForNameRegister(params) });\n }\n\n function registerPreferredAsset({\n assetValue,\n payoutAddress,\n name,\n ownerAddress,\n }: {\n assetValue: AssetValue;\n payoutAddress?: string;\n name: string;\n ownerAddress: string;\n }) {\n const payout = payoutAddress || getWallet(assetValue.chain as CryptoChain)?.address;\n\n if (!payout) {\n throw new SwapKitError(\"thorchain_preferred_asset_payout_required\");\n }\n\n return depositToProtocol({\n assetValue: AssetValue.from({ chain: pluginChain }),\n memo: getMemoForNamePreferredAssetRegister({\n asset: assetValue.toString(),\n chain: assetValue.chain,\n name,\n owner: ownerAddress,\n payout,\n }),\n });\n }\n\n function nodeAction({ type, assetValue, address }: NodeActionParams) {\n const memo =\n type === MemoType.UNBOND\n ? getMemoForUnbond({ address, unbondAmount: assetValue.getBaseValue(\"number\") })\n : getMemoForLeaveAndBond({ type, address });\n\n const assetToTransfer =\n type === MemoType.BOND ? assetValue : getMinAmountByChain(pluginChain);\n return depositToProtocol({ memo, assetValue: assetToTransfer });\n }\n\n async function createLiquidity({ baseAssetValue, assetValue }: CreateLiquidityParams) {\n if (baseAssetValue.lte(0) || assetValue.lte(0)) {\n throw new SwapKitError(\"core_transaction_create_liquidity_invalid_params\");\n }\n\n const assetAddress = getWallet(assetValue.chain as CryptoChain).address;\n const baseAssetAddress = getWallet(pluginChain).address;\n\n const baseAssetTx = await wrapWithThrow(() => {\n return depositToPool({\n assetValue: baseAssetValue,\n memo: getMemoForDeposit({ ...assetValue, address: assetAddress }),\n });\n }, \"core_transaction_create_liquidity_base_error\");\n\n const assetTx = await wrapWithThrow(() => {\n return depositToPool({\n assetValue,\n memo: getMemoForDeposit({ ...assetValue, address: baseAssetAddress }),\n });\n }, \"core_transaction_create_liquidity_asset_error\");\n\n return { baseAssetTx, assetTx };\n }\n\n function addLiquidityPart({\n assetValue,\n poolAddress,\n address,\n symmetric,\n }: AddLiquidityPartParams) {\n if (symmetric && !address) {\n throw new SwapKitError(\"core_transaction_add_liquidity_invalid_params\");\n }\n const memo = getMemoForDeposit({\n chain: poolAddress.split(\".\")[0] as Chain,\n symbol: poolAddress.split(\".\")[1] as string,\n address: symmetric ? address : \"\",\n });\n\n return depositToPool({ assetValue, memo });\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TODO: Refactor\n async function addLiquidity({\n baseAssetValue,\n assetValue,\n baseAssetAddr,\n assetAddr,\n isPendingSymmAsset,\n mode = \"sym\",\n }: AddLiquidityParams) {\n const { chain, symbol } = assetValue;\n const isSym = mode === \"sym\";\n const baseTransfer = baseAssetValue?.gt(0) && (isSym || mode === \"baseAsset\");\n const assetTransfer = assetValue?.gt(0) && (isSym || mode === \"asset\");\n const includeBaseAddress = isPendingSymmAsset || baseTransfer;\n const baseAssetWalletAddress = getWallet(pluginChain).address;\n\n const baseAddress = includeBaseAddress ? baseAssetAddr || baseAssetWalletAddress : \"\";\n const assetAddress =\n isSym || mode === \"asset\" ? assetAddr || getWallet(chain as CryptoChain).address : \"\";\n\n if (!(baseTransfer || assetTransfer)) {\n throw new SwapKitError(\"core_transaction_add_liquidity_invalid_params\");\n }\n if (includeBaseAddress && !baseAddress) {\n throw new SwapKitError(\"core_transaction_add_liquidity_base_address\");\n }\n\n const baseAssetTx =\n baseTransfer && baseAssetValue\n ? await wrapWithThrow(() => {\n return depositToPool({\n assetValue: baseAssetValue,\n memo: getMemoForDeposit({ chain, symbol, address: assetAddress }),\n });\n }, \"core_transaction_add_liquidity_base_error\")\n : undefined;\n\n const assetTx =\n assetTransfer && assetValue\n ? await wrapWithThrow(() => {\n return depositToPool({\n assetValue,\n memo: getMemoForDeposit({ chain, symbol, address: baseAddress }),\n });\n }, \"core_transaction_add_liquidity_asset_error\")\n : undefined;\n\n return { baseAssetTx, assetTx };\n }\n\n function savings({ assetValue, memo, percent, type }: SavingsParams) {\n const { chain, symbol } = assetValue;\n const isDeposit = type === \"add\";\n const memoString = isDeposit\n ? getMemoForSaverDeposit({ symbol, chain })\n : getMemoForSaverWithdraw({\n basisPoints: Math.min(10000, Math.round(percent * 100)),\n symbol,\n chain,\n });\n\n return depositToPool({\n memo: memo || memoString,\n assetValue: isDeposit ? assetValue : getMinAmountByChain(chain),\n });\n }\n\n function withdraw({ memo, assetValue, percent, from, to }: WithdrawParams) {\n const targetAsset =\n to === \"baseAsset\" && from !== \"baseAsset\"\n ? AssetValue.from({ chain: pluginChain })\n : (from === \"sym\" && to === \"sym\") || from === \"baseAsset\" || from === \"asset\"\n ? undefined\n : assetValue;\n\n const value = getMinAmountByChain(from === \"asset\" ? assetValue.chain : pluginChain);\n const memoString =\n memo ||\n getMemoForWithdraw({\n symbol: assetValue.symbol,\n chain: assetValue.chain,\n ticker: assetValue.ticker,\n basisPoints: Math.min(10000, Math.round(percent * 100)),\n targetAsset: targetAsset?.toString(),\n });\n\n return depositToPool({ assetValue: value, memo: memoString });\n }\n\n async function swap({\n feeOptionKey,\n route,\n }: SwapParams<typeof pluginType, QuoteResponseRoute>) {\n const { memo, expiration, targetAddress } = route;\n\n const assetValue = await AssetValue.from({\n asyncTokenLookup: true,\n asset: route.sellAsset,\n value: route.sellAmount,\n });\n\n if (!assetValue) {\n throw new SwapKitError(\"core_swap_asset_not_recognized\");\n }\n\n const isRecipientValidated = validateAddressType({\n address: route.destinationAddress,\n chain: AssetValue.from({ asset: route.buyAsset }).chain,\n });\n\n if (!isRecipientValidated) {\n throw new SwapKitError(\"core_transaction_invalid_recipient_address\");\n }\n\n const { address: recipient } = await getInboundDataByChain(assetValue.chain);\n\n return deposit({\n expiration: Number(expiration),\n assetValue,\n memo,\n feeOptionKey,\n router: targetAddress,\n recipient,\n });\n }\n\n return {\n addLiquidity,\n addLiquidityPart,\n approveAssetValue,\n createLiquidity,\n deposit,\n depositToPool,\n getInboundDataByChain,\n isAssetValueApproved,\n nodeAction,\n registerName,\n registerPreferredAsset,\n savings,\n swap,\n withdraw,\n };\n };\n}\n",
|
|
6
6
|
"import { Chain } from \"@swapkit/helpers\";\nimport type { CoreTxParams } from \"./types\";\n\nexport function validateAddressType({ chain, address }: { chain?: Chain; address?: string }) {\n if (!address) return false;\n\n switch (chain) {\n case Chain.Bitcoin:\n // filter out taproot addresses\n return !address.startsWith(\"bc1p\");\n default:\n return true;\n }\n}\n\nexport function prepareTxParams({\n assetValue,\n from,\n memo = \"\",\n ...restTxParams\n}: CoreTxParams & { from: string; router?: string }) {\n return { ...restTxParams, memo, from, assetValue };\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": "kDAAA,sBACE,gBAEA,WACA,
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": "kDAAA,sBACE,gBAEA,WACA,eAGA,gBAEA,cACA,kBACA,kBACA,kBAGA,uBACA,4BACA,2CACA,6BACA,6BACA,8BACA,uBACA,yBACA,0BACA,mBACA,yBAEF,qBAAkC,6BAClC,+BACE,2BACA,4BACA,uBACA,sBACA,yBACA,oCClCF,gBAAS,yBAGF,SAAS,CAAmB,EAAG,QAAO,WAAgD,CAC3F,IAAK,EAAS,MAAO,GAErB,OAAQ,QACD,EAAM,QAET,OAAQ,EAAQ,WAAW,MAAM,UAEjC,MAAO,IAIN,SAAS,CAA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AAG,OAAM,aAAY,UAAS,OAAM,MAAsB,CACzE,IAAM,EACJ,IAAO,aAAe,IAAS,YAC3B,EAAW,KAAK,CAAE,MAAO,CAAY,CAAC,EACrC,IAAS,OAAS,IAAO,OAAU,IAAS,aAAe,IAAS,QACnE,OACA,EAEF,EAAQ,EAAoB,IAAS,QAAU,EAAW,MAAQ,CAAW,EAC7E,EACJ,GACA,GAAmB,CACjB,OAAQ,EAAW,OACnB,MAAO,EAAW,MAClB,OAAQ,EAAW,OACnB,YAAa,KAAK,IAAI,IAAO,KAAK,MAAM,EAAU,GAAG,CAAC,EACtD,YAAa,GAAa,SAAS,CACrC,CAAC,EAEH,OAAO,EAAc,CAAE,WAAY,EAAO,KAAM,CAAW,CAAC,EAG9D,eAAe,CAAI,EACjB,eACA,SACoD,CACpD,IAAQ,OAAM,aAAY,iBAAkB,EAEtC,EAAa,MAAM,EAAW,KAAK,CACvC,iBAAkB,GAClB,MAAO,EAAM,UACb,MAAO,EAAM,UACf,CAAC,EAED,IAAK,EACH,MAAM,IAAI,EAAa,gCAAgC,EAQzD,IAL6B,EAAoB,CAC/C,QAAS,EAAM,mBACf,MAAO,EAAW,KAAK,CAAE,MAAO,EAAM,QAAS,CAAC,EAAE,KACpD,CAAC,EAGC,MAAM,IAAI,EAAa,4CAA4C,EAGrE,IAAQ,QAAS,GAAc,MAAM,EAAsB,EAAW,KAAK,EAE3E,OAAO,EAAQ,CACb,WAAY,OAAO,CAAU,EAC7B,aACA,OACA,eACA,OAAQ,EACR,WACF,CAAC,EAGH,MAAO,CACL,eACA,mBACA,oBACA,kBACA,UACA,gBACA,wBACA,uBACA,aACA,eACA,yBACA,UACA,OACA,UACF",
|
|
9
|
+
"debugId": "1C74BBA1E3F5AA4864756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"author": "swapkit-oss",
|
|
3
3
|
"dependencies": {
|
|
4
|
-
"@
|
|
5
|
-
"@polkadot/
|
|
6
|
-
"@
|
|
7
|
-
"@swapkit/helpers": "3.0.0-beta.
|
|
8
|
-
"@swapkit/toolboxes": "1.0.0-beta.
|
|
4
|
+
"@polkadot/keyring": "13.4.4",
|
|
5
|
+
"@polkadot/util": "13.4.4",
|
|
6
|
+
"@solana/web3.js": "1.98.2",
|
|
7
|
+
"@swapkit/helpers": "3.0.0-beta.9",
|
|
8
|
+
"@swapkit/toolboxes": "1.0.0-beta.10",
|
|
9
|
+
"ts-pattern": "5.7.0"
|
|
9
10
|
},
|
|
10
11
|
"description": "SwapKit Plugin - ChainFlip",
|
|
11
12
|
"exports": {
|
|
@@ -24,16 +25,16 @@
|
|
|
24
25
|
"require": "./dist/evm/index.cjs",
|
|
25
26
|
"types": "./src/evm/index.ts"
|
|
26
27
|
},
|
|
27
|
-
"./kado": {
|
|
28
|
-
"default": "./dist/kado/index.js",
|
|
29
|
-
"require": "./dist/kado/index.cjs",
|
|
30
|
-
"types": "./src/kado/index.ts"
|
|
31
|
-
},
|
|
32
28
|
"./radix": {
|
|
33
29
|
"default": "./dist/radix/index.js",
|
|
34
30
|
"require": "./dist/radix/index.cjs",
|
|
35
31
|
"types": "./src/radix/index.ts"
|
|
36
32
|
},
|
|
33
|
+
"./solana": {
|
|
34
|
+
"default": "./dist/solana/index.js",
|
|
35
|
+
"require": "./dist/solana/index.cjs",
|
|
36
|
+
"types": "./src/solana/index.ts"
|
|
37
|
+
},
|
|
37
38
|
"./thorchain": {
|
|
38
39
|
"default": "./dist/thorchain/index.js",
|
|
39
40
|
"require": "./dist/thorchain/index.cjs",
|
|
@@ -54,12 +55,13 @@
|
|
|
54
55
|
},
|
|
55
56
|
"scripts": {
|
|
56
57
|
"build": "bun run ./build.ts",
|
|
58
|
+
"build:clean": "rm -rf dist && bun run ./build.ts",
|
|
57
59
|
"clean": "rm -rf dist node_modules *.tsbuildinfo",
|
|
58
|
-
"lint": "biome check --write ./src",
|
|
59
60
|
"test": "echo 'bun test'",
|
|
60
61
|
"test:ci": "bun test --coverage",
|
|
61
|
-
"type-check": "tsc --noEmit"
|
|
62
|
+
"type-check": "bun tsc --noEmit",
|
|
63
|
+
"type-check:go": "tsgo"
|
|
62
64
|
},
|
|
63
65
|
"type": "module",
|
|
64
|
-
"version": "1.0.0-beta.
|
|
66
|
+
"version": "1.0.0-beta.10"
|
|
65
67
|
}
|
package/src/chainflip/broker.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { decodeAddress } from "@polkadot/keyring";
|
|
2
2
|
import { isHex, u8aToHex } from "@polkadot/util";
|
|
3
3
|
import { AssetValue, Chain, SwapKitError, wrapWithThrow } from "@swapkit/helpers";
|
|
4
|
-
import {
|
|
5
|
-
import type {
|
|
6
|
-
import type { ChainflipToolbox } from "@swapkit/toolboxes/substrate";
|
|
4
|
+
import type { getEvmToolbox } from "@swapkit/toolboxes/evm";
|
|
5
|
+
import type { getSubstrateToolbox } from "@swapkit/toolboxes/substrate";
|
|
7
6
|
|
|
8
7
|
import type { WithdrawFeeResponse } from "./types";
|
|
9
8
|
|
|
9
|
+
type ChainflipToolbox = Awaited<ReturnType<typeof getSubstrateToolbox<Chain.Chainflip>>>;
|
|
10
|
+
|
|
10
11
|
export const assetIdentifierToChainflipTicker = new Map<string, string>([
|
|
11
12
|
["ARB.ETH", "ArbEth"],
|
|
12
13
|
["ARB.USDC-0XAF88D065E77C8CC2239327C5EDB3A432268E5831", "ArbUsdc"],
|
|
@@ -20,7 +21,7 @@ export const assetIdentifierToChainflipTicker = new Map<string, string>([
|
|
|
20
21
|
["SOL.USDC-EPJFWDD5AUFQSSQEM2QN1XZYBAPC8G4WEGGKZWYTDT1V", "SolUsdc"],
|
|
21
22
|
]);
|
|
22
23
|
|
|
23
|
-
const registerAsBroker = (toolbox:
|
|
24
|
+
const registerAsBroker = (toolbox: ChainflipToolbox) => () => {
|
|
24
25
|
const extrinsic = toolbox.api.tx.swapping?.registerAsBroker?.();
|
|
25
26
|
|
|
26
27
|
if (!extrinsic) {
|
|
@@ -31,7 +32,7 @@ const registerAsBroker = (toolbox: Awaited<ReturnType<typeof ChainflipToolbox>>)
|
|
|
31
32
|
};
|
|
32
33
|
|
|
33
34
|
const withdrawFee =
|
|
34
|
-
(toolbox:
|
|
35
|
+
(toolbox: ChainflipToolbox) =>
|
|
35
36
|
({ feeAsset, recipient }: { feeAsset: AssetValue; recipient: string }) => {
|
|
36
37
|
const isFeeChainPolkadot = feeAsset.chain === Chain.Polkadot;
|
|
37
38
|
|
|
@@ -85,16 +86,18 @@ const withdrawFee =
|
|
|
85
86
|
};
|
|
86
87
|
|
|
87
88
|
const fundStateChainAccount =
|
|
88
|
-
(chainflipToolbox:
|
|
89
|
-
({
|
|
89
|
+
(chainflipToolbox: ChainflipToolbox) =>
|
|
90
|
+
async ({
|
|
90
91
|
evmToolbox,
|
|
91
92
|
stateChainAccount,
|
|
92
93
|
assetValue,
|
|
93
94
|
}: {
|
|
94
|
-
evmToolbox: ReturnType<typeof
|
|
95
|
+
evmToolbox: Awaited<ReturnType<typeof getEvmToolbox>>;
|
|
95
96
|
stateChainAccount: string;
|
|
96
97
|
assetValue: AssetValue;
|
|
97
98
|
}) => {
|
|
99
|
+
const { chainflipGateway } = await import("@swapkit/helpers/contracts");
|
|
100
|
+
|
|
98
101
|
const flipAssetValue = AssetValue.from({ asset: "ETH.FLIP" });
|
|
99
102
|
|
|
100
103
|
if (!assetValue.eqAsset(flipAssetValue)) {
|
|
@@ -117,9 +120,7 @@ const fundStateChainAccount =
|
|
|
117
120
|
});
|
|
118
121
|
};
|
|
119
122
|
|
|
120
|
-
export const ChainflipBroker = (
|
|
121
|
-
chainflipToolbox: Awaited<ReturnType<typeof ChainflipToolbox>>,
|
|
122
|
-
) => ({
|
|
123
|
+
export const ChainflipBroker = (chainflipToolbox: ChainflipToolbox) => ({
|
|
123
124
|
registerAsBroker: registerAsBroker(chainflipToolbox),
|
|
124
125
|
fundStateChainAccount: fundStateChainAccount(chainflipToolbox),
|
|
125
126
|
withdrawFee: withdrawFee(chainflipToolbox),
|
package/src/chainflip/plugin.ts
CHANGED
|
@@ -1,19 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AssetValue,
|
|
3
|
-
type
|
|
3
|
+
type CryptoChain,
|
|
4
4
|
ProviderName,
|
|
5
5
|
SKConfig,
|
|
6
|
-
type SolanaWallets,
|
|
7
|
-
type SubstrateWallets,
|
|
8
6
|
SwapKitError,
|
|
9
|
-
type UTXOWallets,
|
|
10
7
|
createPlugin,
|
|
11
8
|
} from "@swapkit/helpers";
|
|
12
9
|
import { SwapKitApi } from "@swapkit/helpers/api";
|
|
13
10
|
import type { RequestSwapDepositAddressParams } from "./types";
|
|
14
11
|
|
|
15
|
-
type SupportedChain = keyof (EVMWallets & SubstrateWallets & UTXOWallets & SolanaWallets);
|
|
16
|
-
|
|
17
12
|
export const ChainflipPlugin = createPlugin({
|
|
18
13
|
name: "chainflip",
|
|
19
14
|
methods: ({ getWallet }) => ({
|
|
@@ -48,7 +43,7 @@ export const ChainflipPlugin = createPlugin({
|
|
|
48
43
|
value: sellAmount,
|
|
49
44
|
});
|
|
50
45
|
|
|
51
|
-
const wallet = getWallet(sellAsset.chain as
|
|
46
|
+
const wallet = getWallet(sellAsset.chain as CryptoChain);
|
|
52
47
|
|
|
53
48
|
if (!wallet) {
|
|
54
49
|
throw new SwapKitError("core_wallet_connection_not_found");
|
|
@@ -64,7 +59,7 @@ export const ChainflipPlugin = createPlugin({
|
|
|
64
59
|
// we need to simplify this to one object params
|
|
65
60
|
const tx = await wallet.transfer({
|
|
66
61
|
assetValue: sellAsset,
|
|
67
|
-
|
|
62
|
+
sender: wallet.address,
|
|
68
63
|
recipient: depositAddress,
|
|
69
64
|
isProgramDerivedAddress: true,
|
|
70
65
|
});
|
package/src/evm/index.ts
CHANGED
|
@@ -76,7 +76,7 @@ export const EVMPlugin = createPlugin({
|
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
const { from, to, data, value } = tx as EVMTransaction;
|
|
79
|
-
return wallet.sendTransaction({ from, to, data, value: BigInt(value)
|
|
79
|
+
return wallet.sendTransaction({ from, to, data, value: BigInt(value), feeOptionKey });
|
|
80
80
|
},
|
|
81
81
|
}),
|
|
82
82
|
});
|
package/src/index.ts
CHANGED
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
3
|
-
export type * from "./kado/types";
|
|
1
|
+
export * from "./types";
|
|
2
|
+
export * from "./utils";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { SolanaPlugin } from "./plugin";
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AssetValue,
|
|
3
|
+
Chain,
|
|
4
|
+
ProviderName,
|
|
5
|
+
SwapKitError,
|
|
6
|
+
type SwapParams,
|
|
7
|
+
createPlugin,
|
|
8
|
+
} from "@swapkit/helpers";
|
|
9
|
+
import type { QuoteResponseRoute } from "@swapkit/helpers/api";
|
|
10
|
+
|
|
11
|
+
export const SolanaPlugin = createPlugin({
|
|
12
|
+
name: "solana",
|
|
13
|
+
properties: {
|
|
14
|
+
supportedSwapkitProviders: [ProviderName.JUPITER],
|
|
15
|
+
},
|
|
16
|
+
methods: ({ getWallet }) => ({
|
|
17
|
+
swap: async function solanaSwap({ route }: SwapParams<"solana", QuoteResponseRoute>) {
|
|
18
|
+
const { VersionedTransaction } = (await import("@solana/web3.js")).default;
|
|
19
|
+
const { tx, sellAsset } = route;
|
|
20
|
+
|
|
21
|
+
const assetValue = await AssetValue.from({
|
|
22
|
+
asset: sellAsset,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
const chain = assetValue.chain;
|
|
26
|
+
if (!(chain === Chain.Solana && tx)) throw new SwapKitError("core_swap_invalid_params");
|
|
27
|
+
|
|
28
|
+
const wallet = getWallet(chain);
|
|
29
|
+
const transaction = VersionedTransaction.deserialize(Buffer.from(tx as string, "base64"));
|
|
30
|
+
|
|
31
|
+
const signedTransaction = await wallet.signTransaction(transaction);
|
|
32
|
+
|
|
33
|
+
return wallet.broadcastTransaction(signedTransaction);
|
|
34
|
+
},
|
|
35
|
+
}),
|
|
36
|
+
});
|
package/src/thorchain/plugin.ts
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
type ApproveReturnType,
|
|
4
4
|
AssetValue,
|
|
5
5
|
Chain,
|
|
6
|
+
type CryptoChain,
|
|
6
7
|
type EVMChain,
|
|
7
8
|
EVMChains,
|
|
8
9
|
type ErrorKeys,
|
|
@@ -33,18 +34,15 @@ import {
|
|
|
33
34
|
TCBscDepositABI,
|
|
34
35
|
TCEthereumVaultAbi,
|
|
35
36
|
} from "@swapkit/helpers/contracts";
|
|
36
|
-
|
|
37
37
|
import { prepareTxParams, validateAddressType } from "./shared";
|
|
38
38
|
import type {
|
|
39
39
|
AddLiquidityParams,
|
|
40
40
|
AddLiquidityPartParams,
|
|
41
|
-
ApproveParams,
|
|
42
41
|
CoreTxParams,
|
|
43
42
|
CreateLiquidityParams,
|
|
44
43
|
NodeActionParams,
|
|
45
44
|
RegisterThornameParams,
|
|
46
45
|
SavingsParams,
|
|
47
|
-
SupportedChain,
|
|
48
46
|
WithdrawParams,
|
|
49
47
|
} from "./types";
|
|
50
48
|
|
|
@@ -154,7 +152,7 @@ function createTCBasedPlugin<T extends PluginChain>(pluginChain: T) {
|
|
|
154
152
|
const abis = pluginType === "thorchain" ? TCSpecificAbi : MayaSpecificAbi;
|
|
155
153
|
const { chain, symbol, ticker } = assetValue;
|
|
156
154
|
|
|
157
|
-
const wallet = getWallet(chain as
|
|
155
|
+
const wallet = getWallet(chain as CryptoChain);
|
|
158
156
|
if (!wallet) {
|
|
159
157
|
throw new SwapKitError("core_wallet_connection_not_found");
|
|
160
158
|
}
|
|
@@ -172,6 +170,7 @@ function createTCBasedPlugin<T extends PluginChain>(pluginChain: T) {
|
|
|
172
170
|
if (!abi) {
|
|
173
171
|
const wallet = getWallet(chain as PluginChain);
|
|
174
172
|
const shouldDeposit = pluginChain === chain && recipient === "";
|
|
173
|
+
// @Towan: Is that the same action? :)
|
|
175
174
|
return shouldDeposit ? wallet.deposit(params) : wallet.transfer(params);
|
|
176
175
|
}
|
|
177
176
|
|
|
@@ -250,12 +249,12 @@ function createTCBasedPlugin<T extends PluginChain>(pluginChain: T) {
|
|
|
250
249
|
});
|
|
251
250
|
}
|
|
252
251
|
|
|
253
|
-
function approveAssetValue(
|
|
254
|
-
return approve({
|
|
252
|
+
function approveAssetValue({ assetValue }: { assetValue: AssetValue }) {
|
|
253
|
+
return approve({ assetValue, type: ApproveMode.Approve });
|
|
255
254
|
}
|
|
256
255
|
|
|
257
|
-
function isAssetValueApproved(
|
|
258
|
-
return approve({
|
|
256
|
+
function isAssetValueApproved({ assetValue }: { assetValue: AssetValue }) {
|
|
257
|
+
return approve({ assetValue, type: ApproveMode.CheckOnly });
|
|
259
258
|
}
|
|
260
259
|
|
|
261
260
|
function registerName({ assetValue, ...params }: RegisterThornameParams) {
|
|
@@ -273,7 +272,7 @@ function createTCBasedPlugin<T extends PluginChain>(pluginChain: T) {
|
|
|
273
272
|
name: string;
|
|
274
273
|
ownerAddress: string;
|
|
275
274
|
}) {
|
|
276
|
-
const payout = payoutAddress || getWallet(assetValue.chain as
|
|
275
|
+
const payout = payoutAddress || getWallet(assetValue.chain as CryptoChain)?.address;
|
|
277
276
|
|
|
278
277
|
if (!payout) {
|
|
279
278
|
throw new SwapKitError("thorchain_preferred_asset_payout_required");
|
|
@@ -307,7 +306,7 @@ function createTCBasedPlugin<T extends PluginChain>(pluginChain: T) {
|
|
|
307
306
|
throw new SwapKitError("core_transaction_create_liquidity_invalid_params");
|
|
308
307
|
}
|
|
309
308
|
|
|
310
|
-
const assetAddress = getWallet(assetValue.chain as
|
|
309
|
+
const assetAddress = getWallet(assetValue.chain as CryptoChain).address;
|
|
311
310
|
const baseAssetAddress = getWallet(pluginChain).address;
|
|
312
311
|
|
|
313
312
|
const baseAssetTx = await wrapWithThrow(() => {
|
|
@@ -363,7 +362,7 @@ function createTCBasedPlugin<T extends PluginChain>(pluginChain: T) {
|
|
|
363
362
|
|
|
364
363
|
const baseAddress = includeBaseAddress ? baseAssetAddr || baseAssetWalletAddress : "";
|
|
365
364
|
const assetAddress =
|
|
366
|
-
isSym || mode === "asset" ? assetAddr || getWallet(chain as
|
|
365
|
+
isSym || mode === "asset" ? assetAddr || getWallet(chain as CryptoChain).address : "";
|
|
367
366
|
|
|
368
367
|
if (!(baseTransfer || assetTransfer)) {
|
|
369
368
|
throw new SwapKitError("core_transaction_add_liquidity_invalid_params");
|
package/src/thorchain/types.ts
CHANGED
|
@@ -1,14 +1,4 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
AssetValue,
|
|
3
|
-
CosmosWallets,
|
|
4
|
-
EVMWallets,
|
|
5
|
-
FeeOption,
|
|
6
|
-
MemoType,
|
|
7
|
-
ThorchainWallets,
|
|
8
|
-
UTXOWallets,
|
|
9
|
-
} from "@swapkit/helpers";
|
|
10
|
-
|
|
11
|
-
export type SupportedChain = keyof (EVMWallets & UTXOWallets & ThorchainWallets & CosmosWallets);
|
|
1
|
+
import type { AssetValue, FeeOption, MemoType } from "@swapkit/helpers";
|
|
12
2
|
|
|
13
3
|
export type AddLiquidityPartParams = {
|
|
14
4
|
assetValue: AssetValue;
|
|
@@ -26,11 +16,6 @@ export type AddLiquidityParams = {
|
|
|
26
16
|
mode?: "sym" | "baseAsset" | "asset";
|
|
27
17
|
};
|
|
28
18
|
|
|
29
|
-
export type ApproveParams = {
|
|
30
|
-
assetValue: AssetValue;
|
|
31
|
-
contractAddress?: string;
|
|
32
|
-
};
|
|
33
|
-
|
|
34
19
|
export type CreateLiquidityParams = {
|
|
35
20
|
baseAssetValue: AssetValue;
|
|
36
21
|
assetValue: AssetValue;
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ChainflipPlugin } from "./chainflip";
|
|
2
|
+
import type { EVMPlugin } from "./evm";
|
|
3
|
+
import type { RadixPlugin } from "./radix";
|
|
4
|
+
import type { SolanaPlugin } from "./solana/plugin";
|
|
5
|
+
import type { ThorchainPlugin } from "./thorchain";
|
|
6
|
+
|
|
7
|
+
export type * from "./chainflip/types";
|
|
8
|
+
export type * from "./thorchain/types";
|
|
9
|
+
|
|
10
|
+
export type SKPlugins = typeof ChainflipPlugin &
|
|
11
|
+
typeof ThorchainPlugin &
|
|
12
|
+
typeof RadixPlugin &
|
|
13
|
+
typeof SolanaPlugin &
|
|
14
|
+
typeof EVMPlugin;
|
|
15
|
+
|
|
16
|
+
export type PluginName = keyof SKPlugins;
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { PluginName, SKPlugins } from "./types";
|
|
2
|
+
|
|
3
|
+
export async function loadPlugin<P extends PluginName>(pluginName: P) {
|
|
4
|
+
const { match } = await import("ts-pattern");
|
|
5
|
+
|
|
6
|
+
const plugin = await match(pluginName as PluginName)
|
|
7
|
+
.with("chainflip", async () => {
|
|
8
|
+
const { ChainflipPlugin } = await import("./chainflip");
|
|
9
|
+
return ChainflipPlugin;
|
|
10
|
+
})
|
|
11
|
+
.with("thorchain", async () => {
|
|
12
|
+
const { ThorchainPlugin } = await import("./thorchain");
|
|
13
|
+
return ThorchainPlugin;
|
|
14
|
+
})
|
|
15
|
+
.with("radix", async () => {
|
|
16
|
+
const { RadixPlugin } = await import("./radix");
|
|
17
|
+
return RadixPlugin;
|
|
18
|
+
})
|
|
19
|
+
.with("evm", async () => {
|
|
20
|
+
const { EVMPlugin } = await import("./evm");
|
|
21
|
+
return EVMPlugin;
|
|
22
|
+
})
|
|
23
|
+
.with("solana", async () => {
|
|
24
|
+
const { SolanaPlugin } = await import("./solana");
|
|
25
|
+
return SolanaPlugin;
|
|
26
|
+
})
|
|
27
|
+
.exhaustive();
|
|
28
|
+
|
|
29
|
+
return plugin as unknown as SKPlugins[P];
|
|
30
|
+
}
|
package/dist/kado/index.cjs
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
var k={};P(k,{mapKadoQuoteToQuoteResponse:()=>f,SupportedKadoChain:()=>b,KadoSupportedFiatCurrencies:()=>E,KadoPlugin:()=>O,KadoChainToChain:()=>I,ChainToKadoChain:()=>h});module.exports=N(k);var t=require("@swapkit/helpers"),b={thorchain:t.Chain.THORChain,solana:t.Chain.Solana,polygon:t.Chain.Polygon,Optimism:t.Chain.Optimism,litecoin:t.Chain.Litecoin,kujira:t.Chain.Kujira,ethereum:t.Chain.Ethereum,"cosmos hub":t.Chain.Cosmos,bitcoin:t.Chain.Bitcoin,base:t.Chain.Base,Avalanche:t.Chain.Avalanche,Arbitrum:t.Chain.Arbitrum};function h(n){let r=Object.entries(b).find(([e,a])=>a===n);if(!r)throw new Error(`Chain ${n} not supported`);return r[0]}function I(n){if(!Object.keys(b).includes(n))throw new Error(`KadoChain ${n} not supported`);return b[n]}function f({quote:n,sellAsset:o,buyAsset:r}){let e=o.chain,a=r.chain,c=e===t.Chain.Fiat,{receive:u,price:p,baseAmount:s,totalFee:m,processingFee:d,networkFee:g}=n.data.quote,y=r.set(c?u.unitCount.toString():u.amount.toString()),x=c?Math.round(m.amount/u.amount*1e4):Math.round(m.amount/(p.price*s.amount)*1e4),l=Math.ceil(t.blockTimes[e]*3),C=Math.ceil(60),K=Math.ceil(t.blockTimes[a]),S=[{buyAsset:r.toString(),destinationAddress:"{destinationAddress}",estimatedTime:{inbound:l,swap:C,outbound:K,total:l+C+K},expectedBuyAmount:y.getValue("string"),expectedBuyAmountMaxSlippage:y.getValue("string"),providers:[t.ProviderName.KADO],sellAmount:o.getValue("string"),sellAsset:o.toString(),sourceAddress:"{sourceAddress}",totalSlippageBps:x,fees:[{asset:d.currency,amount:d.amount.toString(),type:t.FeeTypeEnum.LIQUIDITY,protocol:t.ProviderName.KADO,chain:t.Chain.Fiat},{asset:g.currency,amount:g.amount.toString(),type:t.FeeTypeEnum.NETWORK,protocol:t.ProviderName.KADO,chain:r.chain}],legs:[{provider:t.ProviderName.KADO,sellAsset:o.toString(),sellAmount:o.getValue("string"),buyAsset:r.toString(),buyAmount:u.unitCount.toString(),buyAmountMaxSlippage:u.unitCount.toString(),fees:[{asset:d.currency,amount:d.amount.toString(),type:t.FeeTypeEnum.LIQUIDITY,protocol:t.ProviderName.KADO,chain:t.Chain.Fiat},{asset:g.currency,amount:g.amount.toString(),type:t.FeeTypeEnum.NETWORK,protocol:t.ProviderName.KADO,chain:r.chain}]}],warnings:[],meta:{tags:[]}}];return{quoteId:crypto.randomUUID(),routes:S,error:n.success?void 0:n.message}}var i=require("@swapkit/helpers");var O=i.createPlugin({name:"kado",methods:()=>({createPopover:R,getAssets:T,getBlockchains:v,getKadoWidgetUrl:F,getOrderStatus:M,fetchProviderQuote:D,swap:_}),properties:{supportedSwapkitProviders:[i.ProviderName.KADO]}});function _({route:n}){if(!(n.sourceAddress&&n.destinationAddress))throw new Error("Source and destination addresses are required");let o=i.AssetValue.from({asset:n.sellAsset}),r=i.AssetValue.from({asset:n.buyAsset}),e=o.chain===i.Chain.Fiat?"buy":"sell",a=F({sellAsset:o,buyAsset:r,recipient:n.destinationAddress,sender:n.sourceAddress,type:e,mode:"minimal"});return R(a),{status:"pending",txHash:null}}async function D({sellAsset:n,buyAsset:o,fiatMethod:r="credit_card"}){try{let e=n.chain===i.Chain.Fiat,[a,c]=e?[o,n]:[n,o],u=e?"buy":"sell",p={amount:a.getValue("string"),asset:a.symbol,blockchain:h(a.chain),currency:c.symbol,fiatMethod:r,partner:"fortress",transactionType:u},s=i.SKConfig.get("apiKeys").kado;i.warnOnce(!s,"plugin(kado): No Kado API key found");let m=await i.RequestClient.get("https://api.kado.money/v2/ramp/quote",{searchParams:p,headers:{"X-Widget-Id":s}});if(!m.success)throw new Error(m.message);return f({quote:m,sellAsset:n,buyAsset:o})}catch(e){throw new Error("core_swap_quote_error")}}async function v(){let n=await i.RequestClient.get("https://api.kado.money/v1/ramp/blockchains");if(!n.success)throw new Error(n.message);return n.data.blockchains}async function T(){let n=await i.RequestClient.get("https://api.kado.money/v1/ramp/supported-assets");if(!n.success)throw new Error(n.message);return n.data.assets}async function M(n){let o=i.SKConfig.get("apiKeys").kado;i.warnOnce(!o,"plugin(kado): No Kado API key found");try{let r=await i.RequestClient.get(`https://api.kado.money/v2/public/orders/${n}`,{headers:{"X-Widget-Id":o}});if(!r.success)throw new Error(r.message);return r.data.order}catch(r){throw new Error("Failed to get order status")}}function F({sellAsset:n,buyAsset:o,recipient:r,type:e,sender:a,mode:c}){let u=i.SKConfig.get("apiKeys").kado;i.warnOnce(!u,"plugin(kado): No Kado API key found");let p=e==="buy"?{onPayAmount:n.getValue("string"),onPayCurrency:n.symbol,onRevCurrency:o.symbol,...r?{onToAddress:r}:{}}:{offPayAmount:n.getValue("string"),offPayCurrency:n.symbol,offRevCurrency:o.symbol,...a?{offFromAddress:a}:{}},s=h(e==="buy"?o.chain:n.chain).toUpperCase();return`https://app.kado.money/?${new URLSearchParams({...p,apiKey:u,network:s,product:e.toUpperCase(),mode:c}).toString()}`}function R(n){let o=document.createElement("div");o.style.cssText=`
|
|
2
|
-
position: fixed;
|
|
3
|
-
top: 0;
|
|
4
|
-
left: 0;
|
|
5
|
-
width: 100%;
|
|
6
|
-
height: 100%;
|
|
7
|
-
background: rgba(0, 0, 0, 0.5);
|
|
8
|
-
display: flex;
|
|
9
|
-
justify-content: center;
|
|
10
|
-
align-items: center;
|
|
11
|
-
z-index: 9999;
|
|
12
|
-
`;let r=document.createElement("iframe");return r.src=n,r.style.cssText=`
|
|
13
|
-
width: 440px;
|
|
14
|
-
height: 700px;
|
|
15
|
-
border: none;
|
|
16
|
-
border-radius: 12px;
|
|
17
|
-
background: white;
|
|
18
|
-
`,o.appendChild(r),document.body.appendChild(o),o.addEventListener("click",(e)=>{if(e.target===o)document.body.removeChild(o)}),o}var E=["USD","CAD","GBP","EUR","MXN","COP","INR","CHF","AUD","ARS","BRL","CLP","JPY","KRW","PEN","PHP","SGD","TRY","UYU","TWD","VND","CRC","SEK","PLN","DKK","NOK","NZD"];
|
|
19
|
-
|
|
20
|
-
//# debugId=F14F09772CF1871864756E2164756E21
|