# Hinkal SDK

Hinkal is a privacy middleware and smart-contract SDK for public blockchains that enables confidential transactions and settlement flows without changing wallets, custody, or chains.

The SDK allows wallets, dApps, and payment platforms to integrate protocol-level privacy on Ethereum, Solana, Tron, Polygon, Base, Arbitrum, and Optimism. It hides transaction history, wallet relationships, and asset flows on-chain while preserving public-chain finality and compliance.

With Hinkal SDK, developers can:
• Enable private sends between public wallets
• Perform confidential payouts and settlements
• Route transactions through Hinkal’s privacy contracts without exposing sender, recipient, or amounts
• Maintain non-custodial control with optional compliance visibility via viewing keys

## Compatibility

| Environment | Supported | Notes                      |
| ----------- | --------- | -------------------------- |
| Node.js     | ✅        | v18+                       |
| Browser     | ✅        | React, Next.js, vanilla JS |

## Installation

Using npm:

```sh
npm install @hinkal/common
```

Or, yarn:

```sh
yarn add @hinkal/common
```

## Usage

### Initialization

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.

Initializing the SDK creates a `Hinkal` object that encapsulates:

- The user's shielded balances
- Actions the user can perform, such as shielding (depositing), transfers, and swapping
- Cryptographic keys for privacy-preserving operations

**ethers.js:**

```typescript
import { prepareEthersHinkal } from '@hinkal/common/providers/prepareEthersHinkal';
// signer: ethers.Signer
const hinkal = await prepareEthersHinkal(signer, hinkalConfig);
```

**wagmi:**

```typescript
import { prepareWagmiHinkal } from '@hinkal/common/providers/prepareWagmiHinkal';
// connector: wagmi.Connector
// wagmiConfig: wagmi.Config
const hinkal = await prepareWagmiHinkal(connector, wagmiConfig, hinkalConfig);
```

The `hinkalConfig` is defined as follows:

```typescript
type HinkalConfig = {
  /** Disables caching in browser localStorage, storing data only in memory. Front-end only. Defaults to false. */
  disableCaching?: boolean;

  /** If true, allows caching in a file locally. Node.js only. Defaults to false. */
  useFileCache?: boolean;

  /**
   * Path to the cache file used for storing temporary data. Node.js only.
   * It should be a valid file path string. Defaults to hinkalCache.json in the current working directory.
   */
  cacheFilePath?: string;

  /**
   * Indicator controlling wether the proof should be constructed remotely in secure enclave. Defaults to true.
   */
  generateProofRemotely?: boolean;
};
```

### Shielded balance

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:

```typescript
const balances: Promise<Map<string, TokenBalance>> = await hinkal.getBalances();
```

This returns a map from token address to balance for all tokens held by the user, including ERC20 and ERC721 tokens.

### Shielding: depositing funds to the shielded balance

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.

A user can deposit funds to their shielded address using:

```typescript
function deposit(
  erc20Tokens: ERC20Token[],
  amountChanges: bigint[],
  preEstimateGas?: boolean,
  returnTxData?: boolean,
): Promise<ethers.providers.TransactionResponse>;
```

where:

- `erc20Tokens` is an array of tokens to deposit
- `amountChanges` represents the corresponding token amounts for the deposit
- `preEstimateGas` If true (default), the gas needed for the operation will be estimated before executing the deposit. This can help avoid failed transactions due to "out of gas" error.
- `returnTxData` If true, returns unsigned transaction data without executing. Defaults to false.

The `ERC20Token` type is defined as follows:

```typescript
type ERC20Token = {
  chainId: number;
  erc20TokenAddress: string;
  name: string;
  symbol: string;
  decimals: number;
};
```

### Private Send to Public Address: withdrawing funds from the shielded balance

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.

A user can withdraw funds from their shielded address to a public address using:

```typescript
function withdraw(
  erc20Tokens: ERC20Token[],
  deltaAmounts: bigint[],
  recipientAddress: string,
  isRelayerOff: boolean,
): Promise<string>;
```

where:

- `recipientAddress` is the public address that will receive the withdrawn funds
- `isRelayerOff` determines whether to use a relayer for the transaction (when `false`, a relayer handles gas fees; when `true`, the user pays gas directly)
- `string` type represents the transaction response from the relayer service.

### Private Send to Private Address: transfering funds from shielded balance

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.

A user can transfer tokens from their shielded balance to another shielded address using:

```typescript
function transfer(erc20Tokens: ERC20Token[], deltaAmounts: bigint[], privateRecipientAddress: string): Promise<string>;
```

where:

- `privateRecipientAddress` is the recipient's private address, formatted as a comma-separated string with five components:
- `randomization` - a random value for privacy
- `stealthAddress` - the recipient's stealth address (hex format starting with `0x`)
- `encryptionKey` - the recipient's encryption key (hex format starting with `0x`, 66 characters)
- `H0` - the first hash component of elliptic curve point for stealth address derivation
- `H1` - the second hash component of elliptic curve point for stealth address derivation

### Private Send from Public to Public addresses

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.

A user can perform a private transfer between public addresses using:

```typescript
function depositAndWithdraw(
  erc20Token: ERC20Token,
  recipientAmounts: bigint[],
  recipientAddresses: string[],
  txCompletionTime?: number,
  preEstimateGas?: boolean,
): Promise<string>;
```

where:

- `erc20Token` is the token to transfer (only single token transfers are supported for this method)
- `recipientAmounts` is an array of amounts to send to each recipient (in the token's smallest unit)
- `recipientAddresses` is an array of public addresses that will receive the funds
- `txCompletionTime` (optional) specifies a delay in milliseconds before the withdrawal completes
- `preEstimateGas` If true (default), the gas needed for the operation will be estimated before executing the deposit. This can help avoid failed transactions due to "out of gas" error.

### Swapping tokens from the shielded balance

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.

A user can swap tokens directly from their shielded balance using:

```typescript
function swap(
  erc20Tokens: ERC20Token[],
  deltaAmounts: bigint[],
  externalActionId: ExternalActionId,
  swapData: string,
): Promise<string>;
```

where:

- `externalActionId` identifies the external swap protocol to use. Possible values include:
  - `ExternalActionId.Uniswap` - for Uniswap swaps
  - `ExternalActionId.OneInch` - for 1Inch swaps
  - `ExternalActionId.Odos` - for Odos swaps
- `swapData` contains the encoded swap parameters specific to the chosen protocol

**Getting swap calldata:**

To obtain the swap calldata using the Hinkal SDK, you can use the built-in swap data generation utilities.

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:

**1Inch:**

```typescript
function getOneInchPrice(
  chainId: number,
  inSwapToken: ERC20Token,
  outSwapToken: ERC20Token,
  inSwapAmount: string,
  slippagePercentage?: number,
): Promise<{
  outSwapAmountValue: bigint;
  oneInchDataValue: string;
}>;
```

Similar functions are available for other supported swap protocols:

- **Uniswap:** `getUniswapPrice`
- **Odos:** `getOdosPrice`
- **LiFi:** `getLifiPrice`

### Interacting with smart contracts privately

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.

```typescript
function actionPrivateWallet(
  chainId: number,
  erc20Tokens: ERC20Token[],
  deltaAmounts: bigint[],
  onChainCreation: boolean[],
  ops: string[],
): Promise<string>;
```

Parameters:

- `chainId` - the blockchain network identifier
- `onChainCreation` - array of booleans indicating the direction of token changes: `true` for positive changes (tokens received), `false` for negative changes (tokens spent)
- `ops` - array of encoded user operations to execute (see User operations below)

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.

To generate user operations, a user will need the `emporiumOp` function.

```typescript
function emporiumOp(
  contract: ethers.Contract | string;
  func?: string;
  args?: any[];
  callDataString?: string;
  invokeWallet?: boolean;
  value?: bigint;
): Promise<string>;
```

The function accepts the following arguments:

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.
2. `func` _(optional)_ - the name of the function to be called on the target address.
3. `args` _(optional)_ - arguments of the function to be called on the target address.
4. `callDataString` _(optional)_ - pre-encoded calldata string. If provided, `func` and `args` should not be used.
5. `invokeWallet` _(optional)_ - boolean flag that determines the type of interaction (see the stateless/stateful interactions below).
6. `value` _(optional)_ - the value field to the user operation call.

When the Emporium contract executes a user operation, it receives the data in this format:

```solidity
(address endpoint, bool invokeWallet, uint256 value, bytes data)
```

This enables the Emporium contract to execute generic calls using user operations:

```solidity
(bool success, bytes memory err) = endpoint.call{value: value}(data);
```

User operations can be categorized into two types based on whether the target protocol needs to track the caller account's history:

**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.

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.

```typescript
const operations = [
  emporiumOp({ contract: usdcContractInstance, func: 'approve', args: [swapRouterAddress, amountIn] }),
  emporiumOp({ contract: swapRouterContractInstance, func: 'exactInputSingle', args: [swapSingleParams] }),
  emporiumOp({ contract: wethContractInstance, func: 'withdraw', args: [amountOut] }),
];
```

In this example:

- First operation approves the swap router to spend USDC tokens
- Second operation executes the swap from USDC to WETH
- Third operation unwraps WETH to ETH

**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.

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.

```typescript
const operations = [
  emporiumOp({ contract: lpTokenInstance, func: 'approve', args: [gaugeAddressInstance, amount], invokeWallet: true }),
  emporiumOp({
    contract: gaugeAddressInstance,
    func: 'deposit',
    args: [amount, invokeWalletAddress],
    invokeWallet: true,
  }),
];
```

In this example:

- First operation approves the gauge contract to spend LP tokens, executed from the persistent wallet
- Second operation deposits LP tokens into the gauge, with the wallet address as the recipient for reward tracking

## Access Tokens

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.

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.

To check whether a user already has an access token on a specific chain, use the `checkAccessToken` function:

```typescript
function checkAccessToken(): Promise<boolean>;
```

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.

To get a list of all available compliance providers that can be used for verification:

```typescript
function getSupportedPassportLinks(): string[];
```

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.

## Supported Chains

Hinkal SDK is available on the following blockchain networks:

| Chain    | Chain ID | Status  |
| -------- | -------- | ------- |
| Ethereum | 1        | ✅ Live |
| Polygon  | 137      | ✅ Live |
| Base     | 8453     | ✅ Live |
| Arbitrum | 42161    | ✅ Live |
| Optimism | 10       | ✅ Live |
| Solana   | -        | ✅ Live |
| Tron     | -        | ✅ Live |

Each chain supports the full suite of Hinkal privacy features including shielding, transfers, and confidential interactions with DeFi protocols.

## References

Wallet: [Hinkal Wallet](https://chromewebstore.google.com/detail/hinkal-wallet/khfjgapjfcdoffmklchibpepboholpbe)

Application: [Hinkal Pay](https://pay.hinkal.io)

Docs: [Hinkal Documentation](https://hinkal-team.gitbook.io/hinkal)
