@hinkal/common 0.2.23 → 0.2.25

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/README.md CHANGED
@@ -5,11 +5,17 @@ Hinkal is a privacy middleware and smart-contract SDK for public blockchains tha
5
5
  The SDK allows wallets, dApps, and payment platforms to integrate protocol-level privacy on Ethereum, Solana, Polygon, Base, Arbitrum, and Optimis. It hides transaction history, wallet relationships, and asset flows on-chain while preserving public-chain finality and compliance.
6
6
 
7
7
  With Hinkal SDK, developers can:
8
- Enable private sends between public wallets
9
- Perform confidential payouts and settlements
10
- Route transactions through Hinkal’s privacy contracts without exposing sender, recipient, or amounts
11
- Maintain non-custodial control with optional compliance visibility via viewing keys
8
+ Enable private sends between public wallets
9
+ Perform confidential payouts and settlements
10
+ Route transactions through Hinkal’s privacy contracts without exposing sender, recipient, or amounts
11
+ Maintain non-custodial control with optional compliance visibility via viewing keys
12
12
 
13
+ ## Compatibility
14
+
15
+ | Environment | Supported | Notes |
16
+ | ----------- | --------- | -------------------------- |
17
+ | Node.js | ✅ | v18+ |
18
+ | Browser | ✅ | React, Next.js, vanilla JS |
13
19
 
14
20
  ## Installation
15
21
 
@@ -25,18 +31,24 @@ Or, yarn:
25
31
  yarn add @hinkal/common
26
32
  ```
27
33
 
28
- ### Usage
34
+ ## Usage
35
+
36
+ ### Initialization
37
+
38
+ To begin using Hinkal in your application, you'll need to initialize the SDK with your preferred Web3 connection library. Hinkal supports multiple popular libraries out of the box, allowing seamless integration with your existing wallet connection setup.
29
39
 
30
- #### Initialization
40
+ Initializing the SDK creates a `Hinkal` object that encapsulates:
31
41
 
32
- To get started with Hinkal, initialize it based on the Web3 connection library you’re using:
42
+ - The user's shielded balances
43
+ - Actions the user can perform, such as shielding (depositing), transfers, and swapping
44
+ - Cryptographic keys for privacy-preserving operations
33
45
 
34
46
  **ethers.js:**
35
47
 
36
48
  ```typescript
37
49
  import { prepareEthersHinkal } from '@hinkal/common/providers/prepareEthersHinkal';
38
50
  // signer: ethers.Signer
39
- const hinkal = await prepareEthersHinkal(signer);
51
+ const hinkal = await prepareEthersHinkal(signer, hinkalConfig);
40
52
  ```
41
53
 
42
54
  **wagmi:**
@@ -44,128 +56,320 @@ const hinkal = await prepareEthersHinkal(signer);
44
56
  ```typescript
45
57
  import { prepareWagmiHinkal } from '@hinkal/common/providers/prepareWagmiHinkal';
46
58
  // connector: wagmi.Connector
47
- // config: wagmi.Config
48
- const hinkal = await prepareWagmiHinkal(connector, config);
59
+ // wagmiConfig: wagmi.Config
60
+ const hinkal = await prepareWagmiHinkal(connector, wagmiConfig, hinkalConfig);
61
+ ```
62
+
63
+ The `hinkalConfig` is defined as follows:
64
+
65
+ ```typescript
66
+ type HinkalConfig = {
67
+ /** Disables caching in browser localStorage, storing data only in memory. Front-end only. Defaults to false. */
68
+ disableCaching?: boolean;
69
+
70
+ /** If true, allows caching in a file locally. Node.js only. Defaults to false. */
71
+ useFileCache?: boolean;
72
+
73
+ /**
74
+ * Path to the cache file used for storing temporary data. Node.js only.
75
+ * It should be a valid file path string. Defaults to hinkalCache.json in the current working directory.
76
+ */
77
+ cacheFilePath?: string;
78
+
79
+ /**
80
+ * Indicator controlling wether the proof should be constructed remotely in secure enclave. Defaults to true.
81
+ */
82
+ generateProofRemotely?: boolean;
83
+ };
49
84
  ```
50
85
 
51
- #### Shielded balance
86
+ ### Shielded balance
52
87
 
53
- Once the Hinkal object is initialized, shielded balances become accessible and can be calculated as needed:
88
+ Shielded balances are encrypted token holdings stored within the Hinkal protocol. Unlike regular blockchain balances that are publicly visible, shielded balances are hidden from external observers, providing privacy for your assets. After initializing the Hinkal object, you can access and calculate your shielded balances:
54
89
 
55
90
  ```typescript
56
- const balances = await hinkal.getBalances();
91
+ const balances: Promise<Map<string, TokenBalance>> = await hinkal.getBalances();
57
92
  ```
58
93
 
59
- #### Depositing funds to the shielded balance
94
+ This returns a map from token address to balance for all tokens held by the user, including ERC20 and ERC721 tokens.
95
+
96
+ ### Shielding: depositing funds to the shielded balance
97
+
98
+ Shielding is the process of moving your tokens from a public blockchain address into a private, encrypted balance. Once shielded, your tokens are no longer visible on-chain to external observers. This provides privacy for your holdings and subsequent transactions.
60
99
 
61
100
  A user can deposit funds to their shielded address using:
62
101
 
63
102
  ```typescript
64
- function deposit(erc20addresses: string[], amountChanges: bigint[]): Promise<TransactionObject>;
103
+ function deposit(erc20Tokens: ERC20Token[], amountChanges: bigint[]): Promise<ethers.providers.TransactionResponse>;
65
104
  ```
66
105
 
67
- where erc20Addresses is an array of token addresses, and amountChanges represents the token amounts for the deposit.
106
+ where:
68
107
 
69
- #### Interacting with smart contracts privately
108
+ - `erc20Tokens` is an array of tokens to deposit
109
+ - `amountChanges` represents the corresponding token amounts for the deposit
70
110
 
71
- After a user’s shielded balance is updated, they can perform any smart contract interaction privately using:
111
+ The `ERC20Token` type is defined as follows:
112
+
113
+ ```typescript
114
+ type ERC20Token = {
115
+ chainId: number;
116
+ erc20TokenAddress: string;
117
+ name: string;
118
+ symbol: string;
119
+ decimals: number;
120
+ };
121
+ ```
122
+
123
+ ### Private Send to Public Address: withdrawing funds from the shielded balance
124
+
125
+ Private Send to Public Address allows you to send tokens from your private, shielded balance directly to any public blockchain address. The sender's identity is not exposed during this transaction. The recipient receives the funds at their public address, where the tokens become visible on-chain. This is useful when you need to interact with public DeFi protocols, send funds to exchanges, or transfer to any public wallet while maintaining privacy for your shielded balance.
126
+
127
+ A user can withdraw funds from their shielded address to a public address using:
128
+
129
+ ```typescript
130
+ function withdraw(
131
+ erc20Tokens: ERC20Token[],
132
+ deltaAmounts: bigint[],
133
+ recipientAddress: string,
134
+ isRelayerOff: boolean,
135
+ ): Promise<string>;
136
+ ```
137
+
138
+ where:
139
+
140
+ - `recipientAddress` is the public address that will receive the withdrawn funds
141
+ - `isRelayerOff` determines whether to use a relayer for the transaction (when `false`, a relayer handles gas fees; when `true`, the user pays gas directly)
142
+ - `string` type represents the transaction response from the relayer service.
143
+
144
+ ### Private Send to Private Address: transfering funds from shielded balance
145
+
146
+ Private Send to Private Address enables fully confidential transfers between shielded balances. Both the sender and recipient remain anonymous, and the transaction amount is hidden from external observers. This is the most private way to transfer tokens, as neither party's identity nor the transaction details are exposed on-chain.
147
+
148
+ A user can transfer tokens from their shielded balance to another shielded address using:
149
+
150
+ ```typescript
151
+ function transfer(erc20Tokens: ERC20Token[], deltaAmounts: bigint[], privateRecipientAddress: string): Promise<string>;
152
+ ```
153
+
154
+ where:
155
+
156
+ - `privateRecipientAddress` is the recipient's private address, formatted as a comma-separated string with five components:
157
+ - `randomization` - a random value for privacy
158
+ - `stealthAddress` - the recipient's stealth address (hex format starting with `0x`)
159
+ - `encryptionKey` - the recipient's encryption key (hex format starting with `0x`, 66 characters)
160
+ - `H0` - the first hash component of elliptic curve point for stealth address derivation
161
+ - `H1` - the second hash component of elliptic curve point for stealth address derivation
162
+
163
+ ### Private Send from Public to Public addresses
164
+
165
+ Private Send from Public to Public addresses enables you to transfer tokens between two public addresses while using Hinkal's privacy infrastructure. The tokens are first shielded from the sender's public address, then unshielded to the recipient's public address either immediately or after some interval. This ensures there is no traceable connection between the sender and recipient on-chain, providing transaction privacy even when both parties use public addresses.
166
+
167
+ A user can perform a private transfer between public addresses using:
168
+
169
+ ```typescript
170
+ function depositAndWithdraw(
171
+ erc20Token: ERC20Token,
172
+ recipientAmounts: bigint[],
173
+ recipientAddresses: string[],
174
+ txCompletionTime?: number,
175
+ ): Promise<string>;
176
+ ```
177
+
178
+ where:
179
+
180
+ - `erc20Token` is the token to transfer (only single token transfers are supported for this method)
181
+ - `recipientAmounts` is an array of amounts to send to each recipient (in the token's smallest unit)
182
+ - `recipientAddresses` is an array of public addresses that will receive the funds
183
+ - `txCompletionTime` (optional) specifies a delay in milliseconds before the withdrawal completes
184
+
185
+ ### Swapping tokens from the shielded balance
186
+
187
+ Swapping allows you to exchange tokens directly from your shielded balance without revealing your identity. The swap is executed through integrated DEX protocols (Uniswap, 1Inch, Odos) while keeping your transaction private. Your tokens are withdrawn from your shielded balance, swapped through the specified protocol, and the resulting tokens are deposited back into your shielded balance—all in a single private transaction.
188
+
189
+ A user can swap tokens directly from their shielded balance using:
190
+
191
+ ```typescript
192
+ function swap(
193
+ erc20Tokens: ERC20Token[],
194
+ deltaAmounts: bigint[],
195
+ externalActionId: ExternalActionId,
196
+ swapData: string,
197
+ ): Promise<string>;
198
+ ```
199
+
200
+ where:
201
+
202
+ - `externalActionId` identifies the external swap protocol to use. Possible values include:
203
+ - `ExternalActionId.Uniswap` - for Uniswap swaps
204
+ - `ExternalActionId.OneInch` - for 1Inch swaps
205
+ - `ExternalActionId.Odos` - for Odos swaps
206
+ - `swapData` contains the encoded swap parameters specific to the chosen protocol
207
+
208
+ **Getting swap calldata:**
209
+
210
+ To obtain the swap calldata using the Hinkal SDK, you can use the built-in swap data generation utilities.
211
+
212
+ To get swap data for 1Inch, you can use the `getOneInchPrice` function. This function fetches a quote from the 1Inch aggregator and returns both the expected output amount and the encoded swap data that can be passed to the `swap` function:
213
+
214
+ **1Inch:**
215
+
216
+ ```typescript
217
+ function getOneInchPrice(
218
+ chainId: number,
219
+ inSwapToken: ERC20Token,
220
+ outSwapToken: ERC20Token,
221
+ inSwapAmount: string,
222
+ slippagePercentage?: number,
223
+ ): Promise<{
224
+ outSwapAmountValue: bigint;
225
+ oneInchDataValue: string;
226
+ }>;
227
+ ```
228
+
229
+ Similar functions are available for other supported swap protocols:
230
+
231
+ - **Uniswap:** `getUniswapPrice`
232
+ - **Odos:** `getOdosPrice`
233
+ - **LiFi:** `getLifiPrice`
234
+
235
+ ### Interacting with smart contracts privately
236
+
237
+ The SDK lets you interact with any smart contract on the blockchain while keeping your identity private. When you initiate a private wallet action, your funds are first unshielded from your Hinkal shielded balance to an intermediary called an Emporium contract. The Emporium then executes your desired actions on-chain (such as swaps, staking, or other DeFi interactions) without exposing who initiated them. After the operations complete, the resulting tokens are automatically shielded back into your Hinkal shielded balance. This means you can use DeFi protocols, NFT marketplaces, or any other smart contract while maintaining full anonymity.
72
238
 
73
239
  ```typescript
74
240
  function actionPrivateWallet(
75
- erc20Addresses: string[],
76
- amountChanges: bigint[],
241
+ chainId: number,
242
+ erc20Tokens: ERC20Token[],
243
+ deltaAmounts: bigint[],
77
244
  onChainCreation: boolean[],
78
245
  ops: string[],
79
- ): Promise<TransactionObject>;
246
+ ): Promise<string>;
80
247
  ```
81
248
 
82
- where onChainCreation indicates the amounts of tokens that are uncertain before the transaction is executed on-chain. The ops array contains encoded user operations.
249
+ Parameters:
83
250
 
84
- ##### User operations
251
+ - `chainId` - the blockchain network identifier
252
+ - `onChainCreation` - array of booleans indicating the direction of token changes: `true` for positive changes (tokens received), `false` for negative changes (tokens spent)
253
+ - `ops` - array of encoded user operations to execute (see User operations below)
254
+
255
+ User operations (`ops`) are encoded instructions that tell the Emporium contract what actions to perform. Each operation specifies a target contract, the function to call, and any necessary parameters. For example, to stake ETH with Lido, you would create an operation that calls Lido's `submit` function with the appropriate value.
256
+
257
+ To generate user operations, a user will need the `emporiumOp` function.
85
258
 
86
- To generate user operations (`ops`) you will need the `emporiumOp` function.
87
259
  ```typescript
88
- import {emporiumOp} from "@hinkal/common";
260
+ function emporiumOp(
261
+ contract: ethers.Contract | string;
262
+ func?: string;
263
+ args?: any[];
264
+ callDataString?: string;
265
+ invokeWallet?: boolean;
266
+ value?: bigint;
267
+ ): Promise<string>;
89
268
  ```
90
269
 
91
270
  The function accepts the following arguments:
92
- 1. `endpoint` *(required)* - target address or contract instance (with address). The contract instance will be used to properly encode the call function, if any, in the custom operation.
93
- 2. `func` *(optional)* - the name of the function to be called on the target address.
94
- 3. `args` *(optional)* - arguments of the function to be called on the target address.
95
- 4. `invokeWallet` *(optional)* - bool flag that determines the type of transaction. There are two types: stateful and stateless interaction. The default is false (stateless).
96
- 5. `value` *(optional)* - the amount of native currency to transfer to the target address.
97
271
 
98
- The `emporiumOp` function will generate data for subsequent calls, supporting both stateful interaction (with state preservation) and stateless interaction (without state preservation). This is determined by the `invokeWallet` flag.
272
+ 1. `contract` _(required)_ - target address or contract instance (with address). The contract instance will be used to properly encode the call function, if any, in the custom operation.
273
+ 2. `func` _(optional)_ - the name of the function to be called on the target address.
274
+ 3. `args` _(optional)_ - arguments of the function to be called on the target address.
275
+ 4. `callDataString` _(optional)_ - pre-encoded calldata string. If provided, `func` and `args` should not be used.
276
+ 5. `invokeWallet` _(optional)_ - boolean flag that determines the type of interaction (see the stateless/stateful interactions below).
277
+ 6. `value` _(optional)_ - the value field to the user operation call.
278
+
279
+ When the Emporium contract executes a user operation, it receives the data in this format:
99
280
 
100
- To execute on a smart contract, the user operation will be received in the following format:
101
281
  ```solidity
102
282
  (address endpoint, bool invokeWallet, uint256 value, bytes data)
103
283
  ```
104
284
 
105
- This will make it possible to make that kind of call:
285
+ This enables the Emporium contract to execute generic calls using user operations:
286
+
106
287
  ```solidity
107
288
  (bool success, bytes memory err) = endpoint.call{value: value}(data);
108
289
  ```
109
290
 
110
- ##### Stateless and stateful
111
-
112
- The best way to demonstrate how this works is with an example.
291
+ User operations can be categorized into two types based on whether the target protocol needs to track the caller account's history:
113
292
 
114
- **Stateless interaction**
293
+ **Stateless interactions** are operations where the resulting token amount changes depend only on the calldata provided. Two different accounts executing the same calldata should receive the same result, regardless of their transaction history. Examples include token swaps, liquidity provision, and simple staking operations.
115
294
 
116
- Let's say we need to exchange USDC for ETH using DEX.
295
+ For example, consider exchanging USDC for ETH using a DEX. To perform a swap, the DEX does not need to know historical data about the caller (e.g., when and what swaps have been performed from his account in the past). It only needs to know how much token to swap and the exchange rate.
117
296
 
118
297
  ```typescript
119
298
  const operations = [
120
- emporiumOp(usdcContractInstance, 'approve', [swapRouterAddress, amountIn]),
121
- emporiumOp(swapRouterContractInstance, 'exactInputSingle', [swapSingleParams]),
122
- emporiumOp(wethContractInstance, 'withdraw', [amountOut]),
299
+ emporiumOp({ contract: usdcContractInstance, func: 'approve', args: [swapRouterAddress, amountIn] }),
300
+ emporiumOp({ contract: swapRouterContractInstance, func: 'exactInputSingle', args: [swapSingleParams] }),
301
+ emporiumOp({ contract: wethContractInstance, func: 'withdraw', args: [amountOut] }),
123
302
  ];
124
303
  ```
125
304
 
126
- To perform a DEX swap, DEX does not need to know historical data about the calling party (e.g. when and what swaps have been performed from this account in the past). It only needs the current token balance for the exchange.
305
+ In this example:
127
306
 
128
- In this case it will be **stateless interaction**, so there is no need to change the default value of the `invokeWallet` flag.
307
+ - First operation approves the swap router to spend USDC tokens
308
+ - Second operation executes the swap from USDC to WETH
309
+ - Third operation unwraps WETH to ETH
129
310
 
130
- **Stateful interaction**
311
+ **Stateful interactions** are operations where the target protocol needs to track the account's history for future calculations, such as staking rewards, voting power, or checkpoints. In these cases, set `invokeWallet: true` to ensure the operation is executed from a persistent wallet address that the protocol can track.
131
312
 
132
- Another example is when the protocol with which an account interacts needs to know what actions this account has done before, for example, to gain rewards. In this case, some account state will be required.
313
+ Consider a scenario where you have already staked Curve LP tokens and want to claim your rewards. The gauge contract needs to track your staking history to calculate accumulated rewards, so it must recognize the same wallet address across multiple interactions.
133
314
 
134
- Let's imagine that you already have Curve LP tokens and need to make a stake.
135
-
136
- ```solidity
315
+ ```typescript
137
316
  const operations = [
138
- emporiumOp(lpTokenInstance, 'approve', [gaugeAddressInstance, amount]), // without flag, because is's stateless interaction
139
- emporiumOp(gaugeAddressInstance, 'deposit', [amount, invokeWalletAddress], true), // with flag, because it's stateful interaction
317
+ emporiumOp({ contract: lpTokenInstance, func: 'approve', args: [gaugeAddressInstance, amount], invokeWallet: true }),
318
+ emporiumOp({
319
+ contract: gaugeAddressInstance,
320
+ func: 'deposit',
321
+ args: [amount, invokeWalletAddress],
322
+ invokeWallet: true,
323
+ }),
140
324
  ];
141
325
  ```
142
326
 
143
- As you can see, in this case `approve` is a stateless interaction, but `deposit` is a stateful interaction, because under the hood Curve will record this address and timestamp in order to calculate the checkpoint correctly in the future.
327
+ In this example:
328
+
329
+ - First operation approves the gauge contract to spend LP tokens, executed from the persistent wallet
330
+ - Second operation deposits LP tokens into the gauge, with the wallet address as the recipient for reward tracking
144
331
 
145
- ### Access Tokens
332
+ ## Access Tokens
146
333
 
147
- Before interacting with Hinkal smart contracts, users need to mint an access token after passing compliance checks.
334
+ Access tokens are required credentials that allow users to interact with Hinkal's privacy smart contracts. Think of them as a "passport" that proves you've completed the necessary compliance verification.
148
335
 
149
- To check whether a user already has an access token, use the checkAccessToken function:
336
+ Before you can deposit funds, make transfers, or perform any private transactions through Hinkal, you must have a valid access token associated with your wallet. This is a one-time requirement—once you have an access token, you can use Hinkal's features without needing to verify again.
337
+
338
+ To check whether a user already has an access token on a specific chain, use the `checkAccessToken` function:
150
339
 
151
340
  ```typescript
152
341
  function checkAccessToken(): Promise<boolean>;
153
342
  ```
154
343
 
155
- If the user does not have an access token, they must use one of the compliance providers to pass the check. To view the available providers:
344
+ If the user does not have an access token, they need to complete a compliance verification through one of Hinkal's supported compliance providers. This is a one-time process that verifies the user meets regulatory requirements before they can use the privacy features.
345
+
346
+ To get a list of all available compliance providers that can be used for verification:
156
347
 
157
348
  ```typescript
158
349
  function getSupportedPassportLinks(): string[];
159
350
  ```
160
351
 
161
- After passing the compliance check, the user can mint an access token using:
352
+ After passing the compliance check with one of the supported providers, the access token will be automatically minted during the user's first transaction with Hinkal. This token is stored on-chain and grants the user permission to interact with Hinkal's privacy contracts.
162
353
 
163
- ```typescript
164
- const { signatureData } = await hinkal.getAPI().getAccessTokenSignature(chainId, ethereumAddress, accessKey);
165
- await mintAccessToken(this, signatureData);
166
- ```
354
+ ## Supported Chains
355
+
356
+ Hinkal SDK is available on the following blockchain networks:
357
+
358
+ | Chain | Chain ID | Status |
359
+ | -------- | -------- | -------------- |
360
+ | Ethereum | 1 | ✅ Live |
361
+ | Polygon | 137 | ✅ Live |
362
+ | Base | 8453 | ✅ Live |
363
+ | Arbitrum | 42161 | ✅ Live |
364
+ | Optimism | 10 | ✅ Live |
365
+ | Solana | - | 🚧 In Progress |
366
+
367
+ Each chain supports the full suite of Hinkal privacy features including shielding, transfers, and confidential interactions with DeFi protocols.
368
+
369
+ ## References
370
+
371
+ Wallet: [Hinkal Wallet](https://chromewebstore.google.com/detail/hinkal-wallet/khfjgapjfcdoffmklchibpepboholpbe)
167
372
 
168
- ### References
373
+ Application: [Private Send](https://send.hinkal.io)
169
374
 
170
- Application: [Hinkal](https://app.hinkal.pro)
171
- Docs: [Hinkal Documentation](https://hinkal-team.gitbook.io/hinkal)
375
+ Docs: [Hinkal Documentation](https://hinkal-team.gitbook.io/hinkal)
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("../../constants/protocol.constants.cjs"),F=require("../../error-handling/error-codes.constants.cjs"),O=require("../../functions/snarkjs/constructGeneralZkProof.cjs"),K=require("../../functions/web3/functionCalls/transactCallRelayer.cjs"),L=require("../../types/external-action.types.cjs"),z=require("../utxo/Utxo.cjs");require("../../types/circom-data.types.cjs");const B=require("../../types/ethereum-network.types.cjs"),N=require("../../types/admin.types.cjs");require("../../types/activities.types.cjs");const D=require("../../types/scheduled-transactions.types.cjs"),Z=require("../../functions/pre-transaction/getSignatureDataForTransact.cjs"),j=require("../../functions/pre-transaction/shouldPatchAccessTokenMerkleTree.cjs"),G=require("../../functions/utils/time.utils.cjs"),V=require("../../functions/pre-transaction/getFeeStructure.cjs"),Y=require("../../functions/utils/addresses.cjs"),$=require("./hinkalDepositOnChainUtxos.cjs"),J=require("../../functions/pre-transaction/constructAdminData.cjs"),q=require("../../API/deposit-and-withdraw-status-calls.cjs"),Q=async(e,t,r,h,s,c,A,i)=>{if(r.length===0)throw new Error("userDepositedUtxos must not be empty");const a=t.erc20TokenAddress,n=await e.getRandomRelay();if(!n)throw Error(F.transactionErrorCodes.RELAYER_NOT_AVAILABLE);const o=await e.getEthereumAddress(),w=G.getCurrentTimeInSeconds().toString(),d=e.generateProofRemotely?5:1,p=[];for(let u=0;u<r.length;u+=d){const x=r.slice(u,u+d),S=await Promise.all(x.map(async({recipientAddress:I,utxo:l})=>{const E=[-l.amount],y=new z.Utxo({amount:0n,erc20TokenAddress:a,shieldedPrivateKey:e.userKeys.getShieldedPrivateKey(),timeStamp:w,tokenId:0}),T=[[l,y]],R=[[y]],P=`swapperM1x${T[0].length}x1`,m={externalActionId:0n,externalAddress:I,externalActionMetadata:"0x00"},{patchAccessTokenMerkleTree:_,kycRequired:f,hasAccessToken:U}=await j.shouldPatchAccessTokenMerkleTree(e,[a],E),W=await Z.getSignatureDataForTransact(e.getCurrentChainId(),o,e.userKeys,f,U),k=J.constructAdminData(N.AdminTransactionType.WithdrawOnChainUtxos,e.getCurrentChainId(),[a],[-l.amount],o),{zkCallData:v,circomData:H,dimData:M}=await O.constructZkProof("v1x1",e.merkleTreeHinkal,e.merkleTreeAccessToken,T,R,e.userKeys,P,m.externalActionId,m.externalAddress,m.externalActionMetadata,e.generateProofRemotely,n??b.zeroAddress,e.getCurrentChainId(),void 0,void 0,void 0,_,void 0,void 0,h,e.getContractWithFetcher(B.ContractType.HinkalHelperContract),W,void 0,!1);return{zkCallData:v,dimData:M,circomData:H,adminData:k}}));p.push(...S)}const C=e.getCurrentChainId();await q.safeUpdateDepositAndWithdrawStatus(C,{id:c,hashedEthereumAddress:s,phase:D.DepositAndWithdrawPhase.BEFORE_SCHEDULE_WITHDRAW});const g=await K.transactCallRelayerBatch(e.getCurrentChainId(),p,s,A,i);return await q.safeUpdateDepositAndWithdrawStatus(C,{id:c,hashedEthereumAddress:s,phase:D.DepositAndWithdrawPhase.AFTER_SCHEDULE_WITHDRAW,scheduleId:g}),g},X=async(e,t,r,h,s,c,A)=>{const i=t.erc20TokenAddress,a=e.getCurrentChainId(),n=Y.hashEthereumAddress(await e.getEthereumAddress()),o=c??await V.getFeeStructure(a,i,[i],L.ExternalActionId.Transact),{userDepositedUtxos:w,statusId:d}=await $.hinkalDepositOnChainUtxos(e,t,r,h,o,n);return Q(e,t,w,o,n,d,s,A)};exports.hinkalDepositAndWithdraw=X;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("../../constants/protocol.constants.cjs"),F=require("../../error-handling/error-codes.constants.cjs"),O=require("../../functions/snarkjs/constructGeneralZkProof.cjs"),K=require("../../functions/web3/functionCalls/transactCallRelayer.cjs"),L=require("../../types/external-action.types.cjs"),z=require("../utxo/Utxo.cjs");require("../../types/circom-data.types.cjs");const B=require("../../types/ethereum-network.types.cjs"),N=require("../../types/admin.types.cjs");require("../../types/activities.types.cjs");const D=require("../../types/scheduled-transactions.types.cjs"),Z=require("../../functions/pre-transaction/getSignatureDataForTransact.cjs"),j=require("../../functions/pre-transaction/shouldPatchAccessTokenMerkleTree.cjs"),G=require("../../functions/utils/time.utils.cjs"),V=require("../../functions/pre-transaction/getFeeStructure.cjs"),Y=require("../../functions/utils/addresses.cjs"),$=require("./hinkalDepositOnChainUtxos.cjs"),J=require("../../functions/pre-transaction/constructAdminData.cjs"),q=require("../../API/deposit-and-withdraw-status-calls.cjs"),Q=async(e,t,r,w,a,c,A,i)=>{if(r.length===0)throw new Error("userDepositedUtxos must not be empty");const s=t.erc20TokenAddress,n=await e.getRandomRelay();if(!n)throw Error(F.transactionErrorCodes.RELAYER_NOT_AVAILABLE);const o=await e.getEthereumAddress(),l=G.getCurrentTimeInSeconds().toString(),d=e.generateProofRemotely?5:1,u=[];for(let h=0;h<r.length;h+=d){const x=r.slice(h,h+d),S=await Promise.all(x.map(async({recipientAddress:I,utxo:p})=>{const E=[-p.amount],T=new z.Utxo({amount:0n,erc20TokenAddress:s,shieldedPrivateKey:e.userKeys.getShieldedPrivateKey(),timeStamp:l,tokenId:0}),y=[[p,T]],R=[[T]],P=`swapperM1x${y[0].length}x1`,m={externalActionId:0n,externalAddress:I,externalActionMetadata:"0x00"},{patchAccessTokenMerkleTree:_,kycRequired:f,hasAccessToken:U}=await j.shouldPatchAccessTokenMerkleTree(e,[s],E),W=await Z.getSignatureDataForTransact(e.getCurrentChainId(),o,e.userKeys,f,U),k=J.constructAdminData(N.AdminTransactionType.WithdrawOnChainUtxos,e.getCurrentChainId(),[s],[-p.amount],o),{zkCallData:v,circomData:H,dimData:M}=await O.constructZkProof("v1x1",e.merkleTreeHinkal,e.merkleTreeAccessToken,y,R,e.userKeys,P,m.externalActionId,m.externalAddress,m.externalActionMetadata,e.generateProofRemotely,n??b.zeroAddress,e.getCurrentChainId(),void 0,void 0,void 0,_,void 0,void 0,w,e.getContractWithFetcher(B.ContractType.HinkalHelperContract),W,void 0,!1);return{zkCallData:v,dimData:M,circomData:H,adminData:k}}));u.push(...S)}const C=e.getCurrentChainId();await q.safeUpdateDepositAndWithdrawStatus(C,{id:c,hashedEthereumAddress:a,phase:D.DepositAndWithdrawPhase.BEFORE_SCHEDULE_WITHDRAW});const g=await K.transactCallRelayerBatch(e.getCurrentChainId(),u,a,A,i);return await q.safeUpdateDepositAndWithdrawStatus(C,{id:c,hashedEthereumAddress:a,phase:D.DepositAndWithdrawPhase.AFTER_SCHEDULE_WITHDRAW,scheduleId:g}),g},X=async(e,t,r,w,a,c,A)=>{const i=t.erc20TokenAddress,s=e.getCurrentChainId(),n=Y.hashEthereumAddress(await e.getEthereumAddress()),o=c??await V.getFeeStructure(s,i,[i],L.ExternalActionId.Transact),{userDepositedUtxos:l,statusId:d,depositTxHash:u}=await $.hinkalDepositOnChainUtxos(e,t,r,w,o,n);return await Q(e,t,l,o,n,d,a,A),u};exports.hinkalDepositAndWithdraw=X;
@@ -17,36 +17,36 @@ import { hashEthereumAddress as j } from "../../functions/utils/addresses.mjs";
17
17
  import { hinkalDepositOnChainUtxos as G } from "./hinkalDepositOnChainUtxos.mjs";
18
18
  import { constructAdminData as J } from "../../functions/pre-transaction/constructAdminData.mjs";
19
19
  import { safeUpdateDepositAndWithdrawStatus as x } from "../../API/deposit-and-withdraw-status-calls.mjs";
20
- const Q = async (t, e, r, p, o, i, u, c) => {
20
+ const Q = async (t, e, r, u, o, i, w, c) => {
21
21
  if (r.length === 0)
22
22
  throw new Error("userDepositedUtxos must not be empty");
23
23
  const a = e.erc20TokenAddress, s = await t.getRandomRelay();
24
24
  if (!s)
25
25
  throw Error(F.RELAYER_NOT_AVAILABLE);
26
- const n = await t.getEthereumAddress(), w = Z().toString(), d = t.generateProofRemotely ? 5 : 1, f = [];
27
- for (let m = 0; m < r.length; m += d) {
28
- const I = r.slice(m, m + d), E = await Promise.all(
26
+ const n = await t.getEthereumAddress(), h = Z().toString(), d = t.generateProofRemotely ? 5 : 1, m = [];
27
+ for (let p = 0; p < r.length; p += d) {
28
+ const I = r.slice(p, p + d), E = await Promise.all(
29
29
  I.map(async ({ recipientAddress: D, utxo: A }) => {
30
30
  const R = [-A.amount], l = new B({
31
31
  amount: 0n,
32
32
  erc20TokenAddress: a,
33
33
  shieldedPrivateKey: t.userKeys.getShieldedPrivateKey(),
34
- timeStamp: w,
34
+ timeStamp: h,
35
35
  tokenId: 0
36
- }), T = [[A, l]], S = [[l]], v = `swapperM1x${T[0].length}x1`, h = {
36
+ }), T = [[A, l]], S = [[l]], v = `swapperM1x${T[0].length}x1`, f = {
37
37
  externalActionId: 0n,
38
38
  externalAddress: D,
39
39
  externalActionMetadata: "0x00"
40
40
  }, {
41
- patchAccessTokenMerkleTree: P,
42
- kycRequired: U,
43
- hasAccessToken: H
41
+ patchAccessTokenMerkleTree: H,
42
+ kycRequired: P,
43
+ hasAccessToken: U
44
44
  } = await Y(t, [a], R), W = await V(
45
45
  t.getCurrentChainId(),
46
46
  n,
47
47
  t.userKeys,
48
- U,
49
- H
48
+ P,
49
+ U
50
50
  ), K = J(
51
51
  N.WithdrawOnChainUtxos,
52
52
  t.getCurrentChainId(),
@@ -61,19 +61,19 @@ const Q = async (t, e, r, p, o, i, u, c) => {
61
61
  S,
62
62
  t.userKeys,
63
63
  v,
64
- h.externalActionId,
65
- h.externalAddress,
66
- h.externalActionMetadata,
64
+ f.externalActionId,
65
+ f.externalAddress,
66
+ f.externalActionMetadata,
67
67
  t.generateProofRemotely,
68
68
  s ?? k,
69
69
  t.getCurrentChainId(),
70
70
  void 0,
71
71
  void 0,
72
72
  void 0,
73
- P,
73
+ H,
74
74
  void 0,
75
75
  void 0,
76
- p,
76
+ u,
77
77
  t.getContractWithFetcher(q.HinkalHelperContract),
78
78
  W,
79
79
  void 0,
@@ -87,7 +87,7 @@ const Q = async (t, e, r, p, o, i, u, c) => {
87
87
  };
88
88
  })
89
89
  );
90
- f.push(...E);
90
+ m.push(...E);
91
91
  }
92
92
  const C = t.getCurrentChainId();
93
93
  await x(C, {
@@ -97,9 +97,9 @@ const Q = async (t, e, r, p, o, i, u, c) => {
97
97
  });
98
98
  const g = await O(
99
99
  t.getCurrentChainId(),
100
- f,
100
+ m,
101
101
  o,
102
- u,
102
+ w,
103
103
  c
104
104
  );
105
105
  return await x(C, {
@@ -108,25 +108,25 @@ const Q = async (t, e, r, p, o, i, u, c) => {
108
108
  phase: y.AFTER_SCHEDULE_WITHDRAW,
109
109
  scheduleId: g
110
110
  }), g;
111
- }, gt = async (t, e, r, p, o, i, u) => {
112
- const c = e.erc20TokenAddress, a = t.getCurrentChainId(), s = j(await t.getEthereumAddress()), n = i ?? await $(a, c, [c], z.Transact), { userDepositedUtxos: w, statusId: d } = await G(
111
+ }, gt = async (t, e, r, u, o, i, w) => {
112
+ const c = e.erc20TokenAddress, a = t.getCurrentChainId(), s = j(await t.getEthereumAddress()), n = i ?? await $(a, c, [c], z.Transact), { userDepositedUtxos: h, statusId: d, depositTxHash: m } = await G(
113
113
  t,
114
114
  e,
115
115
  r,
116
- p,
116
+ u,
117
117
  n,
118
118
  s
119
119
  );
120
- return Q(
120
+ return await Q(
121
121
  t,
122
122
  e,
123
- w,
123
+ h,
124
124
  n,
125
125
  s,
126
126
  d,
127
127
  o,
128
- u
129
- );
128
+ w
129
+ ), m;
130
130
  };
131
131
  export {
132
132
  gt as hinkalDepositAndWithdraw
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const z=require("ethers"),B=require("../../constants/protocol.constants.cjs"),j=require("../../functions/pre-transaction/outputUtxoProcessing.cjs"),G=require("../../functions/snarkjs/constructGeneralZkProof.cjs"),N=require("../../functions/web3/events/getShieldedBalance.cjs"),X=require("../../functions/web3/functionCalls/transactCallDirect.cjs"),J=require("../../types/external-action.types.cjs");require("../../types/circom-data.types.cjs");const u=require("../../types/ethereum-network.types.cjs"),L=require("../../types/admin.types.cjs");require("../../types/activities.types.cjs");const U=require("../../types/scheduled-transactions.types.cjs"),Q=require("../../functions/pre-transaction/getSignatureDataForTransact.cjs"),V=require("../../functions/pre-transaction/shouldPatchAccessTokenMerkleTree.cjs"),Y=require("../../functions/utils/getUtxosFromReceipt.utils.cjs"),tt=require("../../functions/utils/fees.utils.cjs"),et=require("../../functions/pre-transaction/constructAdminData.cjs"),st=require("../../API/admin-calls.cjs"),y=require("../../API/deposit-and-withdraw-status-calls.cjs"),ot=async(t,p,f,P,O,l)=>{const h=p.erc20TokenAddress,x=await t.getEthereumAddress(),a=f.map(e=>e+tt.calculateTotalFee(e,O)),n=[h],i=[0n],S=[!0],{patchAccessTokenMerkleTree:W,kycRequired:v,hasAccessToken:E}=await V.shouldPatchAccessTokenMerkleTree(t,n,i),_=await Q.getSignatureDataForTransact(t.getCurrentChainId(),x,t.userKeys,v,E),o=[...await N.addPaddingToUtxos(t,n,i)],C=[];for(let e=0;e<o.length;e+=1){const{outputUtxos:s}=j.outputUtxoProcessing(t.userKeys,o[e],i[e]);C.push(s)}const A=a.reduce((e,s)=>e+s,0n),F=z.ethers.AbiCoder.defaultAbiCoder().encode(["uint256[]"],[a]),g=t.getContractWithSigner(u.ContractType.HinkalWrapper),D=t.getContractWithSigner(u.ContractType.DepositOnChainUtxos),{zkCallData:I,circomData:k,dimData:b}=await G.constructZkProof("v1x1",t.merkleTreeHinkal,t.merkleTreeAccessToken,o,C,t.userKeys,`swapperM1x${o[0].length}x1`,J.ExternalActionId.DepositOnChainUtxos,await D.getAddress(),F,t.generateProofRemotely,B.zeroAddress,t.getCurrentChainId(),S,void 0,void 0,W,void 0,void 0,void 0,t.getContractWithFetcher(u.ContractType.HinkalHelperContract),_,await g.getAddress(),!1),r=t.getCurrentChainId(),T=(await y.updateDepositAndWithdrawStatus(r,{hashedEthereumAddress:l,phase:U.DepositAndWithdrawPhase.BEFORE_DEPOSIT})).id??void 0,m=await X.transactCallDirect(t,A,p,I,k,b,D,g),R=await m.wait(),H=m.hash;await y.safeUpdateDepositAndWithdrawStatus(r,{id:T,hashedEthereumAddress:l,phase:U.DepositAndWithdrawPhase.AFTER_DEPOSIT,depositTxHash:H});const M=await Y.getUtxosFromReceipt(R,t,h),w=[],c=[...M];P.forEach((e,s)=>{const q=a[s],d=c.find($=>$.amount===q);if(!d)throw new Error(`Could not find newly created UTXO with amount ${q} for recipient ${e}.`);w.push({recipientAddress:e,utxo:d});const Z=c.indexOf(d);c.splice(Z,1)});const K=et.constructAdminData(L.AdminTransactionType.DepositOnChainUtxos,r,n,[A],x);return st.emitTxPublicData(r,K),{userDepositedUtxos:w,statusId:T}};exports.hinkalDepositOnChainUtxos=ot;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const z=require("ethers"),B=require("../../constants/protocol.constants.cjs"),j=require("../../functions/pre-transaction/outputUtxoProcessing.cjs"),G=require("../../functions/snarkjs/constructGeneralZkProof.cjs"),N=require("../../functions/web3/events/getShieldedBalance.cjs"),X=require("../../functions/web3/functionCalls/transactCallDirect.cjs"),J=require("../../types/external-action.types.cjs");require("../../types/circom-data.types.cjs");const u=require("../../types/ethereum-network.types.cjs"),L=require("../../types/admin.types.cjs");require("../../types/activities.types.cjs");const y=require("../../types/scheduled-transactions.types.cjs"),Q=require("../../functions/pre-transaction/getSignatureDataForTransact.cjs"),V=require("../../functions/pre-transaction/shouldPatchAccessTokenMerkleTree.cjs"),Y=require("../../functions/utils/getUtxosFromReceipt.utils.cjs"),tt=require("../../functions/utils/fees.utils.cjs"),et=require("../../functions/pre-transaction/constructAdminData.cjs"),st=require("../../API/admin-calls.cjs"),f=require("../../API/deposit-and-withdraw-status-calls.cjs"),ot=async(t,p,P,O,S,l)=>{const h=p.erc20TokenAddress,x=await t.getEthereumAddress(),a=P.map(e=>e+tt.calculateTotalFee(e,S)),n=[h],i=[0n],W=[!0],{patchAccessTokenMerkleTree:v,kycRequired:E,hasAccessToken:_}=await V.shouldPatchAccessTokenMerkleTree(t,n,i),F=await Q.getSignatureDataForTransact(t.getCurrentChainId(),x,t.userKeys,E,_),o=[...await N.addPaddingToUtxos(t,n,i)],C=[];for(let e=0;e<o.length;e+=1){const{outputUtxos:s}=j.outputUtxoProcessing(t.userKeys,o[e],i[e]);C.push(s)}const A=a.reduce((e,s)=>e+s,0n),I=z.ethers.AbiCoder.defaultAbiCoder().encode(["uint256[]"],[a]),g=t.getContractWithSigner(u.ContractType.HinkalWrapper),D=t.getContractWithSigner(u.ContractType.DepositOnChainUtxos),{zkCallData:k,circomData:b,dimData:R}=await G.constructZkProof("v1x1",t.merkleTreeHinkal,t.merkleTreeAccessToken,o,C,t.userKeys,`swapperM1x${o[0].length}x1`,J.ExternalActionId.DepositOnChainUtxos,await D.getAddress(),I,t.generateProofRemotely,B.zeroAddress,t.getCurrentChainId(),W,void 0,void 0,v,void 0,void 0,void 0,t.getContractWithFetcher(u.ContractType.HinkalHelperContract),F,await g.getAddress(),!1),r=t.getCurrentChainId(),T=(await f.updateDepositAndWithdrawStatus(r,{hashedEthereumAddress:l,phase:y.DepositAndWithdrawPhase.BEFORE_DEPOSIT})).id??void 0,m=await X.transactCallDirect(t,A,p,k,b,R,D,g),H=await m.wait(),w=m.hash;await f.safeUpdateDepositAndWithdrawStatus(r,{id:T,hashedEthereumAddress:l,phase:y.DepositAndWithdrawPhase.AFTER_DEPOSIT,depositTxHash:w});const M=await Y.getUtxosFromReceipt(H,t,h),q=[],c=[...M];O.forEach((e,s)=>{const U=a[s],d=c.find($=>$.amount===U);if(!d)throw new Error(`Could not find newly created UTXO with amount ${U} for recipient ${e}.`);q.push({recipientAddress:e,utxo:d});const Z=c.indexOf(d);c.splice(Z,1)});const K=et.constructAdminData(L.AdminTransactionType.DepositOnChainUtxos,r,n,[A],x);return st.emitTxPublicData(r,K),{userDepositedUtxos:q,statusId:T,depositTxHash:w}};exports.hinkalDepositOnChainUtxos=ot;
@@ -4,4 +4,5 @@ import { FeeStructure } from '../../types/hinkal.types';
4
4
  export declare const hinkalDepositOnChainUtxos: (hinkal: IHinkal, erc20Token: ERC20Token, recipientAmounts: bigint[], recipientAddresses: string[], feeStructure: FeeStructure, hashedEthereumAddress: string) => Promise<{
5
5
  userDepositedUtxos: RecipientUtxo[];
6
6
  statusId?: string | undefined;
7
+ depositTxHash: string;
7
8
  }>;