@sabaaa1/common 0.0.2 → 0.0.3
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/package.json +1 -1
- package/providers/WagmiProviderAdapter.cjs +1 -1
- package/providers/WagmiProviderAdapter.mjs +12 -12
- package/README.md +0 -164
package/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("../constants/chains.constants.cjs"),o=require("../error-handling/error-codes.constants.cjs"),s=require("ethers"),g=require("wagmi"),
|
|
1
|
+
"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const i=require("../constants/chains.constants.cjs"),o=require("../error-handling/error-codes.constants.cjs"),s=require("ethers"),g=require("wagmi"),n=require("wagmi/actions"),a=require("../functions/web3/getContractMetadata.cjs");class h{connector;chainId;originalProvider;fetchProvider;signer;chainEventListener;config;unsubscribeFns=[];initConnector(t){this.connector=t}getSigner(){if(!this.signer)throw new Error("No Signer In Provider Adapter");return this.signer}requireConnector(){if(!this.connector)throw Error("No Connector In Provider Adapter")}initConfig(t){this.config=t}async init(t){this.requireConnector(),t&&(this.chainId=t),this.originalProvider=await this.connector.getProvider(),this.fetchProvider=this.createFetchProvider()??this.originalProvider,this.fetchProvider===this.originalProvider&&console.warn("fetchProvider not available");const r=await this.connector.getProvider(),e=await this.connector.getAccounts();this.signer=await this.walletClientToSigner({transport:r,account:e[0]},this.chainId)}async disconnectFromConnector(){if(!this.config)throw new Error("No Config In Provider Adapter");this.release(),await n.disconnect(this.config)}async connectToConnector(t){if(!this.config)throw new Error("No Config In Provider Adapter");if(t.id==="walletConnect")try{await n.reconnect(this.config,{connectors:[t]}),await n.disconnect(this.config)}catch{}try{return(await n.connect(this.config,{connector:t})).chainId}catch(r){if(r instanceof g.ConnectorAlreadyConnectedError)return t.getChainId();let e=o.transactionErrorCodes.CONNECTION_FAILED;throw r?.code===4001&&(e=o.UserFriendlyErrorCodes.YOU_CANCELED_REQUEST),new Error(e)}}async waitForTransaction(t,r){if((await this.fetchProvider?.waitForTransaction(t,r))?.status)return!0;throw Error(o.transactionErrorCodes.TRANSACTION_NOT_CONFIRMED)}async signMessage(t){if(!this.config)throw new Error("No Config In Provider Adapter");const r=await n.signMessage(this.config,{message:t});if(!r)throw new Error(o.transactionErrorCodes.SIGNING_FAILED);if(r.includes("error"))throw new Error(o.transactionErrorCodes.SIGNATURE_UNSUPPORTED_PERSONAL_SIGN);return r}async signTypedData(t,r,e){return this.signer._signTypedData(t,r,e)}getSelectedNetwork=()=>{if(!this.chainId)throw new Error("Illegal state: no chaindId");return i.networkRegistry[this.chainId]};async switchNetwork(t){if(!this.config)throw new Error("No Config In Provider Adapter");return n.switchChain(this.config,{chainId:t.chainId})}createFetchProvider(){try{const r=i.networkRegistry[this.chainId]?.fetchRpcUrl;return r?r.includes("wss")?new s.providers.WebSocketProvider(r):new s.providers.StaticJsonRpcProvider(r):void 0}catch(t){console.log("create Fetch Provider error",t);return}}async getAddress(){if(!this.config)throw new Error("No Config In Provider Adapter");const{address:t}=n.getAccount(this.config);if(!t)throw new Error("IllegalState");return s.utils.getAddress(t)}setChainEventListener(t){if(!this.config)throw new Error("No Config In Provider Adapter");this.chainEventListener=t,this.chainEventListener&&(this.unsubscribeFns.push(n.watchAccount(this.config,{onChange:({address:r},{address:e})=>{if(!this.chainEventListener){console.warn("chainEventListener is not set");return}console.log("Account changed"),r!==e&&(console.log("Account changed"),this.chainEventListener.onAccountChanged())}})),this.unsubscribeFns.push(n.watchChainId(this.config,{onChange:r=>{if(!this.chainEventListener){console.warn("chainEventListener is not set");return}console.log("Chain ID changed!",r),this.chainEventListener.onChainChanged(r)}})))}onAccountChanged(){return this.init()}onChainChanged(t){return this.init(t)}release(){this.removeListeners()}removeListeners(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[]}parseChainIdParam(t){const r=t??this.chainId;if(!r)throw new Error("No chainId provided in context");return r}getContractMetadata(t,r){const e=this.parseChainIdParam(r);return a.getContractMetadata(t,e)}getContract(t,r=void 0,e){const c=this.parseChainIdParam(e);return a.getContract(t,c,r)}getContractWithSigner(t,r=void 0){if(!this.signer)throw new Error("IllegalState: no signer");return this.getContract(t,r).connect(this.signer)}getContractWithFetcher(t,r=void 0){if(!this.fetchProvider)throw new Error("fetchProvider not initialized");return this.getContract(t,r).connect(this.fetchProvider)}getContractWithFetcherForEthereum(t,r=void 0){const e=this.chainId===i.chainIds.localhost&&i.localhostNetwork===i.chainIds.ethMainnet?i.chainIds.localhost:i.chainIds.ethMainnet;return a.getContractWithFetcherByChainId(e,t,r)}async sendTransaction(t){if(!this.signer)throw new Error("IllegalState: no signer");return await this.signer.sendTransaction(t)}async connectAndPatchProvider(t){return await this.connectToConnector(t)}isPermitterAvailable(){return!!this.getSelectedNetwork()?.contractData?.permitterAddress}async getGasPrice(){const t=await this.fetchProvider?.getGasPrice();if(!t)throw Error("Could not fetch gas price in getGasPrice");return t.toBigInt()}async walletClientToSigner(t,r){const{account:e,transport:c}=t,d={chainId:r,name:""};return new s.providers.Web3Provider(c,d).getSigner(e)}switchAccount(){throw new Error("Method not implemented.")}}const w=new h,u=()=>new h;exports.WagmiProviderAdapter=h;exports.default=u;exports.wagmiProviderAdapter=w;
|
|
@@ -2,8 +2,8 @@ import { networkRegistry as c, chainIds as n, localhostNetwork as g } from "../c
|
|
|
2
2
|
import { transactionErrorCodes as i, UserFriendlyErrorCodes as w } from "../error-handling/error-codes.constants.mjs";
|
|
3
3
|
import { providers as s, utils as f } from "ethers";
|
|
4
4
|
import { ConnectorAlreadyConnectedError as l } from "wagmi";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
5
|
+
import { disconnect as a, reconnect as u, connect as v, signMessage as C, switchChain as I, getAccount as E, watchAccount as p, watchChainId as P } from "wagmi/actions";
|
|
6
|
+
import { getContractMetadata as A, getContract as m, getContractWithFetcherByChainId as N } from "../functions/web3/getContractMetadata.mjs";
|
|
7
7
|
class h {
|
|
8
8
|
connector;
|
|
9
9
|
chainId;
|
|
@@ -43,11 +43,11 @@ class h {
|
|
|
43
43
|
throw new Error("No Config In Provider Adapter");
|
|
44
44
|
if (t.id === "walletConnect")
|
|
45
45
|
try {
|
|
46
|
-
await
|
|
46
|
+
await u(this.config, { connectors: [t] }), await a(this.config);
|
|
47
47
|
} catch {
|
|
48
48
|
}
|
|
49
49
|
try {
|
|
50
|
-
return (await
|
|
50
|
+
return (await v(this.config, { connector: t })).chainId;
|
|
51
51
|
} catch (r) {
|
|
52
52
|
if (r instanceof l)
|
|
53
53
|
return t.getChainId();
|
|
@@ -63,7 +63,7 @@ class h {
|
|
|
63
63
|
async signMessage(t) {
|
|
64
64
|
if (!this.config)
|
|
65
65
|
throw new Error("No Config In Provider Adapter");
|
|
66
|
-
const r = await
|
|
66
|
+
const r = await C(this.config, { message: t });
|
|
67
67
|
if (!r)
|
|
68
68
|
throw new Error(i.SIGNING_FAILED);
|
|
69
69
|
if (r.includes("error"))
|
|
@@ -81,7 +81,7 @@ class h {
|
|
|
81
81
|
async switchNetwork(t) {
|
|
82
82
|
if (!this.config)
|
|
83
83
|
throw new Error("No Config In Provider Adapter");
|
|
84
|
-
return
|
|
84
|
+
return I(this.config, {
|
|
85
85
|
chainId: t.chainId
|
|
86
86
|
});
|
|
87
87
|
}
|
|
@@ -97,7 +97,7 @@ class h {
|
|
|
97
97
|
async getAddress() {
|
|
98
98
|
if (!this.config)
|
|
99
99
|
throw new Error("No Config In Provider Adapter");
|
|
100
|
-
const { address: t } =
|
|
100
|
+
const { address: t } = E(this.config);
|
|
101
101
|
if (!t)
|
|
102
102
|
throw new Error("IllegalState");
|
|
103
103
|
return f.getAddress(t);
|
|
@@ -106,7 +106,7 @@ class h {
|
|
|
106
106
|
if (!this.config)
|
|
107
107
|
throw new Error("No Config In Provider Adapter");
|
|
108
108
|
this.chainEventListener = t, this.chainEventListener && (this.unsubscribeFns.push(
|
|
109
|
-
|
|
109
|
+
p(this.config, {
|
|
110
110
|
onChange: ({ address: r }, { address: e }) => {
|
|
111
111
|
if (!this.chainEventListener) {
|
|
112
112
|
console.warn("chainEventListener is not set");
|
|
@@ -116,7 +116,7 @@ class h {
|
|
|
116
116
|
}
|
|
117
117
|
})
|
|
118
118
|
), this.unsubscribeFns.push(
|
|
119
|
-
|
|
119
|
+
P(this.config, {
|
|
120
120
|
onChange: (r) => {
|
|
121
121
|
if (!this.chainEventListener) {
|
|
122
122
|
console.warn("chainEventListener is not set");
|
|
@@ -147,11 +147,11 @@ class h {
|
|
|
147
147
|
}
|
|
148
148
|
getContractMetadata(t, r) {
|
|
149
149
|
const e = this.parseChainIdParam(r);
|
|
150
|
-
return
|
|
150
|
+
return A(t, e);
|
|
151
151
|
}
|
|
152
152
|
getContract(t, r = void 0, e) {
|
|
153
153
|
const o = this.parseChainIdParam(e);
|
|
154
|
-
return
|
|
154
|
+
return m(t, o, r);
|
|
155
155
|
}
|
|
156
156
|
getContractWithSigner(t, r = void 0) {
|
|
157
157
|
if (!this.signer)
|
|
@@ -165,7 +165,7 @@ class h {
|
|
|
165
165
|
}
|
|
166
166
|
getContractWithFetcherForEthereum(t, r = void 0) {
|
|
167
167
|
const e = this.chainId === n.localhost && g === n.ethMainnet ? n.localhost : n.ethMainnet;
|
|
168
|
-
return
|
|
168
|
+
return N(e, t, r);
|
|
169
169
|
}
|
|
170
170
|
async sendTransaction(t) {
|
|
171
171
|
if (!this.signer)
|
package/README.md
DELETED
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
# Hinkal SDK
|
|
2
|
-
|
|
3
|
-
Hinkal is middleware and a set of smart contracts on EVM chains that use ZK-proofs and stealth addresses to enable compliant and private transactions on major dApps. Users can privately store assets and transact on platforms such as Uniswap, Pendle, Lido, Curve, and others.
|
|
4
|
-
|
|
5
|
-
This SDK enables users to perform arbitrary smart contract interactions privately.
|
|
6
|
-
|
|
7
|
-
## Installation
|
|
8
|
-
|
|
9
|
-
Using npm:
|
|
10
|
-
|
|
11
|
-
```sh
|
|
12
|
-
npm install @hinkal/common
|
|
13
|
-
```
|
|
14
|
-
|
|
15
|
-
Or, yarn:
|
|
16
|
-
|
|
17
|
-
```sh
|
|
18
|
-
yarn add @hinkal/common
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
### Usage
|
|
22
|
-
|
|
23
|
-
#### Initialization
|
|
24
|
-
|
|
25
|
-
To get started with Hinkal, initialize it based on the Web3 connection library you’re using:
|
|
26
|
-
|
|
27
|
-
**ethers.js:**
|
|
28
|
-
|
|
29
|
-
```typescript
|
|
30
|
-
import { prepareEthersHinkal } from '@hinkal/common/providers/prepareEthersHinkal';
|
|
31
|
-
// signer: ethers.Signer
|
|
32
|
-
const hinkal = await prepareEthersHinkal(signer);
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
**wagmi:**
|
|
36
|
-
|
|
37
|
-
```typescript
|
|
38
|
-
import { prepareWagmiHinkal } from '@hinkal/common/providers/prepareWagmiHinkal';
|
|
39
|
-
// connector: wagmi.Connector
|
|
40
|
-
// config: wagmi.Config
|
|
41
|
-
const hinkal = await prepareWagmiHinkal(connector, config);
|
|
42
|
-
```
|
|
43
|
-
|
|
44
|
-
#### Shielded balance
|
|
45
|
-
|
|
46
|
-
Once the Hinkal object is initialized, shielded balances become accessible and can be calculated as needed:
|
|
47
|
-
|
|
48
|
-
```typescript
|
|
49
|
-
const balances = await hinkal.getBalances();
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
#### Depositing funds to the shielded balance
|
|
53
|
-
|
|
54
|
-
A user can deposit funds to their shielded address using:
|
|
55
|
-
|
|
56
|
-
```typescript
|
|
57
|
-
function deposit(erc20addresses: string[], amountChanges: bigint[]): Promise<TransactionObject>;
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
where erc20Addresses is an array of token addresses, and amountChanges represents the token amounts for the deposit.
|
|
61
|
-
|
|
62
|
-
#### Interacting with smart contracts privately
|
|
63
|
-
|
|
64
|
-
After a user’s shielded balance is updated, they can perform any smart contract interaction privately using:
|
|
65
|
-
|
|
66
|
-
```typescript
|
|
67
|
-
function actionPrivateWallet(
|
|
68
|
-
erc20Addresses: string[],
|
|
69
|
-
amountChanges: bigint[],
|
|
70
|
-
onChainCreation: boolean[],
|
|
71
|
-
ops: string[],
|
|
72
|
-
): Promise<TransactionObject>;
|
|
73
|
-
```
|
|
74
|
-
|
|
75
|
-
where onChainCreation indicates the amounts of tokens that are uncertain before the transaction is executed on-chain. The ops array contains encoded user operations.
|
|
76
|
-
|
|
77
|
-
##### User operations
|
|
78
|
-
|
|
79
|
-
To generate user operations (`ops`) you will need the `emporiumOp` function.
|
|
80
|
-
```typescript
|
|
81
|
-
import {emporiumOp} from "@hinkal/common";
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
The function accepts the following arguments:
|
|
85
|
-
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.
|
|
86
|
-
2. `func` *(optional)* - the name of the function to be called on the target address.
|
|
87
|
-
3. `args` *(optional)* - arguments of the function to be called on the target address.
|
|
88
|
-
4. `invokeWallet` *(optional)* - bool flag that determines the type of transaction. There are two types: stateful and stateless interaction. The default is false (stateless).
|
|
89
|
-
5. `value` *(optional)* - the amount of native currency to transfer to the target address.
|
|
90
|
-
|
|
91
|
-
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.
|
|
92
|
-
|
|
93
|
-
To execute on a smart contract, the user operation will be received in the following format:
|
|
94
|
-
```solidity
|
|
95
|
-
(address endpoint, bool invokeWallet, uint256 value, bytes data)
|
|
96
|
-
```
|
|
97
|
-
|
|
98
|
-
This will make it possible to make that kind of call:
|
|
99
|
-
```solidity
|
|
100
|
-
(bool success, bytes memory err) = endpoint.call{value: value}(data);
|
|
101
|
-
```
|
|
102
|
-
|
|
103
|
-
##### Stateless and stateful
|
|
104
|
-
|
|
105
|
-
The best way to demonstrate how this works is with an example.
|
|
106
|
-
|
|
107
|
-
**Stateless interaction**
|
|
108
|
-
|
|
109
|
-
Let's say we need to exchange USDC for ETH using DEX.
|
|
110
|
-
|
|
111
|
-
```typescript
|
|
112
|
-
const operations = [
|
|
113
|
-
emporiumOp(usdcContractInstance, 'approve', [swapRouterAddress, amountIn]),
|
|
114
|
-
emporiumOp(swapRouterContractInstance, 'exactInputSingle', [swapSingleParams]),
|
|
115
|
-
emporiumOp(wethContractInstance, 'withdraw', [amountOut]),
|
|
116
|
-
];
|
|
117
|
-
```
|
|
118
|
-
|
|
119
|
-
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.
|
|
120
|
-
|
|
121
|
-
In this case it will be **stateless interaction**, so there is no need to change the default value of the `invokeWallet` flag.
|
|
122
|
-
|
|
123
|
-
**Stateful interaction**
|
|
124
|
-
|
|
125
|
-
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.
|
|
126
|
-
|
|
127
|
-
Let's imagine that you already have Curve LP tokens and need to make a stake.
|
|
128
|
-
|
|
129
|
-
```solidity
|
|
130
|
-
const operations = [
|
|
131
|
-
emporiumOp(lpTokenInstance, 'approve', [gaugeAddressInstance, amount]), // without flag, because is's stateless interaction
|
|
132
|
-
emporiumOp(gaugeAddressInstance, 'deposit', [amount, invokeWalletAddress], true), // with flag, because it's stateful interaction
|
|
133
|
-
];
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
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.
|
|
137
|
-
|
|
138
|
-
### Access Tokens
|
|
139
|
-
|
|
140
|
-
Before interacting with Hinkal smart contracts, users need to mint an access token after passing compliance checks.
|
|
141
|
-
|
|
142
|
-
To check whether a user already has an access token, use the checkAccessToken function:
|
|
143
|
-
|
|
144
|
-
```typescript
|
|
145
|
-
function checkAccessToken(): Promise<boolean>;
|
|
146
|
-
```
|
|
147
|
-
|
|
148
|
-
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:
|
|
149
|
-
|
|
150
|
-
```typescript
|
|
151
|
-
function getSupportedPassportLinks(): string[];
|
|
152
|
-
```
|
|
153
|
-
|
|
154
|
-
After passing the compliance check, the user can mint an access token using:
|
|
155
|
-
|
|
156
|
-
```typescript
|
|
157
|
-
const { signatureData } = await hinkal.getAPI().getAccessTokenSignature(chainId, ethereumAddress, accessKey);
|
|
158
|
-
await mintAccessToken(this, signatureData);
|
|
159
|
-
```
|
|
160
|
-
|
|
161
|
-
### References
|
|
162
|
-
|
|
163
|
-
Application: [Hinkal](https://app.hinkal.pro)
|
|
164
|
-
Docs: [Hinkal Documentation](https://hinkal-team.gitbook.io/hinkal)
|