@funkit/core 2.1.2-next.0 → 2.1.2-next.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 (170) hide show
  1. package/dist/index.js +16232 -12
  2. package/dist/index.js.map +7 -1
  3. package/dist/src/viem/Converter.d.ts +4 -4
  4. package/package.json +6 -4
  5. package/dist/src/abis/ApproveAndExec.json +0 -106
  6. package/dist/src/abis/ApproveAndSwap.json +0 -141
  7. package/dist/src/abis/CheckoutPaymaster.json +0 -3358
  8. package/dist/src/abis/ERC20.json +0 -1
  9. package/dist/src/abis/ERC721.json +0 -1
  10. package/dist/src/abis/EntryPoint.json +0 -1023
  11. package/dist/src/abis/EstimationPaymaster.json +0 -266
  12. package/dist/src/abis/FeePercentOracle.json +0 -218
  13. package/dist/src/abis/FunWallet.json +0 -758
  14. package/dist/src/abis/FunWalletFactory.json +0 -232
  15. package/dist/src/abis/GaslessPaymaster.json +0 -558
  16. package/dist/src/abis/LidoWithdrawQueue.json +0 -1
  17. package/dist/src/abis/RoleBasedAccessControl.json +0 -836
  18. package/dist/src/abis/TestNFT.json +0 -226
  19. package/dist/src/abis/TokenPaymaster.json +0 -696
  20. package/dist/src/abis/TokenPriceOracle.json +0 -57
  21. package/dist/src/abis/UniswapV2Factory.json +0 -1
  22. package/dist/src/abis/UniswapV2Router02.json +0 -1
  23. package/dist/src/abis/UniswapV3LimitOrder.json +0 -1
  24. package/dist/src/abis/UserAuthentication.json +0 -338
  25. package/dist/src/abis/univ3factory.json +0 -1
  26. package/dist/src/abis/univ3quoter.json +0 -1
  27. package/dist/src/abis/univ3router.json +0 -1
  28. package/dist/src/actions/AccessControl.js +0 -87
  29. package/dist/src/actions/AccessControl.js.map +0 -1
  30. package/dist/src/actions/BatchActions.js +0 -8
  31. package/dist/src/actions/BatchActions.js.map +0 -1
  32. package/dist/src/actions/Bridge.js +0 -42
  33. package/dist/src/actions/Bridge.js.map +0 -1
  34. package/dist/src/actions/FirstClassActions.js +0 -329
  35. package/dist/src/actions/FirstClassActions.js.map +0 -1
  36. package/dist/src/actions/Group.js +0 -30
  37. package/dist/src/actions/Group.js.map +0 -1
  38. package/dist/src/actions/LimitOrder.js +0 -43
  39. package/dist/src/actions/LimitOrder.js.map +0 -1
  40. package/dist/src/actions/Stake.js +0 -108
  41. package/dist/src/actions/Stake.js.map +0 -1
  42. package/dist/src/actions/Swap.js +0 -150
  43. package/dist/src/actions/Swap.js.map +0 -1
  44. package/dist/src/actions/Token.js +0 -103
  45. package/dist/src/actions/Token.js.map +0 -1
  46. package/dist/src/actions/index.js +0 -8
  47. package/dist/src/actions/index.js.map +0 -1
  48. package/dist/src/actions/types.js +0 -14
  49. package/dist/src/actions/types.js.map +0 -1
  50. package/dist/src/apis/AccessControlApis.js +0 -19
  51. package/dist/src/apis/AccessControlApis.js.map +0 -1
  52. package/dist/src/apis/BridgeApis.js +0 -54
  53. package/dist/src/apis/BridgeApis.js.map +0 -1
  54. package/dist/src/apis/ContractApis.js +0 -7
  55. package/dist/src/apis/ContractApis.js.map +0 -1
  56. package/dist/src/apis/GroupApis.js +0 -15
  57. package/dist/src/apis/GroupApis.js.map +0 -1
  58. package/dist/src/apis/InfoApis.js +0 -53
  59. package/dist/src/apis/InfoApis.js.map +0 -1
  60. package/dist/src/apis/ListenerApis.js +0 -31
  61. package/dist/src/apis/ListenerApis.js.map +0 -1
  62. package/dist/src/apis/NFTApis.js +0 -29
  63. package/dist/src/apis/NFTApis.js.map +0 -1
  64. package/dist/src/apis/OperationApis.js +0 -76
  65. package/dist/src/apis/OperationApis.js.map +0 -1
  66. package/dist/src/apis/PaymasterApis.js +0 -18
  67. package/dist/src/apis/PaymasterApis.js.map +0 -1
  68. package/dist/src/apis/SwapApis.js +0 -40
  69. package/dist/src/apis/SwapApis.js.map +0 -1
  70. package/dist/src/apis/UserApis.js +0 -56
  71. package/dist/src/apis/UserApis.js.map +0 -1
  72. package/dist/src/apis/index.js +0 -9
  73. package/dist/src/apis/index.js.map +0 -1
  74. package/dist/src/apis/types.js +0 -2
  75. package/dist/src/apis/types.js.map +0 -1
  76. package/dist/src/auth/Auth.js +0 -321
  77. package/dist/src/auth/Auth.js.map +0 -1
  78. package/dist/src/auth/SessionKeyAuth.js +0 -115
  79. package/dist/src/auth/SessionKeyAuth.js.map +0 -1
  80. package/dist/src/auth/index.js +0 -3
  81. package/dist/src/auth/index.js.map +0 -1
  82. package/dist/src/auth/types.js +0 -2
  83. package/dist/src/auth/types.js.map +0 -1
  84. package/dist/src/common/constants.js +0 -477
  85. package/dist/src/common/constants.js.map +0 -1
  86. package/dist/src/common/index.js +0 -3
  87. package/dist/src/common/index.js.map +0 -1
  88. package/dist/src/common/types.js +0 -2
  89. package/dist/src/common/types.js.map +0 -1
  90. package/dist/src/config/Config.js +0 -50
  91. package/dist/src/config/Config.js.map +0 -1
  92. package/dist/src/config/index.js +0 -3
  93. package/dist/src/config/index.js.map +0 -1
  94. package/dist/src/config/types.js +0 -2
  95. package/dist/src/config/types.js.map +0 -1
  96. package/dist/src/data/Chain.js +0 -209
  97. package/dist/src/data/Chain.js.map +0 -1
  98. package/dist/src/data/NFT.js +0 -101
  99. package/dist/src/data/NFT.js.map +0 -1
  100. package/dist/src/data/Operation.js +0 -88
  101. package/dist/src/data/Operation.js.map +0 -1
  102. package/dist/src/data/SolidityData.js +0 -84
  103. package/dist/src/data/SolidityData.js.map +0 -1
  104. package/dist/src/data/Token.js +0 -118
  105. package/dist/src/data/Token.js.map +0 -1
  106. package/dist/src/data/index.js +0 -7
  107. package/dist/src/data/index.js.map +0 -1
  108. package/dist/src/data/types.js +0 -22
  109. package/dist/src/data/types.js.map +0 -1
  110. package/dist/src/errors/BaseError.js +0 -25
  111. package/dist/src/errors/BaseError.js.map +0 -1
  112. package/dist/src/errors/ClientError.js +0 -63
  113. package/dist/src/errors/ClientError.js.map +0 -1
  114. package/dist/src/errors/ServerError.js +0 -13
  115. package/dist/src/errors/ServerError.js.map +0 -1
  116. package/dist/src/errors/errors.json +0 -626
  117. package/dist/src/errors/index.js +0 -5
  118. package/dist/src/errors/index.js.map +0 -1
  119. package/dist/src/errors/types.js +0 -48
  120. package/dist/src/errors/types.js.map +0 -1
  121. package/dist/src/sponsors/CheckoutSponsor.js +0 -61
  122. package/dist/src/sponsors/CheckoutSponsor.js.map +0 -1
  123. package/dist/src/sponsors/GaslessSponsor.js +0 -75
  124. package/dist/src/sponsors/GaslessSponsor.js.map +0 -1
  125. package/dist/src/sponsors/Sponsor.js +0 -80
  126. package/dist/src/sponsors/Sponsor.js.map +0 -1
  127. package/dist/src/sponsors/TokenSponsor.js +0 -251
  128. package/dist/src/sponsors/TokenSponsor.js.map +0 -1
  129. package/dist/src/sponsors/index.js +0 -5
  130. package/dist/src/sponsors/index.js.map +0 -1
  131. package/dist/src/sponsors/types.js +0 -8
  132. package/dist/src/sponsors/types.js.map +0 -1
  133. package/dist/src/utils/ApiUtils.js +0 -94
  134. package/dist/src/utils/ApiUtils.js.map +0 -1
  135. package/dist/src/utils/AuthUtils.js +0 -31
  136. package/dist/src/utils/AuthUtils.js.map +0 -1
  137. package/dist/src/utils/ChainUtils.js +0 -131
  138. package/dist/src/utils/ChainUtils.js.map +0 -1
  139. package/dist/src/utils/CheckoutUtils.js +0 -28
  140. package/dist/src/utils/CheckoutUtils.js.map +0 -1
  141. package/dist/src/utils/GroupUtils.js +0 -26
  142. package/dist/src/utils/GroupUtils.js.map +0 -1
  143. package/dist/src/utils/MerkleUtils.js +0 -86
  144. package/dist/src/utils/MerkleUtils.js.map +0 -1
  145. package/dist/src/utils/PaymasterUtils.js +0 -17
  146. package/dist/src/utils/PaymasterUtils.js.map +0 -1
  147. package/dist/src/utils/SwapUtils.js +0 -193
  148. package/dist/src/utils/SwapUtils.js.map +0 -1
  149. package/dist/src/utils/TypeUtils.js +0 -9
  150. package/dist/src/utils/TypeUtils.js.map +0 -1
  151. package/dist/src/utils/UserOpUtils.js +0 -171
  152. package/dist/src/utils/UserOpUtils.js.map +0 -1
  153. package/dist/src/utils/ViemUtils.js +0 -30
  154. package/dist/src/utils/ViemUtils.js.map +0 -1
  155. package/dist/src/utils/WalletUtils.js +0 -56
  156. package/dist/src/utils/WalletUtils.js.map +0 -1
  157. package/dist/src/utils/index.js +0 -9
  158. package/dist/src/utils/index.js.map +0 -1
  159. package/dist/src/viem/ContractInterface.js +0 -90
  160. package/dist/src/viem/ContractInterface.js.map +0 -1
  161. package/dist/src/viem/Converter.js +0 -47
  162. package/dist/src/viem/Converter.js.map +0 -1
  163. package/dist/src/viem/index.js +0 -3
  164. package/dist/src/viem/index.js.map +0 -1
  165. package/dist/src/wallet/FunWallet.js +0 -804
  166. package/dist/src/wallet/FunWallet.js.map +0 -1
  167. package/dist/src/wallet/index.js +0 -3
  168. package/dist/src/wallet/index.js.map +0 -1
  169. package/dist/src/wallet/types.js +0 -2
  170. package/dist/src/wallet/types.js.map +0 -1
@@ -1,804 +0,0 @@
1
- import { getAllWalletNFTs, getAllWalletNFTsByChainId, getAllWalletTokens, getAllWalletTokensByChainId, getMoonpayOffRampUrl, getMoonpayOnRampSupportedCurrencies, getMoonpayOnRampUrl, getWalletLidoWithdrawalsByChainId, } from '@funkit/api-base';
2
- import { concat, createPublicClient, encodeAbiParameters, http, isAddress, isHex, keccak256, pad, toBytes, } from 'viem';
3
- import { FirstClassActions } from '../actions/FirstClassActions';
4
- import { checkWalletAccessInitialization, initializeWalletAccess, } from '../apis/AccessControlApis';
5
- import { getGroups } from '../apis/GroupApis';
6
- import { createOp, deleteOp, executeOp, getFullReceipt, getOps, getOpsOfWallet, scheduleOp, signOp, } from '../apis/OperationApis';
7
- import { addTransaction } from '../apis/PaymasterApis';
8
- import { addUserToWallet } from '../apis/UserApis';
9
- import { ENTRYPOINT_CONTRACT_INTERFACE, WALLET_CONTRACT_INTERFACE, } from '../common';
10
- import { AddressZero, FACTORY_CONTRACT_INTERFACE } from '../common/constants';
11
- import { parseOptions } from '../config';
12
- import { AuthType, Chain, encodeLoginData, encodeUserAuthInitData, Operation, OperationStatus, OperationType, toBytes32Arr, Token, } from '../data';
13
- import { ErrorCode, InternalFailureError, InvalidParameterError, } from '../errors';
14
- import { CheckoutSponsor, GaslessSponsor, TokenSponsor } from '../sponsors';
15
- import { generateRandomNonceKey, getWalletAddress, isGroupOperation, isSignatureMissing, isWalletInitOp, } from '../utils';
16
- import { getPaymasterType } from '../utils/PaymasterUtils';
17
- import { isBytes32 } from '../utils/TypeUtils';
18
- export class FunWallet extends FirstClassActions {
19
- walletUniqueId;
20
- userInfo;
21
- address;
22
- /**
23
- * Creates FunWallet object
24
- * @constructor
25
- * @param {object} params - The parameters for the constructing fun wallet - (users, uniqueId) or walletAddr
26
- */
27
- constructor(params) {
28
- const chain = globalThis.globalEnvOption.chain;
29
- super(chain);
30
- if (typeof params === 'string') {
31
- if (isAddress(params)) {
32
- this.address = params;
33
- }
34
- else {
35
- throw new InvalidParameterError(ErrorCode.InvalidParameter, 'string input must be an address type', params, 'Provide either (uniqueId, users) or walletAddr when constructing a FunWallet', 'https://docs.fun.xyz/how-to-guides/execute-transactions/create-funwallet#create-funwallet-manual-funwallet-creation');
36
- }
37
- }
38
- else {
39
- const { users, uniqueId } = params;
40
- if (!uniqueId || !isBytes32(uniqueId) || !users || users.length <= 0) {
41
- throw new InvalidParameterError(ErrorCode.InvalidParameter, 'uniqueId must be bytes32 and users must be non-empty', params, 'The uniqueId field should be a 32 byte Hexstring and the users field should be an array of User objects', 'https://docs.fun.xyz/how-to-guides/execute-transactions/create-funwallet#create-funwallet-manual-funwallet-creation');
42
- }
43
- this.userInfo = new Map(users?.map((user) => {
44
- if (!user.userId || !isHex(user.userId)) {
45
- throw new InvalidParameterError(ErrorCode.InvalidParameter, 'userId is required and must be a hex string', users, 'Provide hex string userId when creating a FunWallet', 'https://docs.fun.xyz/how-to-guides/execute-transactions/create-funwallet#create-funwallet-manual-funwallet-creation');
46
- }
47
- if (user.groupInfo &&
48
- (!Number.isInteger(user.groupInfo.threshold) ||
49
- !Array.isArray(user.groupInfo.memberIds) ||
50
- !user.groupInfo.memberIds.every((memberId) => isHex(memberId)))) {
51
- throw new InvalidParameterError(ErrorCode.InvalidParameter, 'groupInfo must be an object with threshold as integer and memberIds as array of hex strings', users, 'Provide valid groupInfo when creating a FunWallet', 'https://docs.fun.xyz/how-to-guides/execute-transactions/create-funwallet#create-funwallet-manual-funwallet-creation');
52
- }
53
- return [pad(user.userId, { size: 32 }), user];
54
- }));
55
- this.walletUniqueId = uniqueId;
56
- }
57
- }
58
- /**
59
- * Retrieves the wallet address associated with this FunWallet. The address should be the same for all EVM chains so no input is needed
60
- * If the address is not already cached, it fetches it using the wallet's unique ID and chain information.
61
- * @returns {Promise<Address>} The wallet address.
62
- */
63
- async getAddress(txOptions = globalThis.globalEnvOption) {
64
- if (!this.address) {
65
- const chainIdentifier = txOptions.chain;
66
- this.address = await getWalletAddress(await Chain.getChain({ chainIdentifier: chainIdentifier ?? 137 }), this.walletUniqueId);
67
- }
68
- return this.address;
69
- }
70
- /**
71
- * Retrieves the wallet address associated with the provided unique ID using the given API key.
72
- * @param {string} uniqueId - The unique ID of the wallet.
73
- * @param {string} apiKey - The API key to access the required resources.
74
- * @returns {Promise<Address>} The wallet address.
75
- */
76
- static async getAddress(uniqueId, apiKey) {
77
- ;
78
- globalThis.globalEnvOption.apiKey = apiKey;
79
- return await getWalletAddress(await Chain.getChain({ chainIdentifier: 137 }), keccak256(toBytes(uniqueId)));
80
- }
81
- /**
82
- * Retrieves the wallet address associated with the provided unique ID in an offline environment.
83
- * @param {string} uniqueId - The unique ID of the wallet.
84
- * @param {string} rpcUrl - The URL of the RPC endpoint for offline querying.
85
- * @param {Address} factoryAddress - The address of the factory contract.
86
- * @returns {Promise<Address>} The wallet address.
87
- */
88
- static async getAddressOffline(uniqueId, rpcUrl, factoryAddress) {
89
- const client = await createPublicClient({
90
- transport: http(rpcUrl),
91
- });
92
- return await FACTORY_CONTRACT_INTERFACE.readFromChain(factoryAddress, 'getAddress', [keccak256(toBytes(uniqueId))], client);
93
- }
94
- /**
95
- * Get all tokens for a specific chain
96
- * @param {string} chainId string version of the chainId or ALL. If empty, then default to the one in globalEnvOption
97
- * @param {boolean} onlyVerifiedTokens If true, only return alchemy tokens that are verified(filters spam) - defaults to false
98
- * @returns JSON
99
- */
100
- async getTokens(chainIdInput, onlyVerifiedTokens = false) {
101
- let chainId;
102
- if (!chainIdInput) {
103
- const chain = await Chain.getChain({
104
- chainIdentifier: globalThis.globalEnvOption.chain,
105
- });
106
- chainId = await chain.getChainId();
107
- }
108
- else {
109
- chainId = chainIdInput;
110
- }
111
- const walletAddress = await this.getAddress();
112
- return chainId === 'ALL'
113
- ? await getAllWalletTokens({
114
- walletAddress,
115
- onlyVerifiedTokens,
116
- apiKey: globalThis.globalEnvOption.apiKey,
117
- })
118
- : await getAllWalletTokensByChainId({
119
- chainId,
120
- walletAddress,
121
- onlyVerifiedTokens,
122
- apiKey: globalThis.globalEnvOption.apiKey,
123
- });
124
- }
125
- /**
126
- * Given an address and a chain, returns all NFTs owned by that address
127
- * @param {string} chainId string version of the chainId or ALL. If empty, then default to the one in globalEnvOption
128
- * @returns array
129
- */
130
- async getNFTs(chainIdInput) {
131
- let chainId;
132
- if (!chainIdInput) {
133
- const chain = await Chain.getChain({
134
- chainIdentifier: globalThis.globalEnvOption.chain,
135
- });
136
- chainId = await chain.getChainId();
137
- }
138
- else {
139
- chainId = chainIdInput;
140
- }
141
- const walletAddress = await this.getAddress();
142
- return chainId === 'ALL'
143
- ? await getAllWalletNFTs({
144
- walletAddress,
145
- apiKey: globalThis.globalEnvOption.apiKey,
146
- })
147
- : await getAllWalletNFTsByChainId({
148
- chainId,
149
- walletAddress,
150
- apiKey: globalThis.globalEnvOption.apiKey,
151
- });
152
- }
153
- async getLidoWithdrawals() {
154
- const walletAddress = await this.getAddress();
155
- return await getWalletLidoWithdrawalsByChainId({
156
- chainId: '1',
157
- walletAddress,
158
- apiKey: globalThis.globalEnvOption.apiKey,
159
- });
160
- }
161
- /**
162
- * Get all tokens on all supported chains. Merge tokens by symbol
163
- * @param {string} chainIdInput string version of the chainId or ALL. If empty, then default to the one in globalEnvOption
164
- * @param {*} onlyVerifiedTokens true if you want to filter out spam tokens(Uses alchemy lists)
165
- * @param {boolean} checkStatus true if you want to check if the address has any pending lido withdrawals
166
- * @returns JSON of all tokens owned by address
167
- */
168
- async getAssets(chainIdInput, onlyVerifiedTokens = false, checkStatus = false) {
169
- let chainId;
170
- if (!chainIdInput) {
171
- const chain = await Chain.getChain({
172
- chainIdentifier: globalThis.globalEnvOption.chain,
173
- });
174
- chainId = await chain.getChainId();
175
- }
176
- else {
177
- chainId = chainIdInput;
178
- }
179
- const tokens = await this.getTokens(chainId, onlyVerifiedTokens);
180
- const lidoWithdrawals = checkStatus ? await this.getLidoWithdrawals() : {};
181
- return { ...lidoWithdrawals, ...tokens };
182
- }
183
- /**
184
- * Retrieves the nonce value for the specified sender address and nonce key.
185
- * If the nonce is unavailable, a random nonce key is generated and returned as the nonce.
186
- * @param {string} sender - The sender's address.
187
- * @param {string} key - The nonce key (default: randomly generated).
188
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
189
- * @returns {Promise<bigint>} The nonce value.
190
- */
191
- async getNonce(sender, key = generateRandomNonceKey(), txOptions = globalThis.globalEnvOption) {
192
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
193
- const entryPointAddress = await chain.getAddress('entryPointAddress');
194
- let nonce = undefined;
195
- let retryCount = 3;
196
- while ((nonce === undefined || nonce === null) && retryCount > 0) {
197
- nonce = await ENTRYPOINT_CONTRACT_INTERFACE.readFromChain(entryPointAddress, 'getNonce', [sender, key], chain);
198
- retryCount--;
199
- }
200
- if (nonce !== undefined && nonce !== null) {
201
- return BigInt(nonce);
202
- }
203
- else {
204
- return BigInt(key << 64n);
205
- }
206
- }
207
- /**
208
- * Retrieves a list of operations associated with the wallet.
209
- * @param {OperationStatus} status - The status of operations to retrieve (default: OperationStatus.ALL).
210
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
211
- * @returns {Promise<Operation[]>} A list of operations.
212
- */
213
- async getOperations(status = OperationStatus.ALL, txOptions = globalThis.globalEnvOption) {
214
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
215
- return await getOpsOfWallet(await this.getAddress(txOptions), await chain.getChainId(), status);
216
- }
217
- /**
218
- * Retrieves a specific operation by its ID.
219
- * @param {Hex} opId - The ID of the operation to retrieve.
220
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
221
- * @returns {Promise<Operation>} The requested operation.
222
- */
223
- async getOperation(opId, txOptions = globalThis.globalEnvOption) {
224
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
225
- return (await getOps([opId], await chain.getChainId()))[0];
226
- }
227
- /**
228
- * Retrieves a list of users associated with the wallet and their potential corresponding group information.
229
- * @param {Auth} auth - The authentication instance for retrieving user information.
230
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
231
- * @returns {Promise<User[]>} A list of users with their group information.
232
- */
233
- async getUsers(auth, txOptions = globalThis.globalEnvOption) {
234
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
235
- const storedUserIds = await auth.getUserIds(await this.getAddress(txOptions), await chain.getChainId());
236
- const userIds = new Set([...storedUserIds]);
237
- if (this.userInfo) {
238
- for (const userId of this.userInfo.keys()) {
239
- userIds.add(userId.toLowerCase());
240
- }
241
- }
242
- const users = [];
243
- const groupIds = [];
244
- for (const userId of userIds) {
245
- if (pad(userId, { size: 32 }).toLowerCase() === (await auth.getUserId())) {
246
- users.push({ userId: pad(userId, { size: 32 }) });
247
- }
248
- else {
249
- groupIds.push(pad(userId, { size: 32 }));
250
- }
251
- }
252
- if (groupIds && groupIds.length > 0) {
253
- const groups = await getGroups(groupIds, await chain.getChainId());
254
- groups.forEach((group) => {
255
- users.push({
256
- userId: group.groupId,
257
- groupInfo: {
258
- threshold: group.threshold,
259
- memberIds: group.memberIds,
260
- },
261
- });
262
- });
263
- }
264
- return users;
265
- }
266
- /**
267
- * Checks the deployment status of the wallet's address to determine if it's a contract.
268
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
269
- * @returns {Promise<boolean>} `true` if the address is a contract, `false` otherwise.
270
- */
271
- async getDeploymentStatus(txOptions = globalThis.globalEnvOption) {
272
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
273
- return await chain.addressIsContract(await this.getAddress(txOptions));
274
- }
275
- /**
276
- * Creates the wallet.
277
- * @param {Auth} auth - The authentication instance for the user.
278
- * @param {string} userId - The ID of the user initiating the operation.
279
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
280
- * @returns {Promise<Operation>} The operation to create the wallet.
281
- */
282
- async create(auth, userId, txOptions = globalThis.globalEnvOption) {
283
- const transactionParams = {
284
- to: await this.getAddress(txOptions),
285
- data: '0x',
286
- value: 0n,
287
- };
288
- return await this.createOperation(auth, userId, transactionParams, txOptions);
289
- }
290
- /**
291
- * Saves the wallet to the authentication system.
292
- * @param auth - The auth or signer to save the wallet to.
293
- * @param txOptions - The configuration options.
294
- * @returns A Promise that resolves when the wallet is saved to the authentication system.
295
- */
296
- async saveWalletToAuth(auth, txOptions = globalThis.globalEnvOption) {
297
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
298
- const walletAddr = await this.getAddress(txOptions);
299
- const userId = await auth.getUserId();
300
- const users = await auth.getUserIds(walletAddr, await chain.getChainId());
301
- if (!users.includes(userId)) {
302
- if ((await checkWalletAccessInitialization(walletAddr)) === false) {
303
- await initializeWalletAccess(walletAddr, await auth.getAddress());
304
- }
305
- await addUserToWallet(await auth.getAddress(), await chain.getChainId(), walletAddr, [userId], this.walletUniqueId);
306
- }
307
- }
308
- /**
309
- * Generates an on-ramp URL for the account address.
310
- * @param {Address} address - The account address (optional, defaults to the wallet's address).
311
- * @param {string} currencyCode - The currency code (optional, defaults to undefined to allow users to select).
312
- * @returns {Promise<string>} The on-ramp URL.
313
- */
314
- async onRamp(address, currencyCode) {
315
- return await getMoonpayOnRampUrl({
316
- apiKey: globalThis.globalEnvOption.apiKey,
317
- walletAddr: address ? address : await this.getAddress(),
318
- currencyCode: currencyCode ? currencyCode : undefined,
319
- });
320
- }
321
- /**
322
- * Generates an off-ramp URL for the account address.
323
- * @param {Address} address - The account address (optional, defaults to the wallet's address).
324
- * @returns {Promise<string>} The off-ramp URL.
325
- */
326
- async offRamp(address) {
327
- return await getMoonpayOffRampUrl({
328
- apiKey: globalThis.globalEnvOption.apiKey,
329
- walletAddr: address ? address : await this.getAddress(),
330
- });
331
- }
332
- /**
333
- * Retrieves the supported currencies for on-ramp.
334
- * @returns {Promise<MoonpayCurrency[]>} The supported currencies.
335
- */
336
- async getSupportedCurrencies() {
337
- return await getMoonpayOnRampSupportedCurrencies({
338
- apiKey: globalThis.globalEnvOption.apiKey,
339
- });
340
- }
341
- /**
342
- * Creates a new operation to be associated with the wallet and prepares it for execution.
343
- * @param {Auth} auth - The authentication instance for the user.
344
- * @param {string} userId - The ID of the user initiating the operation.
345
- * @param {TransactionParams} transactionParams - The parameters for the transaction.
346
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
347
- * @returns {Promise<Operation>} The created and prepared operation.
348
- */
349
- async createOperation(auth, userId, transactionParams, txOptions = globalThis.globalEnvOption) {
350
- if (!userId || userId === '') {
351
- throw new InvalidParameterError(ErrorCode.MissingParameter, 'userId is required', { userId }, 'Provide userId when createOperation', 'https://docs.fun.xyz/how-to-guides/execute-transactions#execute-transactions');
352
- }
353
- userId = pad(userId, { size: 32 }).toLowerCase();
354
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
355
- const sender = await this.getAddress(txOptions);
356
- const initCode = (await chain.addressIsContract(sender))
357
- ? '0x'
358
- : await this.getThisInitCode(chain);
359
- let paymasterAndData = '0x';
360
- let maxFeePerGas, maxPriorityFeePerGas;
361
- const chainId = await chain.getChainId();
362
- const OPStackChains = ['10', '8453'];
363
- if (OPStackChains.includes(chainId)) {
364
- const gasPrice = await chain.getFeeData();
365
- maxFeePerGas = gasPrice.maxFeePerGas;
366
- maxPriorityFeePerGas = gasPrice.maxPriorityFeePerGas;
367
- }
368
- else {
369
- maxFeePerGas = 1n;
370
- maxPriorityFeePerGas = 1n;
371
- }
372
- const partialOp = {
373
- callData: await this.buildCalldata(auth, userId, transactionParams, txOptions),
374
- paymasterAndData,
375
- sender,
376
- maxFeePerGas,
377
- maxPriorityFeePerGas,
378
- initCode,
379
- nonce: txOptions.nonce !== null && txOptions.nonce !== undefined
380
- ? txOptions.nonce
381
- : await this.getNonce(sender),
382
- preVerificationGas: 100000n,
383
- callGasLimit: BigInt(10e6),
384
- verificationGasLimit: BigInt(10e6),
385
- };
386
- if ((await chain.getChainId()) === '36865') {
387
- partialOp.callGasLimit = BigInt(10e5);
388
- partialOp.verificationGasLimit = BigInt(10e5);
389
- }
390
- const isGroupOp = (await auth.getUserId()) !== userId;
391
- const operation = new Operation(partialOp, {
392
- chainId: await chain.getChainId(),
393
- opType: isGroupOp
394
- ? OperationType.GROUP_OPERATION
395
- : OperationType.SINGLE_OPERATION,
396
- authType: isGroupOp ? AuthType.MULTI_SIG : AuthType.ECDSA,
397
- walletAddr: await this.getAddress(txOptions),
398
- proposer: await auth.getAddress(),
399
- });
400
- if (isGroupOp) {
401
- operation.groupId = pad(userId, { size: 32 });
402
- }
403
- if (txOptions.gasSponsor && Object.keys(txOptions.gasSponsor).length > 0) {
404
- if (txOptions.gasSponsor.token) {
405
- const sponsor = new TokenSponsor(txOptions);
406
- if (txOptions.gasSponsor.usePermit) {
407
- paymasterAndData = (await sponsor.getPaymasterAndDataPermit(operation, await this.getAddress(txOptions), userId, auth)).toLowerCase();
408
- }
409
- else {
410
- paymasterAndData = (await sponsor.getPaymasterAndData(txOptions)).toLowerCase();
411
- }
412
- }
413
- else if (txOptions.gasSponsor.useCheckoutSponsor) {
414
- const sponsor = new CheckoutSponsor(txOptions);
415
- paymasterAndData = (await sponsor.getPaymasterAndData(txOptions)).toLowerCase();
416
- }
417
- else {
418
- const sponsor = new GaslessSponsor(txOptions);
419
- paymasterAndData = (await sponsor.getPaymasterAndData(txOptions)).toLowerCase();
420
- }
421
- }
422
- operation.userOp.paymasterAndData = paymasterAndData;
423
- const estimatedOperation = await this.estimateOperation(auth, userId, operation, txOptions);
424
- if (txOptions.bypassInit) {
425
- estimatedOperation.userOp.initCode = '0x';
426
- }
427
- // sign the userOp directly here as we do not have the opId yet
428
- estimatedOperation.userOp.signature = await auth.signOp(estimatedOperation, chain, isGroupOperation(operation));
429
- if (txOptions.skipDBAction !== true) {
430
- const opId = await createOp(estimatedOperation);
431
- estimatedOperation.opId = opId;
432
- if (!(await checkWalletAccessInitialization(sender))) {
433
- await initializeWalletAccess(sender, await auth.getAddress());
434
- }
435
- }
436
- return estimatedOperation;
437
- }
438
- /**
439
- * Signs an operation using the provided authentication instance and returns the signed operation.
440
- * @param {Auth} auth - The authentication instance for the user.
441
- * @param {Operation} operation - The operation to be signed.
442
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
443
- * @returns {Promise<Operation>} The signed operation.
444
- */
445
- async signOperation(auth, operation, txOptions = globalThis.globalEnvOption) {
446
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
447
- operation = Operation.convertTypeToObject(operation);
448
- operation.userOp.signature = await auth.signOp(operation, chain, isGroupOperation(operation));
449
- if (isGroupOperation(operation) && txOptions.skipDBAction !== true) {
450
- await signOp(operation.opId, await chain.getChainId(), operation.userOp.signature, await auth.getAddress(), this.userInfo?.get(operation.groupId)?.groupInfo?.threshold);
451
- }
452
- return operation;
453
- }
454
- /**
455
- * Executes an operation and returns the execution receipt.
456
- * @param {Auth} auth - The authentication instance for the user.
457
- * @param {Operation} operation - The operation to be executed.
458
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
459
- * @returns {Promise<ExecutionReceipt>} The execution receipt of the operation.
460
- */
461
- async executeOperation(auth, operation, txOptions = globalThis.globalEnvOption) {
462
- txOptions = parseOptions(txOptions);
463
- operation = Operation.convertTypeToObject(operation);
464
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
465
- const chainId = await chain.getChainId();
466
- if (txOptions.skipDBAction !== true) {
467
- // cache group info
468
- if (isGroupOperation(operation)) {
469
- const groups = await getGroups([operation.groupId], chainId);
470
- if (groups && groups.length > 0) {
471
- // could be empty as a new wallet wants to create a group
472
- this.userInfo?.set(operation.groupId, {
473
- userId: operation.groupId,
474
- groupInfo: {
475
- threshold: groups[0].threshold,
476
- memberIds: groups[0].memberIds,
477
- },
478
- });
479
- }
480
- }
481
- }
482
- const threshold = this.userInfo?.get(operation.groupId)?.groupInfo?.threshold ?? 1;
483
- if (threshold <= 1) {
484
- if (!operation.userOp.signature || operation.userOp.signature === '0x') {
485
- operation.userOp.signature = await auth.signOp(operation, chain, isGroupOperation(operation));
486
- }
487
- }
488
- else {
489
- if (txOptions.skipDBAction !== true) {
490
- // check remote collected signature
491
- const storedOps = await getOps([operation.opId], chainId);
492
- let collectedSigCount;
493
- if (isSignatureMissing(await auth.getUserId(), storedOps[0]?.signatures)) {
494
- collectedSigCount = storedOps[0]?.signatures?.length
495
- ? storedOps[0]?.signatures?.length + 1
496
- : 1;
497
- if (collectedSigCount >= threshold) {
498
- operation.userOp.signature = await auth.signOp(operation, chain, isGroupOperation(operation));
499
- }
500
- }
501
- else {
502
- collectedSigCount = storedOps[0]?.signatures?.length ?? 1;
503
- }
504
- if (collectedSigCount < threshold) {
505
- throw new InvalidParameterError(ErrorCode.InsufficientSignatures, 'Signatures are not sufficient to execute the operation', { threshold, collectedSigCount, chainId }, 'Only execute operation with enough signatures', 'https://docs.fun.xyz/how-to-guides/execute-transactions#execute-transactions');
506
- }
507
- }
508
- else {
509
- throw new InvalidParameterError(ErrorCode.InsufficientSignatures, 'Signatures are not sufficient to execute the operation', { threshold, chainId, skipDBAction: txOptions.skipDBAction }, 'Only execute operation with enough signatures', 'https://docs.fun.xyz/how-to-guides/execute-transactions#execute-transactions');
510
- }
511
- }
512
- let receipt;
513
- if (isGroupOperation(operation)) {
514
- receipt = await executeOp({
515
- opId: operation.opId,
516
- chainId,
517
- executedBy: await auth.getAddress(),
518
- entryPointAddress: await chain.getAddress('entryPointAddress'),
519
- signature: operation.userOp.signature,
520
- groupInfo: this.userInfo?.get(operation.groupId)?.groupInfo,
521
- });
522
- }
523
- else {
524
- receipt = await executeOp({
525
- opId: operation.opId,
526
- chainId,
527
- executedBy: await auth.getAddress(),
528
- entryPointAddress: await chain.getAddress('entryPointAddress'),
529
- signature: operation.userOp.signature,
530
- userOp: operation.userOp,
531
- });
532
- }
533
- receipt = await getFullReceipt(operation.opId, chainId, receipt.userOpHash);
534
- if (isWalletInitOp(operation.userOp) && txOptions.skipDBAction !== true) {
535
- await addUserToWallet(await auth.getAddress(), chainId, await this.getAddress(txOptions), Array.from(this.userInfo.keys()), this.walletUniqueId);
536
- if (txOptions?.gasSponsor?.sponsorAddress) {
537
- const paymasterType = getPaymasterType(txOptions);
538
- addTransaction(await chain.getChainId(), Date.now(), receipt.txId, {
539
- action: 'sponsor',
540
- amount: -1, //Get amount from lazy processing
541
- from: txOptions.gasSponsor.sponsorAddress,
542
- to: await this.getAddress(txOptions),
543
- token: 'eth',
544
- txid: receipt.txId,
545
- }, paymasterType, txOptions.gasSponsor.sponsorAddress);
546
- }
547
- }
548
- return receipt;
549
- }
550
- /**
551
- * Schedules an operation for execution and returns the scheduled operation's ID.
552
- * @param {Auth} auth - The authentication instance for the user.
553
- * @param {Operation} operation - The operation to be scheduled.
554
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
555
- * @returns {Promise<Hex>} The ID of the scheduled operation.
556
- */
557
- async scheduleOperation(auth, operation, txOptions = globalThis.globalEnvOption) {
558
- txOptions = parseOptions(txOptions);
559
- operation = Operation.convertTypeToObject(operation);
560
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
561
- const chainId = await chain.getChainId();
562
- if (txOptions.skipDBAction !== true) {
563
- // cache group info
564
- if (isGroupOperation(operation)) {
565
- const groups = await getGroups([operation.groupId], chainId);
566
- if (groups && groups.length > 0) {
567
- // could be empty as a new wallet wants to create a group
568
- this.userInfo?.set(operation.groupId, {
569
- userId: operation.groupId,
570
- groupInfo: {
571
- threshold: groups[0].threshold,
572
- memberIds: groups[0].memberIds,
573
- },
574
- });
575
- }
576
- }
577
- }
578
- const threshold = this.userInfo?.get(operation.groupId)?.groupInfo?.threshold ?? 1;
579
- if (threshold <= 1) {
580
- if (!operation.userOp.signature || operation.userOp.signature === '0x') {
581
- operation.userOp.signature = await auth.signOp(operation, chain, isGroupOperation(operation));
582
- }
583
- }
584
- else {
585
- if (txOptions.skipDBAction !== true) {
586
- // check remote collected signature
587
- const storedOps = await getOps([operation.opId], chainId);
588
- let collectedSigCount;
589
- if (isSignatureMissing(await auth.getUserId(), storedOps[0]?.signatures)) {
590
- collectedSigCount = storedOps[0]?.signatures?.length
591
- ? storedOps[0]?.signatures?.length + 1
592
- : 1;
593
- if (collectedSigCount >= threshold) {
594
- operation.userOp.signature = await auth.signOp(operation, chain, isGroupOperation(operation));
595
- }
596
- }
597
- else {
598
- collectedSigCount = storedOps[0]?.signatures?.length ?? 1;
599
- }
600
- if (collectedSigCount < threshold) {
601
- throw new InvalidParameterError(ErrorCode.InsufficientSignatures, 'Signatures are not sufficient to execute the operation', { threshold, collectedSigCount, chainId }, 'Only execute operation with enough signatures', 'https://docs.fun.xyz/how-to-guides/execute-transactions#execute-transactions');
602
- }
603
- }
604
- else {
605
- throw new InvalidParameterError(ErrorCode.InsufficientSignatures, 'Signatures are not sufficient to execute the operation', { threshold, chainId, skipDBAction: txOptions.skipDBAction }, 'Only execute operation with enough signatures', 'https://docs.fun.xyz/how-to-guides/execute-transactions#execute-transactions');
606
- }
607
- }
608
- if (isGroupOperation(operation)) {
609
- await scheduleOp({
610
- opId: operation.opId,
611
- chainId,
612
- scheduledBy: await auth.getAddress(),
613
- entryPointAddress: await chain.getAddress('entryPointAddress'),
614
- signature: operation.userOp.signature,
615
- groupInfo: this.userInfo?.get(operation.groupId)?.groupInfo,
616
- });
617
- }
618
- else {
619
- await scheduleOp({
620
- opId: operation.opId,
621
- chainId,
622
- scheduledBy: await auth.getAddress(),
623
- entryPointAddress: await chain.getAddress('entryPointAddress'),
624
- signature: operation.userOp.signature,
625
- userOp: operation.userOp,
626
- });
627
- }
628
- if (!operation.opId) {
629
- throw new InternalFailureError(ErrorCode.ServerFailure, 'Operation id is required', operation, 'Make sure you are scheduling a valid operation', 'https://docs.fun.xyz/');
630
- }
631
- return operation.opId;
632
- }
633
- /**
634
- * Removes an operation from the system using its ID.
635
- * @param {Auth} _ - The authentication instance (not used in this method).
636
- * @param {Hex} operationId - The ID of the operation to be removed.
637
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
638
- * @returns {Promise<void>} A promise that resolves after the operation is removed.
639
- */
640
- async removeOperation(_, operationId, txOptions = globalThis.globalEnvOption) {
641
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
642
- await deleteOp(operationId, await chain.getChainId());
643
- }
644
- /**
645
- * Creates and prepares a rejection operation for an existing operation.
646
- * @param {Auth} auth - The authentication instance for the user.
647
- * @param {string} groupId - The ID of the group to which the operation belongs.
648
- * @param {Operation} operation - The operation to be rejected.
649
- * @param {string} rejectionMessage - Optional rejection message.
650
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
651
- * @returns {Promise<Operation>} The prepared rejection operation.
652
- */
653
- async createRejectOperation(auth, groupId, operation, rejectionMessage, txOptions = globalThis.globalEnvOption) {
654
- const rejectOperation = await this.transfer(auth, groupId, { to: await this.getAddress(txOptions), amount: 0, token: 'eth' }, {
655
- ...txOptions,
656
- skipDBAction: true,
657
- nonce: BigInt(operation.userOp.nonce),
658
- });
659
- if (rejectionMessage)
660
- rejectOperation.message = rejectionMessage;
661
- rejectOperation.relatedOpIds = [operation.opId];
662
- rejectOperation.opType = OperationType.REJECTION;
663
- rejectOperation.opId = (await createOp(rejectOperation));
664
- return rejectOperation;
665
- }
666
- /**
667
- * Estimates the gas cost for executing an operation and returns the updated operation with gas estimation details.
668
- * @param {Auth} auth - The authentication instance for the user.
669
- * @param {string} userId - The ID of the user initiating the operation.
670
- * @param {Operation} operation - The operation for which to estimate gas.
671
- * @param {EnvOption} txOptions - Transaction environment options (default: global environment options).
672
- * @returns {Promise<Operation>} The updated operation with gas estimation details.
673
- */
674
- async estimateOperation(auth, userId, operation, txOptions = globalThis.globalEnvOption) {
675
- const chain = await Chain.getChain({ chainIdentifier: txOptions.chain });
676
- const estimateGasSignature = await auth.getEstimateGasSignature(userId, operation);
677
- operation.userOp.signature = estimateGasSignature.toLowerCase();
678
- const estimationPaymasterAddress = await chain.getAddress('estimationPaymasterAddress');
679
- const paymasterAndData = operation.userOp.paymasterAndData;
680
- const res = await chain.estimateOpGas({
681
- ...operation.userOp,
682
- paymasterAndData: estimationPaymasterAddress,
683
- });
684
- operation.userOp = {
685
- ...operation.userOp,
686
- ...res,
687
- paymasterAndData,
688
- };
689
- const { maxFeePerGas, maxPriorityFeePerGas } = await chain.getFeeData();
690
- operation.userOp.maxFeePerGas = maxFeePerGas;
691
- operation.userOp.maxPriorityFeePerGas = maxPriorityFeePerGas;
692
- return operation;
693
- }
694
- async getThisInitCode(chain) {
695
- const owners = Array.from(this.userInfo.keys());
696
- const entryPointAddress = await chain.getAddress('entryPointAddress');
697
- const factoryAddress = await chain.getAddress('factoryAddress');
698
- const rbac = await chain.getAddress('rbacAddress');
699
- const userAuth = await chain.getAddress('userAuthAddress');
700
- const loginData = {
701
- salt: this.walletUniqueId,
702
- };
703
- const rbacInitData = toBytes32Arr(owners);
704
- let userAuthInitData = '0x';
705
- const groupUsers = Array.from(this.userInfo.values()).filter((user) => user.groupInfo !== null && user.groupInfo !== undefined);
706
- if (groupUsers.length > 0) {
707
- userAuthInitData = encodeUserAuthInitData(groupUsers);
708
- }
709
- const initCodeParams = {
710
- entryPointAddress,
711
- factoryAddress,
712
- implementationAddress: AddressZero,
713
- loginData,
714
- verificationAddresses: [rbac, userAuth],
715
- verificationData: [rbacInitData, userAuthInitData],
716
- };
717
- return this.getInitCode(initCodeParams);
718
- }
719
- getInitCode(input) {
720
- const encodedVerificationInitdata = encodeAbiParameters([
721
- {
722
- type: 'address[]',
723
- name: 'verificationAddresses',
724
- },
725
- {
726
- type: 'bytes[]',
727
- name: 'verificationData',
728
- },
729
- ], [input.verificationAddresses, input.verificationData]);
730
- const initializerCallData = WALLET_CONTRACT_INTERFACE.encodeData('initialize', [input.entryPointAddress, encodedVerificationInitdata]);
731
- const data = FACTORY_CONTRACT_INTERFACE.encodeData('createAccount', [
732
- initializerCallData,
733
- encodeLoginData(input.loginData),
734
- ]);
735
- return concat([input.factoryAddress, data]);
736
- }
737
- /**
738
- * Encodes arbitrary transactions calls to include fees
739
- * @param params Transaction Params, generated from various calldata generating functions
740
- * @param options EnvOptions to read fee data from
741
- * @returns calldata to be passed into createUserOperation
742
- */
743
- async buildCalldata(auth, userId, params, options) {
744
- if (!params.value) {
745
- params.value = 0n;
746
- }
747
- if (options.fee) {
748
- if (!options.fee.token &&
749
- options.gasSponsor &&
750
- options.gasSponsor.token) {
751
- options.fee.token = options.gasSponsor.token;
752
- }
753
- if (!options.fee.token) {
754
- throw new InvalidParameterError(ErrorCode.MissingParameter, 'EnvOption.fee.token or EnvOption.gasSponsor.token is required', { options }, 'Provide EnvOption.fee.token or EnvOption.gasSponsor.token when calling wallet.createOperation', 'https://docs.fun.xyz/how-to-guides/execute-transactions#execute-transactions');
755
- }
756
- if (!options.fee.recipient) {
757
- throw new InvalidParameterError(ErrorCode.MissingParameter, 'EnvOption.fee.recipient is required', { options }, 'Provide EnvOption.fee.recipient when calling wallet.createOperation', 'https://docs.fun.xyz/how-to-guides/execute-transactions#execute-transactions');
758
- }
759
- const chain = await Chain.getChain({ chainIdentifier: options.chain });
760
- const token = new Token(options.fee.token, chain);
761
- if (options.fee.gasPercent && !token.isNative) {
762
- throw new InvalidParameterError(ErrorCode.InvalidParameterCombination, 'GasPercent is only valid for native tokens', { options }, 'Use native token as the fee token if you want to charge fee based on percentage', 'https://docs.fun.xyz/how-to-guides/configure-environment/set-developer-fee');
763
- }
764
- if (token.isNative) {
765
- options.fee.token = AddressZero;
766
- }
767
- else {
768
- options.fee.token = await token.getAddress();
769
- }
770
- if (options.fee.amount) {
771
- options.fee.amount = Number(await token.getDecimalAmount(options.fee.amount));
772
- }
773
- else if (options.fee.gasPercent) {
774
- const feedata = [options.fee.token, options.fee.recipient, 1];
775
- const estimateGasCalldata = WALLET_CONTRACT_INTERFACE.encodeData('execFromEntryPointWithFee', [params.to, params.value, params.data, feedata]);
776
- const operation = await this.createOperation(auth, userId, { to: params.to, value: params.value, data: estimateGasCalldata }, { ...options, fee: undefined });
777
- const gasUsed = await operation.getMaxTxCost();
778
- options.fee.amount = Math.ceil((Number(gasUsed) * options.fee.gasPercent) / 100);
779
- }
780
- else {
781
- throw new InvalidParameterError(ErrorCode.MissingParameter, 'EnvOption.fee.amount or EnvOption.fee.gasPercent is required', { options }, 'Provide either EnvOption.fee.amount or EnvOption.fee.gasPercent when calling wallet.createOperation', 'https://docs.fun.xyz/how-to-guides/configure-environment/set-developer-fee');
782
- }
783
- const feedata = [
784
- options.fee.token,
785
- options.fee.recipient,
786
- options.fee.amount,
787
- ];
788
- return WALLET_CONTRACT_INTERFACE.encodeData('execFromEntryPointWithFee', [
789
- params.to,
790
- params.value,
791
- params.data,
792
- feedata,
793
- ]);
794
- }
795
- else {
796
- return WALLET_CONTRACT_INTERFACE.encodeData('execFromEntryPoint', [
797
- params.to,
798
- params.value,
799
- params.data,
800
- ]);
801
- }
802
- }
803
- }
804
- //# sourceMappingURL=FunWallet.js.map