@funkit/api-base 0.0.1

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.
Files changed (134) hide show
  1. package/.eslintignore +5 -0
  2. package/README.md +1 -0
  3. package/dist/index.d.ts +4 -0
  4. package/dist/index.js +21 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/src/consts/api.d.ts +1 -0
  7. package/dist/src/consts/api.js +12 -0
  8. package/dist/src/consts/api.js.map +1 -0
  9. package/dist/src/consts/index.d.ts +3 -0
  10. package/dist/src/consts/index.js +20 -0
  11. package/dist/src/consts/index.js.map +1 -0
  12. package/dist/src/consts/request.d.ts +13 -0
  13. package/dist/src/consts/request.js +3 -0
  14. package/dist/src/consts/request.js.map +1 -0
  15. package/dist/src/consts/retry.d.ts +4 -0
  16. package/dist/src/consts/retry.js +19 -0
  17. package/dist/src/consts/retry.js.map +1 -0
  18. package/dist/src/errors/BaseError.d.ts +9 -0
  19. package/dist/src/errors/BaseError.js +24 -0
  20. package/dist/src/errors/BaseError.js.map +1 -0
  21. package/dist/src/errors/ClientError.d.ts +22 -0
  22. package/dist/src/errors/ClientError.js +76 -0
  23. package/dist/src/errors/ClientError.js.map +1 -0
  24. package/dist/src/errors/ServerError.d.ts +7 -0
  25. package/dist/src/errors/ServerError.js +18 -0
  26. package/dist/src/errors/ServerError.js.map +1 -0
  27. package/dist/src/errors/errors.json +626 -0
  28. package/dist/src/errors/index.d.ts +4 -0
  29. package/dist/src/errors/index.js +21 -0
  30. package/dist/src/errors/index.js.map +1 -0
  31. package/dist/src/errors/types.d.ts +60 -0
  32. package/dist/src/errors/types.js +51 -0
  33. package/dist/src/errors/types.js.map +1 -0
  34. package/dist/src/services/assets/endpoints.d.ts +50 -0
  35. package/dist/src/services/assets/endpoints.js +95 -0
  36. package/dist/src/services/assets/endpoints.js.map +1 -0
  37. package/dist/src/services/assets/index.d.ts +2 -0
  38. package/dist/src/services/assets/index.js +19 -0
  39. package/dist/src/services/assets/index.js.map +1 -0
  40. package/dist/src/services/assets/types.d.ts +65 -0
  41. package/dist/src/services/assets/types.js +3 -0
  42. package/dist/src/services/assets/types.js.map +1 -0
  43. package/dist/src/services/checkout/endpoints.d.ts +55 -0
  44. package/dist/src/services/checkout/endpoints.js +169 -0
  45. package/dist/src/services/checkout/endpoints.js.map +1 -0
  46. package/dist/src/services/checkout/index.d.ts +2 -0
  47. package/dist/src/services/checkout/index.js +19 -0
  48. package/dist/src/services/checkout/index.js.map +1 -0
  49. package/dist/src/services/checkout/types.d.ts +106 -0
  50. package/dist/src/services/checkout/types.js +21 -0
  51. package/dist/src/services/checkout/types.js.map +1 -0
  52. package/dist/src/services/index.d.ts +4 -0
  53. package/dist/src/services/index.js +21 -0
  54. package/dist/src/services/index.js.map +1 -0
  55. package/dist/src/services/mesh/endpoints.d.ts +45 -0
  56. package/dist/src/services/mesh/endpoints.js +129 -0
  57. package/dist/src/services/mesh/endpoints.js.map +1 -0
  58. package/dist/src/services/mesh/index.d.ts +2 -0
  59. package/dist/src/services/mesh/index.js +19 -0
  60. package/dist/src/services/mesh/index.js.map +1 -0
  61. package/dist/src/services/mesh/types.d.ts +56 -0
  62. package/dist/src/services/mesh/types.js +3 -0
  63. package/dist/src/services/mesh/types.js.map +1 -0
  64. package/dist/src/services/moonpay/endpoints.d.ts +3 -0
  65. package/dist/src/services/moonpay/endpoints.js +43 -0
  66. package/dist/src/services/moonpay/endpoints.js.map +1 -0
  67. package/dist/src/services/moonpay/index.d.ts +2 -0
  68. package/dist/src/services/moonpay/index.js +19 -0
  69. package/dist/src/services/moonpay/index.js.map +1 -0
  70. package/dist/src/services/moonpay/types.d.ts +14 -0
  71. package/dist/src/services/moonpay/types.js +3 -0
  72. package/dist/src/services/moonpay/types.js.map +1 -0
  73. package/dist/src/utils/checkout.d.ts +2 -0
  74. package/dist/src/utils/checkout.js +20 -0
  75. package/dist/src/utils/checkout.js.map +1 -0
  76. package/dist/src/utils/error.d.ts +1 -0
  77. package/dist/src/utils/error.js +13 -0
  78. package/dist/src/utils/error.js.map +1 -0
  79. package/dist/src/utils/index.d.ts +3 -0
  80. package/dist/src/utils/index.js +20 -0
  81. package/dist/src/utils/index.js.map +1 -0
  82. package/dist/src/utils/request.d.ts +7 -0
  83. package/dist/src/utils/request.js +128 -0
  84. package/dist/src/utils/request.js.map +1 -0
  85. package/dist/test/services/assets.test.d.ts +1 -0
  86. package/dist/test/services/assets.test.js +37 -0
  87. package/dist/test/services/assets.test.js.map +1 -0
  88. package/dist/test/services/checkout.test.d.ts +1 -0
  89. package/dist/test/services/checkout.test.js +42 -0
  90. package/dist/test/services/checkout.test.js.map +1 -0
  91. package/dist/test/services/mesh.test.d.ts +1 -0
  92. package/dist/test/services/mesh.test.js +12 -0
  93. package/dist/test/services/mesh.test.js.map +1 -0
  94. package/dist/test/services/moonpay.test.d.ts +1 -0
  95. package/dist/test/services/moonpay.test.js +25 -0
  96. package/dist/test/services/moonpay.test.js.map +1 -0
  97. package/dist/test/setup.d.ts +0 -0
  98. package/dist/test/setup.js +10 -0
  99. package/dist/test/setup.js.map +1 -0
  100. package/index.ts +4 -0
  101. package/package.json +37 -0
  102. package/src/consts/api.ts +9 -0
  103. package/src/consts/index.ts +3 -0
  104. package/src/consts/request.ts +16 -0
  105. package/src/consts/retry.ts +21 -0
  106. package/src/errors/BaseError.ts +28 -0
  107. package/src/errors/ClientError.ts +175 -0
  108. package/src/errors/ServerError.ts +43 -0
  109. package/src/errors/errors.json +626 -0
  110. package/src/errors/index.ts +4 -0
  111. package/src/errors/types.ts +64 -0
  112. package/src/services/assets/endpoints.ts +131 -0
  113. package/src/services/assets/index.ts +2 -0
  114. package/src/services/assets/types.ts +80 -0
  115. package/src/services/checkout/endpoints.ts +233 -0
  116. package/src/services/checkout/index.ts +2 -0
  117. package/src/services/checkout/types.ts +130 -0
  118. package/src/services/index.ts +4 -0
  119. package/src/services/mesh/endpoints.ts +164 -0
  120. package/src/services/mesh/index.ts +2 -0
  121. package/src/services/mesh/types.ts +63 -0
  122. package/src/services/moonpay/endpoints.ts +62 -0
  123. package/src/services/moonpay/index.ts +2 -0
  124. package/src/services/moonpay/types.ts +15 -0
  125. package/src/utils/checkout.ts +17 -0
  126. package/src/utils/error.ts +15 -0
  127. package/src/utils/index.ts +3 -0
  128. package/src/utils/request.ts +198 -0
  129. package/test/services/assets.test.ts +41 -0
  130. package/test/services/checkout.test.ts +53 -0
  131. package/test/services/mesh.test.ts +10 -0
  132. package/test/services/moonpay.test.ts +24 -0
  133. package/test/setup.ts +9 -0
  134. package/tsconfig.json +33 -0
@@ -0,0 +1,64 @@
1
+ export type ErrorData = {
2
+ location: string
3
+ error?: {
4
+ txDetails?: ErrorTransactionDetails
5
+ reasonData?: {
6
+ title: string
7
+ reasons: string[]
8
+ }
9
+ }
10
+ }
11
+
12
+ export type ErrorTransactionDetails = {
13
+ method: string
14
+ params: any[]
15
+ contractAddress?: string
16
+ chainId?: number | string
17
+ }
18
+
19
+ export enum ErrorBaseType {
20
+ ClientError = 'ClientError',
21
+ ServerError = 'ServerError',
22
+ }
23
+
24
+ export enum ErrorType {
25
+ InvalidParameter = 'InvalidParameter',
26
+ InternalServerFailure = 'InternalServerFailure',
27
+ ResourceNotFound = 'ResourceNotFound',
28
+ InvalidAction = 'InvalidAction',
29
+ ThrottlingError = 'ThrottlingError',
30
+ AccessDeniedError = 'AccessDeniedError',
31
+ UserOpFailureError = 'UserOpFailureError',
32
+ }
33
+
34
+ export enum ErrorCode {
35
+ MissingParameter = 'MissingParameter',
36
+ InvalidParameter = 'InvalidParameter',
37
+ InvalidThreshold = 'InvalidThreshold',
38
+ InvalidChainIdentifier = 'InvalidChainIdentifier',
39
+ InvalidNFTIdentifier = 'InvalidNFTIdentifier',
40
+ InsufficientSignatures = 'InsufficientSignatures',
41
+ InvalidParameterCombination = 'InvalidParameterCombination',
42
+ CheckPointHintsNotFound = 'CheckPointHintsNotFound',
43
+ GroupNotFound = 'GroupNotFound',
44
+ TokenNotFound = 'TokenNotFound',
45
+ AddressNotFound = 'AddressNotFound',
46
+ UserAlreadyExists = 'UserAlreadyExists',
47
+ UserNotFound = 'UserNotFound',
48
+ ChainNotSupported = 'ChainNotSupported',
49
+ ServerMissingData = 'ServerMissingData',
50
+ ServerFailure = 'ServerFailure',
51
+ ServerTimeout = 'ServerTimeout',
52
+ UnknownServerError = 'UnknownServerError',
53
+ ServerConnectionError = 'ServerConnectionError',
54
+ UserOpFailureError = 'UserOpFailureError',
55
+ Unauthorized = 'Unauthorized',
56
+ RequestLimitExceeded = 'RequestLimitExceeded',
57
+ WalletPrefundError = 'PrefundError',
58
+ GasSponsorFundError = 'GasSponsorFundError',
59
+ FunWalletErrorCode = 'FunWalletErrorCode',
60
+ BridgeRouteNotFound = 'BridgeRouteNotFound',
61
+ BridgeAllowanceDataNotFound = 'BridgeAllowanceDataNotFound',
62
+ BridgeApproveTxDataNotFound = 'BridgeApproveTxDataNotFound',
63
+ CheckoutInitDepositAddrNotFound = 'CheckoutInitDepositAddrNotFound',
64
+ }
@@ -0,0 +1,131 @@
1
+ import { API_BASE_URL } from '../../consts'
2
+ import { sendGetRequest } from '../../utils'
3
+ import {
4
+ GetAllWalletNFTsByChainIdRequest,
5
+ GetAllWalletNFTsByChainIdResponse,
6
+ GetAllWalletNFTsRequest,
7
+ GetAllWalletNFTsResponse,
8
+ GetAllWalletTokensByChainIdRequest,
9
+ GetAllWalletTokensByChainIdResponse,
10
+ GetAllWalletTokensRequest,
11
+ GetAllWalletTokensResponse,
12
+ GetAssetPriceInfoRequest,
13
+ GetAssetPriceInfoResponse,
14
+ GetWalletLidoWithdrawalsByChainId,
15
+ GetWalletLidoWithdrawalsByChainIdResponse,
16
+ } from './types'
17
+
18
+ /**===========================================================
19
+ * REFERENCE CORE FILE: /packages/core/src/apis/AssetApis.ts
20
+ * TODO: Remove this comment once migration is complete
21
+ *===========================================================*/
22
+
23
+ /**
24
+ * Gets the estimated dollar unit price of a tokenAddress for checkout
25
+ * @param chainId https://chainlist.org/ e.g. "1" for ethereum
26
+ * @param assetTokenAddress tokenAddress of the asset on the given chain
27
+ * @param apiKey
28
+ */
29
+ export async function getAssetPriceInfo({
30
+ chainId,
31
+ assetTokenAddress,
32
+ apiKey,
33
+ }: GetAssetPriceInfoRequest): Promise<GetAssetPriceInfoResponse> {
34
+ const priceInfo = await sendGetRequest({
35
+ uri: `${API_BASE_URL}/asset/erc20/price/${chainId}/${assetTokenAddress}`,
36
+ apiKey,
37
+ retryOptions: { maxAttempts: 2 },
38
+ })
39
+ return priceInfo
40
+ }
41
+
42
+ /**
43
+ * Get all tokens for a given wallet address
44
+ * @param walletAddress
45
+ * @param onlyVerifiedTokens If true, only return alchemy tokens that are verified(filters spam)
46
+ * @param apiKey
47
+ */
48
+ export async function getAllWalletTokens({
49
+ walletAddress,
50
+ onlyVerifiedTokens,
51
+ apiKey,
52
+ }: GetAllWalletTokensRequest): Promise<GetAllWalletTokensResponse> {
53
+ return await sendGetRequest({
54
+ uri: `${API_BASE_URL}/assets/erc20s/${walletAddress}?onlyVerifiedTokens=${onlyVerifiedTokens}`,
55
+ apiKey,
56
+ retryOptions: { maxAttempts: 2 },
57
+ })
58
+ }
59
+
60
+ /**
61
+ * Get all tokens for a given wallet address on a specific chain
62
+ * @param chainId https://chainlist.org/
63
+ * @param walletAddress
64
+ * @param onlyVerifiedTokens If true, only return alchemy tokens that are verified(filters spam)
65
+ * @param apiKey
66
+ */
67
+ export async function getAllWalletTokensByChainId({
68
+ chainId,
69
+ walletAddress,
70
+ onlyVerifiedTokens,
71
+ apiKey,
72
+ }: GetAllWalletTokensByChainIdRequest): Promise<GetAllWalletTokensByChainIdResponse> {
73
+ return await sendGetRequest({
74
+ uri: `${API_BASE_URL}/assets/erc20s/${walletAddress}/${chainId}?onlyVerifiedTokens=${onlyVerifiedTokens}`,
75
+ apiKey,
76
+ retryOptions: { maxAttempts: 2 },
77
+ })
78
+ }
79
+
80
+ /**=======================
81
+ * POTENTIAL DEPRECATION
82
+ *=======================*/
83
+
84
+ /**
85
+ * Get all the NFTs owned by a wallet
86
+ * @param walletAddress
87
+ * @param apiKey
88
+ */
89
+ export async function getAllWalletNFTs({
90
+ walletAddress,
91
+ apiKey,
92
+ }: GetAllWalletNFTsRequest): Promise<GetAllWalletNFTsResponse> {
93
+ return await sendGetRequest({
94
+ uri: `${API_BASE_URL}/assets/nfts/${walletAddress}`,
95
+ apiKey,
96
+ })
97
+ }
98
+
99
+ /**
100
+ * Get all the NFTs owned by a wallet on a specific chain
101
+ * @param chainId From https://chainlist.org/
102
+ * @param walletAddress Address of holder
103
+ * @param apiKey
104
+ */
105
+ export async function getAllWalletNFTsByChainId({
106
+ chainId,
107
+ walletAddress,
108
+ apiKey,
109
+ }: GetAllWalletNFTsByChainIdRequest): Promise<GetAllWalletNFTsByChainIdResponse> {
110
+ return await sendGetRequest({
111
+ uri: `${API_BASE_URL}/assets/nfts/${walletAddress}/${chainId}`,
112
+ apiKey,
113
+ })
114
+ }
115
+
116
+ /**
117
+ * Get all lido withdrawal request ids for a wallet address on a specific chain
118
+ * @param {string} chainId https://chainlist.org/ ie "1" for ethereum
119
+ * @param {string} holderAddr Address of holder
120
+ * @returns [readyToWithdrawRequestIds, notReadyToWithdrawRequestIds]
121
+ */
122
+ export async function getWalletLidoWithdrawalsByChainId({
123
+ chainId,
124
+ walletAddress,
125
+ apiKey,
126
+ }: GetWalletLidoWithdrawalsByChainId): Promise<GetWalletLidoWithdrawalsByChainIdResponse> {
127
+ return await sendGetRequest({
128
+ uri: `${API_BASE_URL}/assets/lido-withdrawals/${walletAddress}/${chainId}`,
129
+ apiKey,
130
+ })
131
+ }
@@ -0,0 +1,2 @@
1
+ export * from './endpoints'
2
+ export * from './types'
@@ -0,0 +1,80 @@
1
+ export interface GetAssetPriceInfoRequest {
2
+ chainId: string
3
+ assetTokenAddress: string
4
+ apiKey: string
5
+ }
6
+
7
+ interface AssetPriceInfo {
8
+ unitPrice: number
9
+ amount: number
10
+ total: number
11
+ }
12
+
13
+ export type GetAssetPriceInfoResponse = AssetPriceInfo
14
+
15
+ export interface GetAllWalletTokensRequest {
16
+ walletAddress: string
17
+ onlyVerifiedTokens: boolean
18
+ apiKey: string
19
+ }
20
+
21
+ interface AssetBalanceInfo {
22
+ chainId: string
23
+ contractAddress: string
24
+ decimals: number
25
+ logo: string
26
+ name: string
27
+ price: number | null
28
+ symbol: string
29
+ tokenBalance: string
30
+ totalUsdValue: number | null
31
+ }
32
+
33
+ interface ChainAssetBalanceInfo {
34
+ [tokenAddress: string]: AssetBalanceInfo
35
+ }
36
+
37
+ export interface GetAllWalletTokensResponse {
38
+ [chainId: number]: ChainAssetBalanceInfo
39
+ }
40
+
41
+ export interface GetAllWalletTokensByChainIdRequest {
42
+ chainId: string
43
+ walletAddress: string
44
+ onlyVerifiedTokens: boolean
45
+ apiKey: string
46
+ }
47
+
48
+ export type GetAllWalletTokensByChainIdResponse = ChainAssetBalanceInfo
49
+
50
+ export interface GetAllWalletNFTsRequest {
51
+ walletAddress: string
52
+ apiKey: string
53
+ }
54
+
55
+ interface ChainNFTInfo {
56
+ address: string
57
+ token_id: string
58
+ floor_price: string
59
+ }
60
+
61
+ export interface GetAllWalletNFTsResponse {
62
+ [chainId: string]: ChainNFTInfo[]
63
+ }
64
+
65
+ export interface GetAllWalletNFTsByChainIdRequest {
66
+ chainId: string
67
+ walletAddress: string
68
+ apiKey: string
69
+ }
70
+
71
+ export type GetAllWalletNFTsByChainIdResponse = ChainNFTInfo[]
72
+
73
+ export interface GetWalletLidoWithdrawalsByChainId {
74
+ chainId: string
75
+ walletAddress: string
76
+ apiKey: string
77
+ }
78
+
79
+ // [readyToWithdrawRequestIds, notReadyToWithdrawRequestIds]
80
+ export type GetWalletLidoWithdrawalsByChainIdResponse = [number[], number[]]
@@ -0,0 +1,233 @@
1
+ import Big from 'big.js'
2
+ import { Address } from 'viem'
3
+
4
+ import { API_BASE_URL } from '../../consts'
5
+ import { ErrorCode, ResourceNotFoundError } from '../../errors'
6
+ import {
7
+ generateRandomCheckoutSalt,
8
+ roundToNearestBottomTenth,
9
+ sendGetRequest,
10
+ sendPostRequest,
11
+ } from '../../utils'
12
+ import {
13
+ CheckoutApiInitParams,
14
+ CheckoutApiQuoteParams,
15
+ CheckoutApiQuoteResponse,
16
+ CheckoutHistoryItem,
17
+ CheckoutInitParams,
18
+ CheckoutInitResponse,
19
+ CheckoutQuoteParams,
20
+ CheckoutQuoteResponse,
21
+ CheckoutTransferSponsorshipApiParams,
22
+ CheckoutTransferSponsorshipParams,
23
+ CheckoutTransferSponsorshipResponse,
24
+ } from './types'
25
+
26
+ /**
27
+ * Gets a checkout quote (estimation).
28
+ * @param fromChainId The ID of the chain where funds will be provided from.
29
+ * @param fromTokenAddress The asset to fund the checkout. This must be either a chain native token or an ERC-20, on the fromChainId.
30
+ * @param fromTokenDecimals The number of decimals for the fromTokenAddress.
31
+ * @param toChainId The ID of the chain where the checkout operation is to be performed.
32
+ * @param toTokenAddress The wanted asset for the checkout operation. This must be either a chain native token or an ERC-20, on the target chain.
33
+ * @param toTokenAmount The amount of wanted asset for the checkout operation in base units.
34
+ * @param toTokenDecimals The number of decimals for the toTokenAddress.
35
+ * @param expirationTimestampMs The amount of time (duration) from now before the checkout operation expires.
36
+ * @param apiKey A valid fun api key.
37
+ * @return {Promise<CheckoutCoreQuoteResponse>} The formatted quote object
38
+ */
39
+ export async function getCheckoutQuote({
40
+ fromChainId,
41
+ fromTokenAddress,
42
+ fromTokenDecimals,
43
+ toChainId,
44
+ toTokenAddress,
45
+ toTokenDecimals,
46
+ toTokenAmount,
47
+ expirationTimestampMs,
48
+ sponsorInitialTransferGasLimit,
49
+ recipientAddr,
50
+ needsRefuel,
51
+ apiKey,
52
+ }: CheckoutQuoteParams): Promise<CheckoutQuoteResponse> {
53
+ try {
54
+ const toMultipler = 10 ** toTokenDecimals
55
+ const toAmountBaseUnitBI = BigInt(Math.floor(toTokenAmount * toMultipler))
56
+ const queryParams = {
57
+ fromChainId,
58
+ fromTokenAddress,
59
+ toChainId,
60
+ toTokenAddress,
61
+ toAmountBaseUnit: toAmountBaseUnitBI.toString(),
62
+ // Only pass in recipientAddr if specified
63
+ ...(recipientAddr ? { recipientAddr } : {}),
64
+ // Rounding nearest tenth second (instead of seconds) to better support backend quote caching feature
65
+ // Reference: https://vintage-heaven-3cd.notion.site/API-Gateway-Caching-and-Pre-Warming-System-Draft-ee7909d9b85f43c793ce7bd2607bec02?pvs=4
66
+ // Note: Rounding *down* instead of a regular round to safeguard against edge case of timing passing frontend range validation but failing backend range validation
67
+ checkoutExpirationTimestampSeconds: roundToNearestBottomTenth(
68
+ Math.round((Date.now() + expirationTimestampMs) / 1000),
69
+ ).toString(),
70
+ sponsorInitialTransferGasLimit,
71
+ refuel: needsRefuel.toString(),
72
+ } as CheckoutApiQuoteParams
73
+
74
+ const searchParams = new URLSearchParams(queryParams)
75
+ const quoteRes = (await sendGetRequest({
76
+ uri: `${API_BASE_URL}/checkout/quote?${searchParams}`,
77
+ apiKey,
78
+ })) as CheckoutApiQuoteResponse
79
+
80
+ const fromMultipler = 10 ** fromTokenDecimals
81
+ // Format the response for frontend usage
82
+ return {
83
+ quoteId: quoteRes.quoteId,
84
+ fromTokenAddress: quoteRes.fromTokenAddress,
85
+ estFeesUsd: quoteRes.estFeesUsd,
86
+ estSubtotalUsd: quoteRes.estSubtotalUsd,
87
+ estTotalUsd: quoteRes.estTotalUsd,
88
+ estCheckoutTimeMs: quoteRes.estCheckoutTimeMs,
89
+ estTotalFromAmountBaseUnit: quoteRes.estTotalFromAmountBaseUnit,
90
+ estSubtotalFromAmountBaseUnit: quoteRes.estSubtotalFromAmountBaseUnit,
91
+ estFeesFromAmountBaseUnit: quoteRes.estFeesFromAmountBaseUnit,
92
+ // Added fields
93
+ estFeesFromAmount: new Big(quoteRes.estFeesFromAmountBaseUnit)
94
+ .div(fromMultipler)
95
+ .toString(),
96
+ estSubtotalFromAmount: new Big(quoteRes.estSubtotalFromAmountBaseUnit)
97
+ .div(fromMultipler)
98
+ .toString(),
99
+ estTotalFromAmount: new Big(quoteRes.estTotalFromAmountBaseUnit)
100
+ .div(fromMultipler)
101
+ .toString(),
102
+ } as CheckoutQuoteResponse
103
+ } catch (err: any) {
104
+ throw new Error(
105
+ `An error occured trying to generate a checkout quote: ${err.message}`,
106
+ )
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Initializes a checkout
112
+ * @param userOp The checkout UserOp, signed.
113
+ * @param quoteId The quoteId specific to the checkout.
114
+ * @param apiKey A valid fun api key.
115
+ * @return {Address} The generated deposit address
116
+ */
117
+ export async function initializeCheckout({
118
+ userOp,
119
+ quoteId,
120
+ sourceOfFund,
121
+ apiKey,
122
+ clientMetadata,
123
+ }: CheckoutInitParams): Promise<Address> {
124
+ const body = {
125
+ ...(userOp ? { userOp } : {}),
126
+ quoteId,
127
+ sourceOfFund,
128
+ salt: generateRandomCheckoutSalt(),
129
+ clientMetadata,
130
+ } as CheckoutApiInitParams
131
+ const res = await sendPostRequest({
132
+ uri: `${API_BASE_URL}/checkout`,
133
+ body,
134
+ apiKey,
135
+ })
136
+ if (!res?.depositAddr) {
137
+ throw new ResourceNotFoundError(
138
+ ErrorCode.CheckoutInitDepositAddrNotFound,
139
+ 'Unable to initialize checkout',
140
+ body,
141
+ '',
142
+ 'https://docs.fun.xyz',
143
+ )
144
+ }
145
+ return res.depositAddr as CheckoutInitResponse
146
+ }
147
+
148
+ /**
149
+ * Gets a checkout given a depositAddress
150
+ * @param depositAddress A unique deposit address associated with a backend checkout item.
151
+ * @param apiKey A valid fun api key.
152
+ * @returns The checkout object if exists. Otherwise, null.
153
+ */
154
+ export async function getCheckoutByDepositAddress({
155
+ depositAddress,
156
+ apiKey,
157
+ }: {
158
+ depositAddress: Address
159
+ apiKey: string
160
+ }): Promise<CheckoutHistoryItem | null> {
161
+ try {
162
+ return await sendGetRequest({
163
+ uri: `${API_BASE_URL}/checkout/${depositAddress}`,
164
+ apiKey,
165
+ })
166
+ } catch (err) {
167
+ if (err instanceof ResourceNotFoundError) {
168
+ return null
169
+ }
170
+ throw err
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Gets all checkouts associated with a funWallet
176
+ * @param funWalletAddress A funWallet address.
177
+ * @param apiKey A valid fun api key.
178
+ * @returns A list of checkout objects if exists. Otherwise, an empty array.
179
+ */
180
+ export async function getCheckoutsByFunWalletAddress({
181
+ funWalletAddress,
182
+ apiKey,
183
+ }: {
184
+ funWalletAddress: Address
185
+ apiKey: string
186
+ }): Promise<CheckoutHistoryItem[]> {
187
+ const res = await sendGetRequest({
188
+ uri: `${API_BASE_URL}/checkout/fun-wallet/${funWalletAddress}`,
189
+ apiKey,
190
+ })
191
+ return res || []
192
+ }
193
+
194
+ /**
195
+ * Gets all checkouts associated with a recipient address
196
+ * @param recipientAddress A wallet address.
197
+ * @param apiKey A valid fun api key.
198
+ * @returns A list of checkout objects if exists. Otherwise, an empty array.
199
+ */
200
+ export async function getCheckoutsByRecipientAddress({
201
+ recipientAddress,
202
+ apiKey,
203
+ }: {
204
+ recipientAddress: Address
205
+ apiKey: string
206
+ }): Promise<CheckoutHistoryItem[]> {
207
+ const res = await sendGetRequest({
208
+ uri: `${API_BASE_URL}/checkout/recipient/${recipientAddress}`,
209
+ apiKey,
210
+ })
211
+ return res || []
212
+ }
213
+
214
+ export async function getPaymasterDataForCheckoutSponsoredTransfer({
215
+ depositAddress,
216
+ transferUserOp,
217
+ apiKey,
218
+ }: CheckoutTransferSponsorshipParams): Promise<CheckoutTransferSponsorshipResponse> {
219
+ const body = {
220
+ depositAddress,
221
+ userOp: transferUserOp,
222
+ } as CheckoutTransferSponsorshipApiParams
223
+ const res = await sendPostRequest({
224
+ uri: `${API_BASE_URL}/checkout/sponsorship`,
225
+ body,
226
+ apiKey,
227
+ })
228
+ if (!res) {
229
+ // TODO: Better error handling
230
+ throw new Error('Unable to get sponsorship information')
231
+ }
232
+ return res as CheckoutTransferSponsorshipResponse
233
+ }
@@ -0,0 +1,2 @@
1
+ export * from './endpoints'
2
+ export * from './types'
@@ -0,0 +1,130 @@
1
+ /**===============*
2
+ * CHECKOUT QUOTE *
3
+ *================*/
4
+ import { Address, Hex } from 'viem'
5
+
6
+ // TODO: Define the UserOperation type
7
+ type UserOperation = any
8
+
9
+ // The params required for the actual /checkout/quote api
10
+ export type CheckoutApiQuoteParams = {
11
+ fromChainId: string
12
+ fromTokenAddress: Address
13
+ toChainId: string
14
+ toTokenAddress: Address
15
+ toAmountBaseUnit: string
16
+ checkoutExpirationTimestampSeconds: string
17
+ sponsorInitialTransferGasLimit: string
18
+ refuel: string
19
+ recipientAddr?: Address
20
+ }
21
+
22
+ export type CheckoutQuoteParams = Omit<
23
+ CheckoutApiQuoteParams,
24
+ 'toAmountBaseUnit' | 'checkoutExpirationTimestampSeconds' | 'refuel'
25
+ > & {
26
+ fromTokenDecimals: number
27
+ toTokenDecimals: number
28
+ toTokenAmount: number
29
+ expirationTimestampMs: number
30
+ needsRefuel: boolean
31
+ apiKey: string
32
+ }
33
+
34
+ // The response of the actual /checkout/quote api
35
+ export type CheckoutApiQuoteResponse = {
36
+ quoteId: string
37
+ estTotalFromAmountBaseUnit: string
38
+ estSubtotalFromAmountBaseUnit: string
39
+ estFeesFromAmountBaseUnit: string
40
+ fromTokenAddress: Address
41
+ estFeesUsd: number
42
+ estSubtotalUsd: number
43
+ estTotalUsd: number
44
+ estCheckoutTimeMs: number
45
+ }
46
+
47
+ // The formatted response quote interface from the core sdk
48
+ export type CheckoutQuoteResponse = CheckoutApiQuoteResponse & {
49
+ estTotalFromAmount: string
50
+ estSubtotalFromAmount: string
51
+ estFeesFromAmount: string
52
+ }
53
+
54
+ /**===============*
55
+ * CHECKOUT INIT *
56
+ *================*/
57
+
58
+ export type CheckoutApiInitParams = {
59
+ userOp?: UserOperation
60
+ quoteId: string
61
+ sourceOfFund: string
62
+ salt: bigint
63
+ clientMetadata: object
64
+ }
65
+
66
+ export type CheckoutInitParams = Omit<CheckoutApiInitParams, 'salt'> & {
67
+ apiKey: string
68
+ }
69
+
70
+ export type CheckoutInitResponse = Address
71
+
72
+ // Reference from api server: https://github.com/fun-xyz/fun-api-server/blob/main/src/tables/FunWalletCheckout.ts#L11C1-L21C2
73
+ export enum CheckoutState {
74
+ // In-progress States
75
+ FROM_UNFUNDED = 'FROM_UNFUNDED',
76
+ FROM_FUNDED = 'FROM_FUNDED',
77
+ FROM_POOLED = 'FROM_POOLED',
78
+ TO_UNFUNDED = 'TO_UNFUNDED',
79
+ TO_FUNDED = 'TO_FUNDED',
80
+ TO_POOLED = 'TO_POOLED',
81
+ TO_READY = 'TO_READY',
82
+ PENDING_RECEIVAL = 'PENDING_RECEIVAL',
83
+ // Terminal States
84
+ COMPLETED = 'COMPLETED',
85
+ CHECKOUT_ERROR = 'CHECKOUT_ERROR',
86
+ EXPIRED = 'EXPIRED',
87
+ }
88
+
89
+ export type CheckoutHistoryItem = {
90
+ createdTimeMs: number
91
+ depositAddr: Address
92
+ currentDepositAddr: Address
93
+ recipientAddr: Address
94
+ expirationTimestampSeconds: number
95
+ fromAmountBaseUnit: string
96
+ fromChainId: string
97
+ fromTokenAddress: Address
98
+ funWalletAddr: Address
99
+ lastUpdatedTimeMs: number
100
+ salt: Hex
101
+ state: CheckoutState
102
+ toAmountBaseUnit: string
103
+ toChainId: string
104
+ toTokenAddress: Address
105
+ userOp: UserOperation
106
+ version: number
107
+ clientMetadata: object
108
+ }
109
+
110
+ /**===============================*
111
+ * CHECKOUT TRANSFER SPONSORSHIP *
112
+ *================================*/
113
+
114
+ export type CheckoutTransferSponsorshipParams = {
115
+ transferUserOp: UserOperation
116
+ depositAddress: Address
117
+ apiKey: string
118
+ }
119
+
120
+ export type CheckoutTransferSponsorshipApiParams = {
121
+ userOp: UserOperation
122
+ depositAddress: Address
123
+ }
124
+
125
+ export type CheckoutTransferSponsorshipResponse = {
126
+ signerAddress: Address
127
+ signature: Hex
128
+ deadline: number
129
+ paymasterAndData: Hex
130
+ }
@@ -0,0 +1,4 @@
1
+ export * from './assets'
2
+ export * from './checkout'
3
+ export * from './mesh'
4
+ export * from './moonpay'