@zama-fhe/sdk 2.5.0 → 3.0.0-alpha.10
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 +18 -84
- package/dist/cjs/cleartext.cjs +1 -1
- package/dist/cjs/cleartext.cjs.map +1 -1
- package/dist/cjs/ethers/index.cjs +1 -1
- package/dist/cjs/ethers/index.cjs.map +1 -1
- package/dist/cjs/index.cjs +3 -22
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/readonly-token.cjs +2 -0
- package/dist/cjs/readonly-token.cjs.map +1 -0
- package/dist/cjs/relayer-sdk.worker.js +1 -20
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/cjs/wrappers-registry.cjs +1 -1
- package/dist/cjs/wrappers-registry.cjs.map +1 -1
- package/dist/esm/cleartext/index.d.ts +4 -10
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-Cs28cTsa.js → cleartext-hS6TVszr.js} +2 -2
- package/dist/esm/cleartext-hS6TVszr.js.map +1 -0
- package/dist/esm/ethers/index.d.ts +2 -2
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/index.d.ts +6 -12
- package/dist/esm/index.js +3 -22
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/{memory-storage-F8xjMzVy.js → memory-storage-GS1uT4ua.js} +2 -2
- package/dist/esm/memory-storage-GS1uT4ua.js.map +1 -0
- package/dist/esm/node/index.d.ts +4 -10
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/node/index.js.map +1 -1
- package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
- package/dist/esm/node/relayer-sdk.node-worker.js.map +1 -1
- package/dist/esm/{activity-DBMyE78S.d.ts → onchain-events-dMUs_wMQ.d.ts} +4480 -5268
- package/dist/esm/query/index.d.ts +16 -57
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/readonly-token-BPfj8Qgf.js +2 -0
- package/dist/esm/readonly-token-BPfj8Qgf.js.map +1 -0
- package/dist/esm/{relayer-sdk-DPqytEbO.d.ts → relayer-sdk-CjKGIodc.d.ts} +4 -10
- package/dist/esm/{relayer-sdk.types-CGfXwKcB.d.ts → relayer-sdk.types-DawSwNjS.d.ts} +24 -61
- package/dist/esm/relayer-sdk.worker.js +1 -20
- package/dist/esm/{relayer-utils-BeoTNDM4.js → relayer-utils-DDa_R8Ft.js} +2 -2
- package/dist/esm/relayer-utils-DDa_R8Ft.js.map +1 -0
- package/dist/esm/viem/index.d.ts +2 -2
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/wrappers-registry-Dzw2Yvk6.js +2 -0
- package/dist/esm/wrappers-registry-Dzw2Yvk6.js.map +1 -0
- package/package.json +1 -1
- package/dist/cjs/activity.cjs +0 -2
- package/dist/cjs/activity.cjs.map +0 -1
- package/dist/esm/activity-dMzF5FdR.js +0 -2
- package/dist/esm/activity-dMzF5FdR.js.map +0 -1
- package/dist/esm/cleartext-Cs28cTsa.js.map +0 -1
- package/dist/esm/memory-storage-F8xjMzVy.js.map +0 -1
- package/dist/esm/relayer-utils-BeoTNDM4.js.map +0 -1
- package/dist/esm/wrappers-registry-DO0729Zi.js +0 -2
- package/dist/esm/wrappers-registry-DO0729Zi.js.map +0 -1
package/README.md
CHANGED
|
@@ -186,7 +186,7 @@ Full read/write interface for a single confidential ERC-20. Extends `ReadonlyTok
|
|
|
186
186
|
| `unwrap(amount)` | Request unwrap for a specific amount (low-level, requires manual finalization). |
|
|
187
187
|
| `unwrapAll()` | Request unwrap for the entire balance (low-level, requires manual finalization). |
|
|
188
188
|
| `resumeUnshield(unwrapTxHash, callbacks?)` | Resume an interrupted unshield from an existing unwrap tx hash. Goes straight to wait receipt → finalize. |
|
|
189
|
-
| `finalizeUnwrap(
|
|
189
|
+
| `finalizeUnwrap(unwrapRequestId)` | Complete unwrap with public decryption proof. |
|
|
190
190
|
| `confidentialTransfer(to, amount)` | Encrypted transfer. Encrypts amount, then calls the contract. |
|
|
191
191
|
| `confidentialTransferFrom(from, to, amt)` | Operator encrypted transfer. |
|
|
192
192
|
| `approve(spender, until?)` | Set operator approval. `until` defaults to now + 1 hour. |
|
|
@@ -534,15 +534,15 @@ interface ContractCallConfig {
|
|
|
534
534
|
|
|
535
535
|
### Wrapper
|
|
536
536
|
|
|
537
|
-
| Function
|
|
538
|
-
|
|
|
539
|
-
| `wrapContract(wrapper, to, amount)`
|
|
540
|
-
| `unwrapContract(token, from, to, encryptedAmount, inputProof)`
|
|
541
|
-
| `unwrapFromBalanceContract(token, from, to, encryptedBalance)`
|
|
542
|
-
| `finalizeUnwrapContract(wrapper,
|
|
543
|
-
| `underlyingContract(wrapper)`
|
|
544
|
-
| `inferredTotalSupplyContract(wrapper)`
|
|
545
|
-
| `totalSupplyContract(wrapper)`
|
|
537
|
+
| Function | Description |
|
|
538
|
+
| -------------------------------------------------------------------- | --------------------------------------------------- |
|
|
539
|
+
| `wrapContract(wrapper, to, amount)` | Wrap ERC-20 tokens. |
|
|
540
|
+
| `unwrapContract(token, from, to, encryptedAmount, inputProof)` | Request unwrap with encrypted amount. |
|
|
541
|
+
| `unwrapFromBalanceContract(token, from, to, encryptedBalance)` | Request unwrap using on-chain balance handle. |
|
|
542
|
+
| `finalizeUnwrapContract(wrapper, unwrapRequestId, cleartext, proof)` | Finalize unwrap with decryption proof. |
|
|
543
|
+
| `underlyingContract(wrapper)` | Read underlying ERC-20 address. |
|
|
544
|
+
| `inferredTotalSupplyContract(wrapper)` | Read inferred plaintext total supply. |
|
|
545
|
+
| `totalSupplyContract(wrapper)` | Deprecated alias for `inferredTotalSupplyContract`. |
|
|
546
546
|
|
|
547
547
|
### ERC-165
|
|
548
548
|
|
|
@@ -626,8 +626,8 @@ Individual topic hashes are accessible via the `Topics` object: `Topics.Confiden
|
|
|
626
626
|
| --------------------------------- | ----------------------------------------------------------------------------------------------------------- |
|
|
627
627
|
| `decodeConfidentialTransfer(log)` | `ConfidentialTransferEvent \| null` — `{ from, to, encryptedAmountHandle }` |
|
|
628
628
|
| `decodeWrapped(log)` | `WrappedEvent \| null` — `{ to, amountIn }` |
|
|
629
|
-
| `decodeUnwrapRequested(log)` | `UnwrapRequestedEvent \| null` — `{ receiver, encryptedAmount }`
|
|
630
|
-
| `decodeUnwrappedFinalized(log)` | `UnwrappedFinalizedEvent \| null` — `{ receiver, encryptedAmount, cleartextAmount }`
|
|
629
|
+
| `decodeUnwrapRequested(log)` | `UnwrapRequestedEvent \| null` — `{ receiver, unwrapRequestId, encryptedAmount }` |
|
|
630
|
+
| `decodeUnwrappedFinalized(log)` | `UnwrappedFinalizedEvent \| null` — `{ receiver, unwrapRequestId, encryptedAmount, cleartextAmount }` |
|
|
631
631
|
| `decodeUnwrappedStarted(log)` | `UnwrappedStartedEvent \| null` — `{ returnVal, requestId, txId, to, refund, requestedAmount, burnAmount }` |
|
|
632
632
|
| `decodeOnChainEvent(log)` | `OnChainEvent \| null` — tries all decoders |
|
|
633
633
|
| `decodeOnChainEvents(logs)` | `OnChainEvent[]` — batch decode, skips unrecognized logs |
|
|
@@ -643,73 +643,6 @@ const wrappedEvent = findWrapped(receipt.logs);
|
|
|
643
643
|
const unwrapEvent = findUnwrapRequested(receipt.logs);
|
|
644
644
|
```
|
|
645
645
|
|
|
646
|
-
## Activity Feed Helpers
|
|
647
|
-
|
|
648
|
-
Transform raw event logs into a user-friendly activity feed with decrypted amounts.
|
|
649
|
-
|
|
650
|
-
### Pipeline
|
|
651
|
-
|
|
652
|
-
```ts
|
|
653
|
-
import {
|
|
654
|
-
parseActivityFeed,
|
|
655
|
-
extractEncryptedHandles,
|
|
656
|
-
applyDecryptedValues,
|
|
657
|
-
sortByBlockNumber,
|
|
658
|
-
} from "@zama-fhe/sdk";
|
|
659
|
-
|
|
660
|
-
// 1. Parse raw logs into classified activity items
|
|
661
|
-
const items = parseActivityFeed(logs, userAddress);
|
|
662
|
-
|
|
663
|
-
// 2. Extract encrypted handles that need decryption
|
|
664
|
-
const handles = extractEncryptedHandles(items);
|
|
665
|
-
|
|
666
|
-
// 3. Decrypt handles via SDK
|
|
667
|
-
const decryptedMap = await sdk.userDecrypt(
|
|
668
|
-
handles.map((h) => ({ handle: h, contractAddress: tokenAddress })),
|
|
669
|
-
);
|
|
670
|
-
|
|
671
|
-
// 4. Apply decrypted values back to activity items
|
|
672
|
-
const enrichedItems = applyDecryptedValues(items, decryptedMap);
|
|
673
|
-
|
|
674
|
-
// 5. Sort by block number (most recent first)
|
|
675
|
-
const sorted = sortByBlockNumber(enrichedItems);
|
|
676
|
-
```
|
|
677
|
-
|
|
678
|
-
### Types
|
|
679
|
-
|
|
680
|
-
```ts
|
|
681
|
-
type ActivityDirection = "incoming" | "outgoing" | "self";
|
|
682
|
-
|
|
683
|
-
type ActivityType =
|
|
684
|
-
| "transfer"
|
|
685
|
-
| "shield"
|
|
686
|
-
| "unshield_requested"
|
|
687
|
-
| "unshield_started"
|
|
688
|
-
| "unshield_finalized";
|
|
689
|
-
|
|
690
|
-
type ActivityAmount =
|
|
691
|
-
| { type: "clear"; value: bigint }
|
|
692
|
-
| { type: "encrypted"; handle: string; decryptedValue?: bigint };
|
|
693
|
-
|
|
694
|
-
interface ActivityItem {
|
|
695
|
-
type: ActivityType;
|
|
696
|
-
direction: ActivityDirection;
|
|
697
|
-
amount: ActivityAmount;
|
|
698
|
-
from?: string;
|
|
699
|
-
to?: string;
|
|
700
|
-
fee?: ActivityAmount;
|
|
701
|
-
success?: boolean;
|
|
702
|
-
metadata: ActivityLogMetadata;
|
|
703
|
-
rawEvent: OnChainEvent;
|
|
704
|
-
}
|
|
705
|
-
|
|
706
|
-
interface ActivityLogMetadata {
|
|
707
|
-
transactionHash?: string;
|
|
708
|
-
blockNumber?: bigint | number;
|
|
709
|
-
logIndex?: number;
|
|
710
|
-
}
|
|
711
|
-
```
|
|
712
|
-
|
|
713
646
|
## Error Handling
|
|
714
647
|
|
|
715
648
|
All SDK errors extend `ZamaError`. Use `instanceof` to catch specific error types:
|
|
@@ -815,11 +748,12 @@ Low-level FHE operations are available on the relayer backend via `sdk.relayer`:
|
|
|
815
748
|
|
|
816
749
|
## Constants
|
|
817
750
|
|
|
818
|
-
| Constant
|
|
819
|
-
|
|
|
820
|
-
| `ZERO_HANDLE`
|
|
821
|
-
| `ERC7984_INTERFACE_ID`
|
|
822
|
-
| `ERC7984_WRAPPER_INTERFACE_ID`
|
|
751
|
+
| Constant | Value | Description |
|
|
752
|
+
| ------------------------------------- | --------------------------------- | ---------------------------------------------------- |
|
|
753
|
+
| `ZERO_HANDLE` | `"0x0000...0000"` (32 zero bytes) | Sentinel for empty/zero encrypted values. |
|
|
754
|
+
| `ERC7984_INTERFACE_ID` | `"0x4958f2a4"` | ERC-165 interface ID for confidential tokens. |
|
|
755
|
+
| `ERC7984_WRAPPER_INTERFACE_ID` | `"0x1f1c62b2"` | ERC-165 interface ID for upgraded wrapper contracts. |
|
|
756
|
+
| `ERC7984_WRAPPER_INTERFACE_ID_LEGACY` | `"0xd04584ba"` | ERC-165 interface ID for legacy wrapper contracts. |
|
|
823
757
|
|
|
824
758
|
## Exported ABIs
|
|
825
759
|
|
package/dist/cjs/cleartext.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`./relayer.cjs`);let t=require(`viem`),n=require(`viem/accounts`),r=require(`viem/chains`);async function i(e,t=2){let n;for(let r=0;r<=t;r++)try{return await e()}catch(e){if(n=e,r<t&&a(e)){await o(500*2**r);continue}throw e}throw n}function a(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`timed out`)||t.includes(`timeout`)||t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`network`)||t.includes(`fetch failed`)||t.includes(`socket hang up`)||t.includes(`502`)||t.includes(`503`)||t.includes(`504`)}function o(e){return new Promise(t=>setTimeout(t,e))}const s={chainId:1,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org/v2`,network:`https://ethereum-rpc.publicnode.com`,aclContractAddress:`0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6`,kmsContractAddress:`0x77627828a55156b04Ac0DC0eb30467f1a552BB03`,inputVerifierContractAddress:`0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xeb5015fF021DB115aCe010f23F55C2591059bBA0`},c={chainId:11155111,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org/v2`,network:`https://ethereum-sepolia-rpc.publicnode.com`,aclContractAddress:`0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D`,kmsContractAddress:`0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A`,inputVerifierContractAddress:`0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0x2f0750Bbb0A246059d80e94c454586a7F27a128e`},l={chainId:31337,gatewayChainId:10901,relayerUrl:``,network:`http://127.0.0.1:8545`,aclContractAddress:`0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D`,inputVerifierContractAddress:`0x36772142b74871f255CbD7A3e89B401d3e45825f`,kmsContractAddress:`0x901F8942346f7AB3a01F6D7613119Bca447Bb030`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:void 0},u={[s.chainId]:s,[c.chainId]:c,[l.chainId]:l},d={name:`string`,version:`string`,chainId:`uint256`,verifyingContract:`address`,salt:`bytes32`};function f(e){return Object.keys(d).filter(t=>t in e).map(e=>({name:e,type:d[e]}))}const p=(e,t)=>({name:`InputVerification`,version:`1`,chainId:Number(e),verifyingContract:t}),m=(e,t)=>({name:`Decryption`,version:`1`,chainId:Number(e),verifyingContract:t}),h={domain:p,types:{CiphertextVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`userAddress`,type:`address`},{name:`contractAddress`,type:`address`},{name:`contractChainId`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},g={domain:m,types:{PublicDecryptVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`decryptedResult`,type:`bytes`},{name:`extraData`,type:`bytes`}]}},_={domain:m,types:{UserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},v={domain:m,types:{DelegatedUserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`delegatorAddress`,type:`address`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},y={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},b={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},x={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(y),Object.freeze(b),Object.freeze(x),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function S(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function C(e){return typeof e==`string`?e in y:!1}function w(e){if(!C(e))throw Error(`Invalid FheType name '${e}'`);return y[e]}function T(e){if(!S(e))throw Error(`Invalid FheType id '${e}'`);let t=x[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const E=(0,t.toBytes)(`ZK-w_rct`),D=(0,t.toBytes)(`ZK-w_hdl`);function O(e,n){let r=Math.ceil(T(n)/8);return(0,t.toBytes)((0,t.pad)((0,t.toHex)(e),{size:r}))}function k(n,r,i){if(i.length!==32)throw new e.i(`random32 must be exactly 32 bytes`);let a=O(r,n),o=(0,t.keccak256)((0,t.concat)([(0,t.toHex)(new Uint8Array([n])),(0,t.toHex)(a),(0,t.toHex)(i)]));return(0,t.keccak256)((0,t.concat)([(0,t.toHex)(E),o]))}function A(n,r,i,a,o){if(!Number.isInteger(r)||r<0||r>255)throw new e.i(`index must be an integer between 0 and 255`);let s=(0,t.keccak256)((0,t.concat)([(0,t.toHex)(E),n])),c=(0,t.keccak256)((0,t.encodePacked)([`bytes`,`bytes32`,`uint8`,`address`,`uint256`],[(0,t.toHex)(D),s,r,a,o])),l=o&18446744073709551615n;return(0,t.toHex)(BigInt(c)&115792089237316195423570985008687907853269984665640254554447762662844404858880n|BigInt(r)<<80n|l<<16n|BigInt(i)<<8n|BigInt(0),{size:32})}const j=(0,t.parseAbi)([`function persistAllowed(bytes32 handle, address account) view returns (bool)`,`function isAllowedForDecryption(bytes32 handle) view returns (bool)`,`function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)`]),M=(0,t.parseAbi)([`function plaintexts(bytes32 handle) view returns (uint256)`]),N=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`}],P={EIP712Domain:N,UserDecryptRequestVerification:_.types.UserDecryptRequestVerification},F={EIP712Domain:N,DelegatedUserDecryptRequestVerification:v.types.DelegatedUserDecryptRequestVerification},I={EIP712Domain:N,PublicDecryptVerification:g.types.PublicDecryptVerification},L=new Set([r.mainnet.id,r.sepolia.id]);function R(e,n){let r=Number(BigInt(e)>>8n&255n);return r===0?n!==0n:r===7?(0,t.toHex)(n,{size:20}):n}function z(n){if(!C(n.type))throw new e.i(`Unsupported FHE type`);let r=w(n.type),i;if(n.type===`ebool`){if(typeof n.value==`boolean`)i=n.value?1n:0n;else if(i=n.value,i!==0n&&i!==1n)throw new e.i(`Bool value must be 0, 1, true, or false`)}else i=n.type===`eaddress`?BigInt((0,t.getAddress)(n.value)):n.value;if(i<0n)throw new e.i(`Only non-negative cleartext values are supported`);let a=T(r),o=(1n<<BigInt(a))-1n;if(i>o)throw new e.i(`Value ${i} exceeds max ${o} for FheType ${r}`);return{fheType:r,value:i}}var B=class{#e;#t;kmsSigner;inputSigner;constructor(r){if(L.has(r.chainId))throw new e.t(`Cleartext mode is not allowed on chain ${r.chainId}. It is intended for local development and testing only.`);this.#e=(0,t.createPublicClient)({transport:typeof r.network==`string`?(0,t.http)(r.network):(0,t.custom)(r.network)}),this.#t=r,this.kmsSigner=(0,n.privateKeyToAccount)(r.kmsSignerPrivateKey??`0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91`),this.inputSigner=(0,n.privateKeyToAccount)(r.inputSignerPrivateKey??`0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901`)}async generateKeypair(){let e=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32))),n=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32)));for(;n===e;)n=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:e,privateKey:n}}async createEIP712(e,t,n,r=7){return{domain:_.domain(this.#t.chainId,this.#t.verifyingContractAddressDecryption),types:P,primaryType:`UserDecryptRequestVerification`,message:{publicKey:e,contractAddresses:t,startTimestamp:BigInt(n),durationDays:BigInt(r),extraData:`0x00`}}}async encrypt(e){let n=e.values.map(z),r=(0,t.getAddress)(e.contractAddress),i=(0,t.getAddress)(e.userAddress),a=n.map(({fheType:e,value:t})=>k(e,t,crypto.getRandomValues(new Uint8Array(32)))),o=(0,t.keccak256)(a.length>0?(0,t.concat)(a):`0x`),s=n.map(({fheType:e},t)=>A(o,t,e,this.#t.aclContractAddress,BigInt(this.#t.chainId))),c=n.map(({value:e})=>(0,t.pad)((0,t.toHex)(e),{size:32})),l=c.length>0?(0,t.concat)(c):`0x`,u=await this.inputSigner.signTypedData({domain:h.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressInputVerification),types:{CiphertextVerification:h.types.CiphertextVerification},primaryType:`CiphertextVerification`,message:{ctHandles:s,userAddress:i,contractAddress:r,contractChainId:BigInt(this.#t.chainId),extraData:l}}),d=(0,t.toBytes)((0,t.concat)([(0,t.toHex)(new Uint8Array([s.length])),(0,t.toHex)(new Uint8Array([1])),...s,u,l]));return{handles:s.map(e=>(0,t.toBytes)(e)),inputProof:d}}async userDecrypt(e){return await this.#r(e.handles,(0,t.getAddress)(e.signerAddress),(0,t.getAddress)(e.contractAddress),`User`,`user decrypt`),this.#n(e.handles)}async publicDecrypt(n){let r=n,i=(await Promise.all(r.map(e=>this.#o(e)))).findIndex(e=>!e);if(i!==-1)throw new e.r(`Handle ${r[i]} is not allowed for public decryption`);let a=await Promise.all(r.map(e=>this.#s(e))),o=Object.fromEntries(r.map((e,t)=>[e,R(e,a[t])])),s=(0,t.concat)(a.map(e=>(0,t.pad)((0,t.toHex)(e),{size:32}))),c=await this.kmsSigner.signTypedData({domain:g.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressDecryption),types:I,primaryType:`PublicDecryptVerification`,message:{ctHandles:r,decryptedResult:s,extraData:`0x`}});return{clearValues:o,abiEncodedClearValues:s,decryptionProof:(0,t.concat)([(0,t.toHex)(new Uint8Array([1])),c])}}async createDelegatedUserDecryptEIP712(e,n,r,i,a=7){let o={publicKey:e,contractAddresses:n,delegatorAddress:(0,t.getAddress)(r),startTimestamp:String(i),durationDays:String(a),extraData:`0x00`};return{domain:v.domain(BigInt(this.#t.chainId),this.#t.verifyingContractAddressDecryption),types:F,primaryType:`DelegatedUserDecryptRequestVerification`,message:o}}async delegatedUserDecrypt(e){return await this.#i(e.handles,(0,t.getAddress)(e.delegatorAddress),(0,t.getAddress)(e.delegateAddress),(0,t.getAddress)(e.contractAddress)),this.#n(e.handles)}async requestZKProofVerification(t){throw new e.t(`Not implemented in cleartext mode`)}async getPublicKey(){return{publicKeyId:`mock-public-key-id`,publicKey:new Uint8Array([32])}}async getPublicParams(e){return{publicParams:new Uint8Array([32]),publicParamsId:`mock-public-params-id`}}async getAclAddress(){return this.#t.aclContractAddress}terminate(){}[Symbol.dispose](){this.terminate()}async#n(e){let t=await Promise.all(e.map(e=>this.#s(e)));return Object.fromEntries(e.map((e,n)=>[e,R(e,t[n])]))}async#r(t,n,r,i,a){if(n===r)throw new e.r(`${i} address ${n} must not equal contract address for ${a}`);let o=await Promise.all(t.flatMap(e=>[this.#a(e,n),this.#a(e,r)]));for(let s=0;s<t.length;s++){let c=o[s*2],l=o[s*2+1];if(!c)throw new e.r(`${i} ${n} is not authorized for ${a} of handle ${t[s]}`);if(!l)throw new e.r(`Contract ${r} is not authorized for ${a} of handle ${t[s]}`)}}async#i(t,n,r,i){let a=await Promise.all(t.map(e=>this.#e.readContract({address:this.#t.aclContractAddress,abi:j,functionName:`isHandleDelegatedForUserDecryption`,args:[n,r,i,e]})));for(let n=0;n<t.length;n++)if(!a[n])throw new e.r(`Handle ${t[n]} is not delegated for user decryption`)}async#a(e,t){return this.#e.readContract({address:this.#t.aclContractAddress,abi:j,functionName:`persistAllowed`,args:[e,t]})}async#o(e){return this.#e.readContract({address:this.#t.aclContractAddress,abi:j,functionName:`isAllowedForDecryption`,args:[e]})}async#s(e){return this.#e.readContract({address:this.#t.executorAddress,abi:M,functionName:`plaintexts`,args:[e]})}};const V={...l,executorAddress:`0xe3a9105a3a932253A70F126eb1E3b589C643dD24`},H={chainId:560048,network:`https://rpc.hoodi.ethpandaops.io`,gatewayChainId:l.gatewayChainId,aclContractAddress:`0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68`,executorAddress:`0xC316692627de536368d82e9121F1D44a550894E6`,verifyingContractAddressDecryption:l.verifyingContractAddressDecryption,verifyingContractAddressInputVerification:l.verifyingContractAddressInputVerification,registryAddress:`0x1807aE2f693F8530DFB126D0eF98F2F2518F292f`};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return f}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return V}});
|
|
1
|
+
const e=require(`./relayer.cjs`);let t=require(`viem`),n=require(`viem/accounts`),r=require(`viem/chains`);async function i(e,t=2){let n;for(let r=0;r<=t;r++)try{return await e()}catch(e){if(n=e,r<t&&a(e)){await o(500*2**r);continue}throw e}throw n}function a(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`timed out`)||t.includes(`timeout`)||t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`network`)||t.includes(`fetch failed`)||t.includes(`socket hang up`)||t.includes(`502`)||t.includes(`503`)||t.includes(`504`)}function o(e){return new Promise(t=>setTimeout(t,e))}const s={chainId:1,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org/v2`,network:`https://ethereum-rpc.publicnode.com`,aclContractAddress:`0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6`,kmsContractAddress:`0x77627828a55156b04Ac0DC0eb30467f1a552BB03`,inputVerifierContractAddress:`0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xeb5015fF021DB115aCe010f23F55C2591059bBA0`},c={chainId:11155111,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org/v2`,network:`https://ethereum-sepolia-rpc.publicnode.com`,aclContractAddress:`0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D`,kmsContractAddress:`0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A`,inputVerifierContractAddress:`0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0x2f0750Bbb0A246059d80e94c454586a7F27a128e`},l={chainId:31337,gatewayChainId:10901,relayerUrl:``,network:`http://127.0.0.1:8545`,aclContractAddress:`0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D`,inputVerifierContractAddress:`0x36772142b74871f255CbD7A3e89B401d3e45825f`,kmsContractAddress:`0x901F8942346f7AB3a01F6D7613119Bca447Bb030`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:void 0},u={[s.chainId]:s,[c.chainId]:c,[l.chainId]:l},d=(e,t)=>({name:`InputVerification`,version:`1`,chainId:BigInt(e),verifyingContract:t}),f=(e,t)=>({name:`Decryption`,version:`1`,chainId:BigInt(e),verifyingContract:t}),p={domain:d,types:{CiphertextVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`userAddress`,type:`address`},{name:`contractAddress`,type:`address`},{name:`contractChainId`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},m={domain:f,types:{PublicDecryptVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`decryptedResult`,type:`bytes`},{name:`extraData`,type:`bytes`}]}},h={domain:f,types:{UserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},g={domain:f,types:{DelegatedUserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`delegatorAddress`,type:`address`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},_={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},v={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},y={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(_),Object.freeze(v),Object.freeze(y),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function b(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function x(e){return typeof e==`string`?e in _:!1}function S(e){if(!x(e))throw Error(`Invalid FheType name '${e}'`);return _[e]}function C(e){if(!b(e))throw Error(`Invalid FheType id '${e}'`);let t=y[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const w=(0,t.toBytes)(`ZK-w_rct`),T=(0,t.toBytes)(`ZK-w_hdl`);function E(e,n){let r=Math.ceil(C(n)/8);return(0,t.toBytes)((0,t.pad)((0,t.toHex)(e),{size:r}))}function D(n,r,i){if(i.length!==32)throw new e.i(`random32 must be exactly 32 bytes`);let a=E(r,n),o=(0,t.keccak256)((0,t.concat)([(0,t.toHex)(new Uint8Array([n])),(0,t.toHex)(a),(0,t.toHex)(i)]));return(0,t.keccak256)((0,t.concat)([(0,t.toHex)(w),o]))}function O(n,r,i,a,o){if(!Number.isInteger(r)||r<0||r>255)throw new e.i(`index must be an integer between 0 and 255`);let s=(0,t.keccak256)((0,t.concat)([(0,t.toHex)(w),n])),c=(0,t.keccak256)((0,t.encodePacked)([`bytes`,`bytes32`,`uint8`,`address`,`uint256`],[(0,t.toHex)(T),s,r,a,o])),l=o&18446744073709551615n;return(0,t.toHex)(BigInt(c)&115792089237316195423570985008687907853269984665640254554447762662844404858880n|BigInt(r)<<80n|l<<16n|BigInt(i)<<8n|BigInt(0),{size:32})}const k=(0,t.parseAbi)([`function persistAllowed(bytes32 handle, address account) view returns (bool)`,`function isAllowedForDecryption(bytes32 handle) view returns (bool)`,`function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)`]),A=(0,t.parseAbi)([`function plaintexts(bytes32 handle) view returns (uint256)`]),j=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`}],M={EIP712Domain:j,UserDecryptRequestVerification:h.types.UserDecryptRequestVerification},N={EIP712Domain:j,DelegatedUserDecryptRequestVerification:g.types.DelegatedUserDecryptRequestVerification},P={EIP712Domain:j,PublicDecryptVerification:m.types.PublicDecryptVerification},F=new Set([r.mainnet.id,r.sepolia.id]);function I(e,n){let r=Number(BigInt(e)>>8n&255n);return r===0?n!==0n:r===7?(0,t.toHex)(n,{size:20}):n}function L(n){if(!x(n.type))throw new e.i(`Unsupported FHE type`);let r=S(n.type),i;if(n.type===`ebool`){if(typeof n.value==`boolean`)i=n.value?1n:0n;else if(i=n.value,i!==0n&&i!==1n)throw new e.i(`Bool value must be 0, 1, true, or false`)}else i=n.type===`eaddress`?BigInt((0,t.getAddress)(n.value)):n.value;if(i<0n)throw new e.i(`Only non-negative cleartext values are supported`);let a=C(r),o=(1n<<BigInt(a))-1n;if(i>o)throw new e.i(`Value ${i} exceeds max ${o} for FheType ${r}`);return{fheType:r,value:i}}var R=class{#e;#t;kmsSigner;inputSigner;constructor(r){if(F.has(r.chainId))throw new e.t(`Cleartext mode is not allowed on chain ${r.chainId}. It is intended for local development and testing only.`);this.#e=(0,t.createPublicClient)({transport:typeof r.network==`string`?(0,t.http)(r.network):(0,t.custom)(r.network)}),this.#t=r,this.kmsSigner=(0,n.privateKeyToAccount)(r.kmsSignerPrivateKey??`0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91`),this.inputSigner=(0,n.privateKeyToAccount)(r.inputSignerPrivateKey??`0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901`)}async generateKeypair(){let e=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32))),n=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32)));for(;n===e;)n=(0,t.toHex)(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:e,privateKey:n}}async createEIP712(e,t,n,r=7){return{domain:h.domain(this.#t.chainId,this.#t.verifyingContractAddressDecryption),types:M,primaryType:`UserDecryptRequestVerification`,message:{publicKey:e,contractAddresses:t,startTimestamp:String(n),durationDays:String(r),extraData:`0x00`}}}async encrypt(e){let n=e.values.map(L),r=(0,t.getAddress)(e.contractAddress),i=(0,t.getAddress)(e.userAddress),a=n.map(({fheType:e,value:t})=>D(e,t,crypto.getRandomValues(new Uint8Array(32)))),o=(0,t.keccak256)(a.length>0?(0,t.concat)(a):`0x`),s=n.map(({fheType:e},t)=>O(o,t,e,this.#t.aclContractAddress,BigInt(this.#t.chainId))),c=n.map(({value:e})=>(0,t.pad)((0,t.toHex)(e),{size:32})),l=c.length>0?(0,t.concat)(c):`0x`,u=await this.inputSigner.signTypedData({domain:p.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressInputVerification),types:{CiphertextVerification:p.types.CiphertextVerification},primaryType:`CiphertextVerification`,message:{ctHandles:s,userAddress:i,contractAddress:r,contractChainId:BigInt(this.#t.chainId),extraData:l}}),d=(0,t.toBytes)((0,t.concat)([(0,t.toHex)(new Uint8Array([s.length])),(0,t.toHex)(new Uint8Array([1])),...s,u,l]));return{handles:s.map(e=>(0,t.toBytes)(e)),inputProof:d}}async userDecrypt(e){return await this.#r(e.handles,(0,t.getAddress)(e.signerAddress),(0,t.getAddress)(e.contractAddress),`User`,`user decrypt`),this.#n(e.handles)}async publicDecrypt(n){let r=n,i=(await Promise.all(r.map(e=>this.#o(e)))).findIndex(e=>!e);if(i!==-1)throw new e.r(`Handle ${r[i]} is not allowed for public decryption`);let a=await Promise.all(r.map(e=>this.#s(e))),o=Object.fromEntries(r.map((e,t)=>[e,I(e,a[t])])),s=(0,t.concat)(a.map(e=>(0,t.pad)((0,t.toHex)(e),{size:32}))),c=await this.kmsSigner.signTypedData({domain:m.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressDecryption),types:P,primaryType:`PublicDecryptVerification`,message:{ctHandles:r,decryptedResult:s,extraData:`0x`}});return{clearValues:o,abiEncodedClearValues:s,decryptionProof:(0,t.concat)([(0,t.toHex)(new Uint8Array([1])),c])}}async createDelegatedUserDecryptEIP712(e,n,r,i,a=7){let o={publicKey:e,contractAddresses:n,delegatorAddress:(0,t.getAddress)(r),startTimestamp:String(i),durationDays:String(a),extraData:`0x00`};return{domain:g.domain(this.#t.chainId,this.#t.verifyingContractAddressDecryption),types:N,primaryType:`DelegatedUserDecryptRequestVerification`,message:o}}async delegatedUserDecrypt(e){return await this.#i(e.handles,(0,t.getAddress)(e.delegatorAddress),(0,t.getAddress)(e.delegateAddress),(0,t.getAddress)(e.contractAddress)),this.#n(e.handles)}async requestZKProofVerification(t){throw new e.t(`Not implemented in cleartext mode`)}async getPublicKey(){return{publicKeyId:`mock-public-key-id`,publicKey:new Uint8Array([32])}}async getPublicParams(e){return{publicParams:new Uint8Array([32]),publicParamsId:`mock-public-params-id`}}async getAclAddress(){return this.#t.aclContractAddress}terminate(){}[Symbol.dispose](){this.terminate()}async#n(e){let t=await Promise.all(e.map(e=>this.#s(e)));return Object.fromEntries(e.map((e,n)=>[e,I(e,t[n])]))}async#r(t,n,r,i,a){if(n===r)throw new e.r(`${i} address ${n} must not equal contract address for ${a}`);let o=await Promise.all(t.flatMap(e=>[this.#a(e,n),this.#a(e,r)]));for(let s=0;s<t.length;s++){let c=o[s*2],l=o[s*2+1];if(!c)throw new e.r(`${i} ${n} is not authorized for ${a} of handle ${t[s]}`);if(!l)throw new e.r(`Contract ${r} is not authorized for ${a} of handle ${t[s]}`)}}async#i(t,n,r,i){let a=await Promise.all(t.map(e=>this.#e.readContract({address:this.#t.aclContractAddress,abi:k,functionName:`isHandleDelegatedForUserDecryption`,args:[n,r,i,e]})));for(let n=0;n<t.length;n++)if(!a[n])throw new e.r(`Handle ${t[n]} is not delegated for user decryption`)}async#a(e,t){return this.#e.readContract({address:this.#t.aclContractAddress,abi:k,functionName:`persistAllowed`,args:[e,t]})}async#o(e){return this.#e.readContract({address:this.#t.aclContractAddress,abi:k,functionName:`isAllowedForDecryption`,args:[e]})}async#s(e){return this.#e.readContract({address:this.#t.executorAddress,abi:A,functionName:`plaintexts`,args:[e]})}};const z={...l,executorAddress:`0xe3a9105a3a932253A70F126eb1E3b589C643dD24`},B={chainId:560048,network:`https://rpc.hoodi.ethpandaops.io`,gatewayChainId:l.gatewayChainId,aclContractAddress:`0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68`,executorAddress:`0xC316692627de536368d82e9121F1D44a550894E6`,verifyingContractAddressDecryption:l.verifyingContractAddressDecryption,verifyingContractAddressInputVerification:l.verifyingContractAddressInputVerification,registryAddress:`0x1807aE2f693F8530DFB126D0eF98F2F2518F292f`};Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return z}});
|
|
2
2
|
//# sourceMappingURL=cleartext.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cleartext.cjs","names":["EncryptionFailedError","mainnet","sepolia","EncryptionFailedError","#client","#config","ConfigurationError","#assertDecryptAuthorization","#decryptHandles","#isAllowedForDecryption","DecryptionFailedError","#readPlaintext","#assertDelegation","#persistAllowed"],"sources":["../../src/relayer/relayer-utils.ts","../../src/relayer/cleartext/eip712.ts","../../src/relayer/cleartext/constants.ts","../../src/relayer/cleartext/fhe-type.ts","../../src/relayer/cleartext/handle.ts","../../src/relayer/cleartext/relayer-cleartext.ts","../../src/relayer/cleartext/presets.ts"],"sourcesContent":["import type { FhevmInstanceConfig } from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { Address } from \"viem\";\nimport type { EIP712TypedData } from \"./relayer-sdk.types\";\n\nconst MAX_RETRIES = 2;\nconst RETRY_BASE_MS = 500;\n\n/**\n * Retry an async operation with exponential backoff.\n * Only retries on transient errors (timeout, network). Does not retry user-facing errors.\n */\nexport async function withRetry<T>(fn: () => Promise<T>, retries = MAX_RETRIES): Promise<T> {\n let lastError: unknown;\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n if (attempt < retries && isTransientError(error)) {\n await sleep(RETRY_BASE_MS * 2 ** attempt);\n continue;\n }\n throw error;\n }\n }\n throw lastError;\n}\n\nfunction isTransientError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const msg = error.message.toLowerCase();\n return (\n msg.includes(\"timed out\") ||\n msg.includes(\"timeout\") ||\n msg.includes(\"econnreset\") ||\n msg.includes(\"econnrefused\") ||\n msg.includes(\"network\") ||\n msg.includes(\"fetch failed\") ||\n msg.includes(\"socket hang up\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\")\n );\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Extends the base relayer config with the on-chain wrappers registry address.\n *\n * Used by `DefaultConfigs` and the `WrappersRegistry` class to\n * resolve the correct registry contract per chain.\n */\nexport interface ExtendedFhevmInstanceConfig extends FhevmInstanceConfig {\n /**\n * Address of the `ConfidentialTokenWrappersRegistry` contract.\n * `undefined` for chains where no registry is deployed (e.g. Hardhat).\n */\n registryAddress: Address | undefined;\n}\n\n/**\n * Mainnet network configuration (chainId 1).\n *\n * Contract addresses mirror `MainnetConfigV2` from `@zama-fhe/relayer-sdk`.\n * They are duplicated here because the `/bundle` export path only exposes\n * types at build time (runtime values require `/web` or `/node` which pull\n * in WASM). `satisfies ExtendedFhevmInstanceConfig` ensures structural drift\n * is caught at compile time.\n *\n * Includes `registryAddress` for the on-chain token wrappers registry.\n */\nexport const MainnetConfig = {\n chainId: 1,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org/v2\",\n network: \"https://ethereum-rpc.publicnode.com\",\n aclContractAddress: \"0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6\",\n kmsContractAddress: \"0x77627828a55156b04Ac0DC0eb30467f1a552BB03\",\n inputVerifierContractAddress: \"0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xeb5015fF021DB115aCe010f23F55C2591059bBA0\",\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Sepolia testnet network configuration (chainId 11155111).\n *\n * See {@link MainnetConfig} for why addresses are hardcoded.\n * Includes `registryAddress` for the on-chain token wrappers registry.\n */\nexport const SepoliaConfig = {\n chainId: 11155111,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org/v2\",\n network: \"https://ethereum-sepolia-rpc.publicnode.com\",\n aclContractAddress: \"0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D\",\n kmsContractAddress: \"0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A\",\n inputVerifierContractAddress: \"0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0x2f0750Bbb0A246059d80e94c454586a7F27a128e\",\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n * Ensure that the executor address and other contract addresses correspond to\n * the contracts deployed on your Hardhat network.\n *\n * `registryAddress` is `undefined` — pass it explicitly via\n * `registryAddresses` when creating a `WrappersRegistry`.\n */\nexport const HardhatConfig = {\n chainId: 31337,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"http://127.0.0.1:8545\",\n aclContractAddress: \"0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D\",\n inputVerifierContractAddress: \"0x36772142b74871f255CbD7A3e89B401d3e45825f\",\n kmsContractAddress: \"0x901F8942346f7AB3a01F6D7613119Bca447Bb030\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: undefined,\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Built-in network configurations keyed by chain ID.\n *\n * Includes Mainnet (1), Sepolia (11155111), and Hardhat (31337).\n * Used by `RelayerWeb` to resolve transport configs and by\n * `WrappersRegistry` to resolve registry addresses.\n */\nexport const DefaultConfigs: Record<number, ExtendedFhevmInstanceConfig> = {\n [MainnetConfig.chainId]: MainnetConfig,\n [SepoliaConfig.chainId]: SepoliaConfig,\n [HardhatConfig.chainId]: HardhatConfig,\n} as const;\n\n/** EIP-712 domain field → Solidity type. Order follows the EIP-712 spec. */\nconst DOMAIN_FIELD_TYPES: Record<string, string> = {\n name: \"string\",\n version: \"string\",\n chainId: \"uint256\",\n verifyingContract: \"address\",\n salt: \"bytes32\",\n};\n\n/**\n * Build `EIP712Domain` type entries from the keys present in a domain object.\n * Order matches the EIP-712 spec (name → version → chainId → verifyingContract → salt).\n */\nexport function buildEIP712DomainType(\n domain: EIP712TypedData[\"domain\"],\n): { name: string; type: string }[] {\n return Object.keys(DOMAIN_FIELD_TYPES)\n .filter((k) => k in domain)\n .map((k) => ({ name: k, type: DOMAIN_FIELD_TYPES[k]! }));\n}\n","import type { Address, TypedDataDomain } from \"viem\";\nimport type {\n CoprocessorEIP712TypesType,\n KmsDelegatedUserDecryptEIP712TypesType,\n KmsPublicDecryptEIP712TypesType,\n KmsUserDecryptEIP712TypesType,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\ntype DomainFactory = (chainId: number | bigint, verifyingContract: Address) => TypedDataDomain;\n\nconst inputDomain: DomainFactory = (chainId, verifyingContract) => ({\n name: \"InputVerification\",\n version: \"1\",\n chainId: Number(chainId),\n verifyingContract,\n});\n\nconst decryptionDomain: DomainFactory = (chainId, verifyingContract) => ({\n name: \"Decryption\",\n version: \"1\",\n chainId: Number(chainId),\n verifyingContract,\n});\n\nexport const INPUT_VERIFICATION_EIP712 = {\n domain: inputDomain,\n types: {\n CiphertextVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"userAddress\", type: \"address\" },\n { name: \"contractAddress\", type: \"address\" },\n { name: \"contractChainId\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const KMS_DECRYPTION_EIP712 = {\n domain: decryptionDomain,\n types: {\n PublicDecryptVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"decryptedResult\", type: \"bytes\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n UserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const DELEGATED_USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n DelegatedUserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"delegatorAddress\", type: \"address\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\n// ── Compile-time structural checks against relayer-sdk types ──────────\n// These assertions ensure our local EIP-712 type arrays stay in sync with\n// the relayer-sdk's canonical definitions. A mismatch will cause a build error.\ntype AssertFieldsMatch<\n Local extends readonly { readonly name: string; readonly type: string }[],\n Canonical extends readonly { readonly name: string; readonly type: string }[],\n> = [Local[\"length\"]] extends [Canonical[\"length\"]]\n ? {\n [K in keyof Local]: Local[K] extends { readonly name: infer N; readonly type: infer T }\n ? Canonical[K & keyof Canonical] extends { readonly name: N; readonly type: T }\n ? true\n : { error: `Field mismatch at index ${K & string}` }\n : never;\n }\n : { error: \"Field count mismatch\" };\n\n// Wrapping in readonly true[] ensures a mismatch produces a compile error\n// (not just an inert type alias that TypeScript silently accepts).\ntype AssertAllTrue<T extends readonly true[]> = T;\n\ntype _CheckInput = AssertAllTrue<\n AssertFieldsMatch<\n typeof INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n CoprocessorEIP712TypesType[\"CiphertextVerification\"]\n >\n>;\ntype _CheckPublicDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n KmsPublicDecryptEIP712TypesType[\"PublicDecryptVerification\"]\n >\n>;\ntype _CheckUserDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n KmsUserDecryptEIP712TypesType[\"UserDecryptRequestVerification\"]\n >\n>;\ntype _CheckDelegatedDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n KmsDelegatedUserDecryptEIP712TypesType[\"DelegatedUserDecryptRequestVerification\"]\n >\n>;\n","export const HANDLE_VERSION = 0;\n\nexport const PREHANDLE_MASK = 0xffffffffffffffffffffffffffffffffffffffffff0000000000000000000000n;\n\n// Constants used for instanciation of the cleartext FHEVM instance.\nexport const MOCK_INPUT_SIGNER_PK =\n \"0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901\";\nexport const MOCK_KMS_SIGNER_PK =\n \"0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91\";\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import { concat, encodePacked, keccak256, pad, toBytes, toHex, type Address, type Hex } from \"viem\";\nimport { HANDLE_VERSION, PREHANDLE_MASK } from \"./constants\";\nimport { encryptionBitsFromFheTypeId, type FheTypeId } from \"./fhe-type\";\nimport { EncryptionFailedError } from \"../../errors\";\n\nconst RAW_CT_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_rct\");\nconst HANDLE_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_hdl\");\n\nfunction cleartextToBytes(cleartext: bigint, fheType: FheTypeId): Uint8Array {\n const byteLength = Math.ceil(encryptionBitsFromFheTypeId(fheType) / 8);\n return toBytes(pad(toHex(cleartext), { size: byteLength }));\n}\n\nexport function computeMockCiphertext(\n fheType: FheTypeId,\n cleartext: bigint,\n random32: Uint8Array,\n): Hex {\n if (random32.length !== 32) {\n throw new EncryptionFailedError(\"random32 must be exactly 32 bytes\");\n }\n\n const clearBytes = cleartextToBytes(cleartext, fheType);\n const inner = keccak256(\n concat([toHex(new Uint8Array([fheType])), toHex(clearBytes), toHex(random32)]),\n );\n\n return keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), inner]));\n}\n\nexport function computeInputHandle(\n mockCiphertext: Hex,\n index: number,\n fheType: FheTypeId,\n aclAddress: Address,\n chainId: bigint,\n): Hex {\n if (!Number.isInteger(index) || index < 0 || index > 255) {\n throw new EncryptionFailedError(\"index must be an integer between 0 and 255\");\n }\n\n const blobHash = keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), mockCiphertext]));\n const handleHash = keccak256(\n encodePacked(\n [\"bytes\", \"bytes32\", \"uint8\", \"address\", \"uint256\"],\n [toHex(HANDLE_HASH_DOMAIN_SEPARATOR), blobHash, index, aclAddress, chainId],\n ),\n );\n\n const chainId64 = chainId & 0xffff_ffff_ffff_ffffn;\n const handle =\n (BigInt(handleHash) & PREHANDLE_MASK) |\n (BigInt(index) << 80n) |\n (chainId64 << 16n) |\n (BigInt(fheType) << 8n) |\n BigInt(HANDLE_VERSION);\n\n return toHex(handle, { size: 32 });\n}\n","import type { PrivateKeyAccount } from \"viem/accounts\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport {\n concat,\n createPublicClient,\n custom,\n getAddress,\n http,\n keccak256,\n pad,\n parseAbi,\n toBytes,\n toHex,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { mainnet, sepolia } from \"viem/chains\";\nimport type {\n InputProofBytesType,\n KeypairType,\n KmsDelegatedUserDecryptEIP712Type,\n KmsPublicDecryptEIP712Type,\n KmsUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { RelayerSDK } from \"../relayer-sdk\";\nimport type {\n ClearValueType,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n Handle,\n PublicDecryptResult,\n UserDecryptParams,\n} from \"../relayer-sdk.types\";\nimport {\n DELEGATED_USER_DECRYPT_EIP712,\n INPUT_VERIFICATION_EIP712,\n KMS_DECRYPTION_EIP712,\n USER_DECRYPT_EIP712,\n} from \"./eip712\";\nimport { MOCK_INPUT_SIGNER_PK, MOCK_KMS_SIGNER_PK } from \"./constants\";\nimport {\n encryptionBitsFromFheTypeId,\n fheTypeIdFromName,\n isFheTypeName,\n type FheTypeId,\n} from \"./fhe-type\";\nimport { computeInputHandle, computeMockCiphertext } from \"./handle\";\nimport type { CleartextConfig } from \"./types\";\nimport { ConfigurationError, DecryptionFailedError, EncryptionFailedError } from \"../../errors\";\n\nconst ACL_ABI = parseAbi([\n \"function persistAllowed(bytes32 handle, address account) view returns (bool)\",\n \"function isAllowedForDecryption(bytes32 handle) view returns (bool)\",\n \"function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)\",\n]);\n\nconst EXECUTOR_ABI = parseAbi([\"function plaintexts(bytes32 handle) view returns (uint256)\"]);\n\nconst STANDARD_EIP712_DOMAIN = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nconst USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n UserDecryptRequestVerification: USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n} satisfies KmsUserDecryptEIP712Type[\"types\"];\nconst DELEGATED_USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n DelegatedUserDecryptRequestVerification:\n DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n} satisfies KmsDelegatedUserDecryptEIP712Type[\"types\"];\nconst KMS_DECRYPTION_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n PublicDecryptVerification: KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n} satisfies KmsPublicDecryptEIP712Type[\"types\"];\n\nconst FORBIDDEN_CHAIN_IDS = new Set<number>([mainnet.id, sepolia.id]);\n\n// FheTypeId constants for hot-path comparisons\nconst EBOOL_ID: FheTypeId = 0;\nconst EADDRESS_ID: FheTypeId = 7;\n\nfunction decodeClearValueType(handle: Handle, rawValue: bigint): ClearValueType {\n const typeByte = Number((BigInt(handle) >> 8n) & 0xffn);\n if (typeByte === EBOOL_ID) {\n return rawValue !== 0n;\n }\n if (typeByte === EADDRESS_ID) {\n return toHex(rawValue, { size: 20 });\n }\n return rawValue;\n}\n\nfunction normalizeEncryptValue(entry: EncryptParams[\"values\"][number]): {\n fheType: FheTypeId;\n value: bigint;\n} {\n if (!isFheTypeName(entry.type)) {\n throw new EncryptionFailedError(\"Unsupported FHE type\");\n }\n\n const fheType = fheTypeIdFromName(entry.type);\n\n let value: bigint;\n if (entry.type === \"ebool\") {\n if (typeof entry.value === \"boolean\") {\n value = entry.value ? 1n : 0n;\n } else {\n value = entry.value;\n if (value !== 0n && value !== 1n) {\n throw new EncryptionFailedError(\"Bool value must be 0, 1, true, or false\");\n }\n }\n } else if (entry.type === \"eaddress\") {\n value = BigInt(getAddress(entry.value));\n } else {\n value = entry.value;\n }\n\n if (value < 0n) {\n throw new EncryptionFailedError(\"Only non-negative cleartext values are supported\");\n }\n\n const bits = encryptionBitsFromFheTypeId(fheType);\n const maxValue = (1n << BigInt(bits)) - 1n;\n if (value > maxValue) {\n throw new EncryptionFailedError(\n `Value ${value} exceeds max ${maxValue} for FheType ${fheType}`,\n );\n }\n\n return { fheType, value };\n}\n\nexport class RelayerCleartext implements RelayerSDK, Disposable {\n readonly #client: PublicClient;\n readonly #config: CleartextConfig;\n readonly kmsSigner: PrivateKeyAccount;\n readonly inputSigner: PrivateKeyAccount;\n\n constructor(config: CleartextConfig) {\n if (FORBIDDEN_CHAIN_IDS.has(config.chainId)) {\n throw new ConfigurationError(\n `Cleartext mode is not allowed on chain ${config.chainId}. ` +\n `It is intended for local development and testing only.`,\n );\n }\n this.#client = createPublicClient({\n transport: typeof config.network === \"string\" ? http(config.network) : custom(config.network),\n });\n this.#config = config;\n this.kmsSigner = privateKeyToAccount(config.kmsSignerPrivateKey ?? MOCK_KMS_SIGNER_PK);\n this.inputSigner = privateKeyToAccount(config.inputSignerPrivateKey ?? MOCK_INPUT_SIGNER_PK);\n }\n\n async generateKeypair(): Promise<KeypairType<Hex>> {\n const publicKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n let privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n\n while (privateKey === publicKey) {\n privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n }\n\n return { publicKey, privateKey };\n }\n\n async createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays = 7,\n ): Promise<EIP712TypedData> {\n return {\n domain: USER_DECRYPT_EIP712.domain(\n this.#config.chainId,\n this.#config.verifyingContractAddressDecryption,\n ) as EIP712TypedData[\"domain\"],\n types: USER_DECRYPT_TYPES,\n primaryType: \"UserDecryptRequestVerification\",\n message: {\n publicKey,\n contractAddresses,\n startTimestamp: BigInt(startTimestamp),\n durationDays: BigInt(durationDays),\n extraData: \"0x00\",\n },\n };\n }\n\n async encrypt(params: EncryptParams): Promise<EncryptResult> {\n const entries = params.values.map(normalizeEncryptValue);\n const contractAddress = getAddress(params.contractAddress);\n const userAddress = getAddress(params.userAddress);\n\n const mockCiphertexts = entries.map(({ fheType, value }) =>\n computeMockCiphertext(fheType, value, crypto.getRandomValues(new Uint8Array(32))),\n );\n\n const ciphertextBlob = keccak256(mockCiphertexts.length > 0 ? concat(mockCiphertexts) : \"0x\");\n\n const handles = entries.map(({ fheType }, index) =>\n computeInputHandle(\n ciphertextBlob,\n index,\n fheType,\n this.#config.aclContractAddress,\n BigInt(this.#config.chainId),\n ),\n );\n\n const cleartextParts = entries.map(({ value }) => pad(toHex(value), { size: 32 }));\n const cleartextBytes: Hex = cleartextParts.length > 0 ? concat(cleartextParts) : \"0x\";\n\n const signature = await this.inputSigner.signTypedData({\n domain: INPUT_VERIFICATION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressInputVerification,\n ),\n types: {\n CiphertextVerification: INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n },\n primaryType: \"CiphertextVerification\",\n message: {\n ctHandles: handles,\n userAddress,\n contractAddress,\n contractChainId: BigInt(this.#config.chainId),\n extraData: cleartextBytes,\n },\n });\n\n const inputProof = toBytes(\n concat([\n toHex(new Uint8Array([handles.length])),\n toHex(new Uint8Array([1])),\n ...handles,\n signature,\n cleartextBytes,\n ]),\n );\n\n return {\n handles: handles.map((handle) => toBytes(handle)),\n inputProof,\n };\n }\n\n async userDecrypt(params: UserDecryptParams): Promise<Readonly<Record<Handle, ClearValueType>>> {\n await this.#assertDecryptAuthorization(\n params.handles,\n getAddress(params.signerAddress),\n getAddress(params.contractAddress),\n \"User\",\n \"user decrypt\",\n );\n\n return this.#decryptHandles(params.handles);\n }\n\n async publicDecrypt(handles: Handle[]): Promise<PublicDecryptResult> {\n const normalizedHandles = handles;\n\n const allowedResults = await Promise.all(\n normalizedHandles.map((handle) => this.#isAllowedForDecryption(handle)),\n );\n const unauthorizedIndex = allowedResults.findIndex((isAllowed) => !isAllowed);\n if (unauthorizedIndex !== -1) {\n throw new DecryptionFailedError(\n `Handle ${normalizedHandles[unauthorizedIndex]!} is not allowed for public decryption`,\n );\n }\n\n const orderedValues = await Promise.all(\n normalizedHandles.map((handle) => this.#readPlaintext(handle)),\n );\n const clearValues: PublicDecryptResult[\"clearValues\"] = Object.fromEntries(\n normalizedHandles.map((handle, index) => [\n handle,\n decodeClearValueType(handle, orderedValues[index]!),\n ]),\n );\n\n const abiEncodedClearValues = concat(orderedValues.map((v) => pad(toHex(v), { size: 32 })));\n\n const signature = await this.kmsSigner.signTypedData({\n domain: KMS_DECRYPTION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressDecryption,\n ) as KmsPublicDecryptEIP712Type[\"domain\"],\n types: KMS_DECRYPTION_TYPES,\n primaryType: \"PublicDecryptVerification\",\n message: {\n ctHandles: normalizedHandles,\n decryptedResult: abiEncodedClearValues,\n extraData: \"0x\",\n },\n });\n\n const decryptionProof = concat([toHex(new Uint8Array([1])), signature]);\n\n return {\n clearValues,\n abiEncodedClearValues,\n decryptionProof,\n };\n }\n\n async createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays = 7,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n const message: KmsDelegatedUserDecryptEIP712Type[\"message\"] = {\n publicKey: publicKey as KmsDelegatedUserDecryptEIP712Type[\"message\"][\"publicKey\"],\n contractAddresses,\n delegatorAddress: getAddress(delegatorAddress),\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n };\n\n return {\n domain: DELEGATED_USER_DECRYPT_EIP712.domain(\n BigInt(this.#config.chainId),\n this.#config.verifyingContractAddressDecryption,\n ) as KmsDelegatedUserDecryptEIP712Type[\"domain\"],\n types: DELEGATED_USER_DECRYPT_TYPES,\n primaryType: \"DelegatedUserDecryptRequestVerification\",\n message,\n };\n }\n\n async delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<Handle, ClearValueType>>> {\n await this.#assertDelegation(\n params.handles,\n getAddress(params.delegatorAddress),\n getAddress(params.delegateAddress),\n getAddress(params.contractAddress),\n );\n\n return this.#decryptHandles(params.handles);\n }\n\n async requestZKProofVerification(_zkProof: ZKProofLike): Promise<InputProofBytesType> {\n throw new ConfigurationError(\"Not implemented in cleartext mode\");\n }\n\n async getPublicKey(): Promise<{ publicKeyId: string; publicKey: Uint8Array } | null> {\n return { publicKeyId: \"mock-public-key-id\", publicKey: new Uint8Array([32]) };\n }\n\n async getPublicParams(\n _bits: number,\n ): Promise<{ publicParams: Uint8Array; publicParamsId: string } | null> {\n return { publicParams: new Uint8Array([32]), publicParamsId: \"mock-public-params-id\" };\n }\n\n async getAclAddress(): Promise<Address> {\n return this.#config.aclContractAddress;\n }\n\n terminate(): void {\n // No resources to release in cleartext mode.\n }\n\n /** Calls {@link terminate} (no-op in cleartext mode). */\n [Symbol.dispose](): void {\n this.terminate();\n }\n\n async #decryptHandles(\n normalizedHandles: Handle[],\n ): Promise<Readonly<Record<Handle, ClearValueType>>> {\n const values = await Promise.all(\n normalizedHandles.map((handle) => this.#readPlaintext(handle)),\n );\n\n return Object.fromEntries(\n normalizedHandles.map((handle, index) => [\n handle,\n decodeClearValueType(handle, values[index]!),\n ]),\n );\n }\n\n async #assertDecryptAuthorization(\n normalizedHandles: Handle[],\n actorAddress: Address,\n contractAddress: Address,\n actorLabel: \"User\" | \"Delegator\",\n operationLabel: \"user decrypt\" | \"delegated decrypt\",\n ): Promise<void> {\n if (actorAddress === contractAddress) {\n throw new DecryptionFailedError(\n `${actorLabel} address ${actorAddress} must not equal contract address for ${operationLabel}`,\n );\n }\n\n const results = await Promise.all(\n normalizedHandles.flatMap((handle) => [\n this.#persistAllowed(handle, actorAddress),\n this.#persistAllowed(handle, contractAddress),\n ]),\n );\n\n for (let i = 0; i < normalizedHandles.length; i++) {\n const actorAllowed = results[i * 2];\n const contractAllowed = results[i * 2 + 1];\n if (!actorAllowed) {\n throw new DecryptionFailedError(\n `${actorLabel} ${actorAddress} is not authorized for ${operationLabel} of handle ${normalizedHandles[i]!}`,\n );\n }\n if (!contractAllowed) {\n throw new DecryptionFailedError(\n `Contract ${contractAddress} is not authorized for ${operationLabel} of handle ${normalizedHandles[i]!}`,\n );\n }\n }\n }\n\n async #assertDelegation(\n handles: Handle[],\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n ): Promise<void> {\n const results = await Promise.all(\n handles.map((handle) =>\n this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, handle],\n }),\n ),\n );\n\n for (let i = 0; i < handles.length; i++) {\n if (!results[i]) {\n throw new DecryptionFailedError(\n `Handle ${handles[i]!} is not delegated for user decryption`,\n );\n }\n }\n }\n\n async #persistAllowed(handle: Handle, account: Address): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"persistAllowed\",\n args: [handle, account],\n });\n }\n\n async #isAllowedForDecryption(handle: Handle): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"isAllowedForDecryption\",\n args: [handle],\n });\n }\n\n async #readPlaintext(handle: Handle): Promise<bigint> {\n return this.#client.readContract({\n address: this.#config.executorAddress as Address,\n abi: EXECUTOR_ABI,\n functionName: \"plaintexts\",\n args: [handle],\n });\n }\n}\n","import { HardhatConfig } from \"../relayer-utils\";\nimport type { CleartextConfig } from \"./types\";\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n * Ensure that the executor address and other contract addresses correspond to\n * the contracts deployed on your Hardhat network.\n */\nexport const hardhatCleartextConfig = {\n ...HardhatConfig,\n executorAddress: \"0xe3a9105a3a932253A70F126eb1E3b589C643dD24\",\n} satisfies CleartextConfig;\n\nexport const hoodiCleartextConfig = {\n chainId: 560048,\n network: \"https://rpc.hoodi.ethpandaops.io\",\n gatewayChainId: HardhatConfig.gatewayChainId,\n aclContractAddress: \"0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68\",\n executorAddress: \"0xC316692627de536368d82e9121F1D44a550894E6\",\n // The values used when configuring the deployments are the same as those used for a hardhat deployment, since there's no gateway chain.\n verifyingContractAddressDecryption: HardhatConfig.verifyingContractAddressDecryption,\n verifyingContractAddressInputVerification:\n HardhatConfig.verifyingContractAddressInputVerification,\n registryAddress: \"0x1807aE2f693F8530DFB126D0eF98F2F2518F292f\",\n} satisfies CleartextConfig;\n"],"mappings":"2GAWA,eAAsB,EAAa,EAAsB,EAAU,EAAyB,CAC1F,IAAI,EACJ,IAAK,IAAI,EAAU,EAAG,GAAW,EAAS,IACxC,GAAI,CACF,OAAO,MAAM,GAAI,OACV,EAAO,CAEd,GADA,EAAY,EACR,EAAU,GAAW,EAAiB,EAAM,CAAE,CAChD,MAAM,EAAM,IAAgB,GAAK,EAAQ,CACzC,SAEF,MAAM,EAGV,MAAM,EAGR,SAAS,EAAiB,EAAyB,CACjD,GAAI,EAAE,aAAiB,OACrB,MAAO,GAET,IAAM,EAAM,EAAM,QAAQ,aAAa,CACvC,OACE,EAAI,SAAS,YAAY,EACzB,EAAI,SAAS,UAAU,EACvB,EAAI,SAAS,aAAa,EAC1B,EAAI,SAAS,eAAe,EAC5B,EAAI,SAAS,UAAU,EACvB,EAAI,SAAS,eAAe,EAC5B,EAAI,SAAS,iBAAiB,EAC9B,E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,GAAI,CAAC,EAAQ,GACX,MAAM,IAAIA,EAAAA,EACR,UAAU,EAAQ,GAAI,uCACvB,CAKP,MAAA,EAAsB,EAAgB,EAAoC,CACxE,OAAO,MAAA,EAAa,aAAa,CAC/B,QAAS,MAAA,EAAa,mBACtB,IAAK,EACL,aAAc,iBACd,KAAM,CAAC,EAAQ,EAAQ,CACxB,CAAC,CAGJ,MAAA,EAA8B,EAAkC,CAC9D,OAAO,MAAA,EAAa,aAAa,CAC/B,QAAS,MAAA,EAAa,mBACtB,IAAK,EACL,aAAc,yBACd,KAAM,CAAC,EAAO,CACf,CAAC,CAGJ,MAAA,EAAqB,EAAiC,CACpD,OAAO,MAAA,EAAa,aAAa,CAC/B,QAAS,MAAA,EAAa,gBACtB,IAAK,EACL,aAAc,aACd,KAAM,CAAC,EAAO,CACf,CAAC,GCxdN,MAAa,EAAyB,CACpC,GAAG,EACH,gBAAiB,6CAClB,CAEY,EAAuB,CAClC,QAAS,OACT,QAAS,mCACT,eAAgB,EAAc,eAC9B,mBAAoB,6CACpB,gBAAiB,6CAEjB,mCAAoC,EAAc,mCAClD,0CACE,EAAc,0CAChB,gBAAiB,6CAClB"}
|
|
1
|
+
{"version":3,"file":"cleartext.cjs","names":["EncryptionFailedError","mainnet","sepolia","EncryptionFailedError","#client","#config","ConfigurationError","#assertDecryptAuthorization","#decryptHandles","#isAllowedForDecryption","DecryptionFailedError","#readPlaintext","#assertDelegation","#persistAllowed"],"sources":["../../src/relayer/relayer-utils.ts","../../src/relayer/cleartext/eip712.ts","../../src/relayer/cleartext/constants.ts","../../src/relayer/cleartext/fhe-type.ts","../../src/relayer/cleartext/handle.ts","../../src/relayer/cleartext/relayer-cleartext.ts","../../src/relayer/cleartext/presets.ts"],"sourcesContent":["import type { FhevmInstanceConfig } from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { Address } from \"viem\";\n\nconst MAX_RETRIES = 2;\nconst RETRY_BASE_MS = 500;\n\n/**\n * Retry an async operation with exponential backoff.\n * Only retries on transient errors (timeout, network). Does not retry user-facing errors.\n */\nexport async function withRetry<T>(fn: () => Promise<T>, retries = MAX_RETRIES): Promise<T> {\n let lastError: unknown;\n for (let attempt = 0; attempt <= retries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n if (attempt < retries && isTransientError(error)) {\n await sleep(RETRY_BASE_MS * 2 ** attempt);\n continue;\n }\n throw error;\n }\n }\n throw lastError;\n}\n\nfunction isTransientError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n const msg = error.message.toLowerCase();\n return (\n msg.includes(\"timed out\") ||\n msg.includes(\"timeout\") ||\n msg.includes(\"econnreset\") ||\n msg.includes(\"econnrefused\") ||\n msg.includes(\"network\") ||\n msg.includes(\"fetch failed\") ||\n msg.includes(\"socket hang up\") ||\n msg.includes(\"502\") ||\n msg.includes(\"503\") ||\n msg.includes(\"504\")\n );\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Extends the base relayer config with the on-chain wrappers registry address.\n *\n * Used by `DefaultConfigs` and the `WrappersRegistry` class to\n * resolve the correct registry contract per chain.\n */\nexport interface ExtendedFhevmInstanceConfig extends FhevmInstanceConfig {\n /**\n * Address of the `ConfidentialTokenWrappersRegistry` contract.\n * `undefined` for chains where no registry is deployed (e.g. Hardhat).\n */\n registryAddress: Address | undefined;\n}\n\n/**\n * Mainnet network configuration (chainId 1).\n *\n * Contract addresses mirror `MainnetConfigV2` from `@zama-fhe/relayer-sdk`.\n * They are duplicated here because the `/bundle` export path only exposes\n * types at build time (runtime values require `/web` or `/node` which pull\n * in WASM). `satisfies ExtendedFhevmInstanceConfig` ensures structural drift\n * is caught at compile time.\n *\n * Includes `registryAddress` for the on-chain token wrappers registry.\n */\nexport const MainnetConfig = {\n chainId: 1,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org/v2\",\n network: \"https://ethereum-rpc.publicnode.com\",\n aclContractAddress: \"0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6\",\n kmsContractAddress: \"0x77627828a55156b04Ac0DC0eb30467f1a552BB03\",\n inputVerifierContractAddress: \"0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xeb5015fF021DB115aCe010f23F55C2591059bBA0\",\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Sepolia testnet network configuration (chainId 11155111).\n *\n * See {@link MainnetConfig} for why addresses are hardcoded.\n * Includes `registryAddress` for the on-chain token wrappers registry.\n */\nexport const SepoliaConfig = {\n chainId: 11155111,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org/v2\",\n network: \"https://ethereum-sepolia-rpc.publicnode.com\",\n aclContractAddress: \"0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D\",\n kmsContractAddress: \"0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A\",\n inputVerifierContractAddress: \"0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0x2f0750Bbb0A246059d80e94c454586a7F27a128e\",\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n * Ensure that the executor address and other contract addresses correspond to\n * the contracts deployed on your Hardhat network.\n *\n * `registryAddress` is `undefined` — pass it explicitly via\n * `registryAddresses` when creating a `WrappersRegistry`.\n */\nexport const HardhatConfig = {\n chainId: 31337,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"http://127.0.0.1:8545\",\n aclContractAddress: \"0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D\",\n inputVerifierContractAddress: \"0x36772142b74871f255CbD7A3e89B401d3e45825f\",\n kmsContractAddress: \"0x901F8942346f7AB3a01F6D7613119Bca447Bb030\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: undefined,\n} as const satisfies ExtendedFhevmInstanceConfig;\n\n/**\n * Built-in network configurations keyed by chain ID.\n *\n * Includes Mainnet (1), Sepolia (11155111), and Hardhat (31337).\n * Used by `RelayerWeb` to resolve transport configs and by\n * `WrappersRegistry` to resolve registry addresses.\n */\nexport const DefaultConfigs: Record<number, ExtendedFhevmInstanceConfig> = {\n [MainnetConfig.chainId]: MainnetConfig,\n [SepoliaConfig.chainId]: SepoliaConfig,\n [HardhatConfig.chainId]: HardhatConfig,\n} as const;\n","import type { Address } from \"viem\";\nimport type {\n CoprocessorEIP712DomainType,\n CoprocessorEIP712TypesType,\n KmsDelegatedUserDecryptEIP712TypesType,\n KmsEIP712DomainType,\n KmsPublicDecryptEIP712TypesType,\n KmsUserDecryptEIP712TypesType,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nconst inputDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): CoprocessorEIP712DomainType => ({\n name: \"InputVerification\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nconst decryptionDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): KmsEIP712DomainType => ({\n name: \"Decryption\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nexport const INPUT_VERIFICATION_EIP712 = {\n domain: inputDomain,\n types: {\n CiphertextVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"userAddress\", type: \"address\" },\n { name: \"contractAddress\", type: \"address\" },\n { name: \"contractChainId\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const KMS_DECRYPTION_EIP712 = {\n domain: decryptionDomain,\n types: {\n PublicDecryptVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"decryptedResult\", type: \"bytes\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n UserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const DELEGATED_USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n DelegatedUserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"delegatorAddress\", type: \"address\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\n// ── Compile-time structural checks against relayer-sdk types ──────────\n// These assertions ensure our local EIP-712 type arrays stay in sync with\n// the relayer-sdk's canonical definitions. A mismatch will cause a build error.\ntype AssertFieldsMatch<\n Local extends readonly { readonly name: string; readonly type: string }[],\n Canonical extends readonly { readonly name: string; readonly type: string }[],\n> = [Local[\"length\"]] extends [Canonical[\"length\"]]\n ? {\n [K in keyof Local]: Local[K] extends { readonly name: infer N; readonly type: infer T }\n ? Canonical[K & keyof Canonical] extends { readonly name: N; readonly type: T }\n ? true\n : { error: `Field mismatch at index ${K & string}` }\n : never;\n }\n : { error: \"Field count mismatch\" };\n\n// Wrapping in readonly true[] ensures a mismatch produces a compile error\n// (not just an inert type alias that TypeScript silently accepts).\ntype AssertAllTrue<T extends readonly true[]> = T;\n\ntype _CheckInput = AssertAllTrue<\n AssertFieldsMatch<\n typeof INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n CoprocessorEIP712TypesType[\"CiphertextVerification\"]\n >\n>;\ntype _CheckPublicDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n KmsPublicDecryptEIP712TypesType[\"PublicDecryptVerification\"]\n >\n>;\ntype _CheckUserDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n KmsUserDecryptEIP712TypesType[\"UserDecryptRequestVerification\"]\n >\n>;\ntype _CheckDelegatedDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n KmsDelegatedUserDecryptEIP712TypesType[\"DelegatedUserDecryptRequestVerification\"]\n >\n>;\n","export const HANDLE_VERSION = 0;\n\nexport const PREHANDLE_MASK = 0xffffffffffffffffffffffffffffffffffffffffff0000000000000000000000n;\n\n// Constants used for instanciation of the cleartext FHEVM instance.\nexport const MOCK_INPUT_SIGNER_PK =\n \"0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901\";\nexport const MOCK_KMS_SIGNER_PK =\n \"0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91\";\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import { concat, encodePacked, keccak256, pad, toBytes, toHex, type Address, type Hex } from \"viem\";\nimport { HANDLE_VERSION, PREHANDLE_MASK } from \"./constants\";\nimport { encryptionBitsFromFheTypeId, type FheTypeId } from \"./fhe-type\";\nimport { EncryptionFailedError } from \"../../errors\";\n\nconst RAW_CT_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_rct\");\nconst HANDLE_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_hdl\");\n\nfunction cleartextToBytes(cleartext: bigint, fheType: FheTypeId): Uint8Array {\n const byteLength = Math.ceil(encryptionBitsFromFheTypeId(fheType) / 8);\n return toBytes(pad(toHex(cleartext), { size: byteLength }));\n}\n\nexport function computeMockCiphertext(\n fheType: FheTypeId,\n cleartext: bigint,\n random32: Uint8Array,\n): Hex {\n if (random32.length !== 32) {\n throw new EncryptionFailedError(\"random32 must be exactly 32 bytes\");\n }\n\n const clearBytes = cleartextToBytes(cleartext, fheType);\n const inner = keccak256(\n concat([toHex(new Uint8Array([fheType])), toHex(clearBytes), toHex(random32)]),\n );\n\n return keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), inner]));\n}\n\nexport function computeInputHandle(\n mockCiphertext: Hex,\n index: number,\n fheType: FheTypeId,\n aclAddress: Address,\n chainId: bigint,\n): Hex {\n if (!Number.isInteger(index) || index < 0 || index > 255) {\n throw new EncryptionFailedError(\"index must be an integer between 0 and 255\");\n }\n\n const blobHash = keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), mockCiphertext]));\n const handleHash = keccak256(\n encodePacked(\n [\"bytes\", \"bytes32\", \"uint8\", \"address\", \"uint256\"],\n [toHex(HANDLE_HASH_DOMAIN_SEPARATOR), blobHash, index, aclAddress, chainId],\n ),\n );\n\n const chainId64 = chainId & 0xffff_ffff_ffff_ffffn;\n const handle =\n (BigInt(handleHash) & PREHANDLE_MASK) |\n (BigInt(index) << 80n) |\n (chainId64 << 16n) |\n (BigInt(fheType) << 8n) |\n BigInt(HANDLE_VERSION);\n\n return toHex(handle, { size: 32 });\n}\n","import type { PrivateKeyAccount } from \"viem/accounts\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport {\n concat,\n createPublicClient,\n custom,\n getAddress,\n http,\n keccak256,\n pad,\n parseAbi,\n toBytes,\n toHex,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { mainnet, sepolia } from \"viem/chains\";\nimport type {\n InputProofBytesType,\n KeypairType,\n KmsDelegatedUserDecryptEIP712Type,\n KmsPublicDecryptEIP712Type,\n KmsUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { RelayerSDK } from \"../relayer-sdk\";\nimport type {\n ClearValueType,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n Handle,\n PublicDecryptResult,\n PublicKeyData,\n PublicParamsData,\n UserDecryptParams,\n} from \"../relayer-sdk.types\";\nimport {\n DELEGATED_USER_DECRYPT_EIP712,\n INPUT_VERIFICATION_EIP712,\n KMS_DECRYPTION_EIP712,\n USER_DECRYPT_EIP712,\n} from \"./eip712\";\nimport { MOCK_INPUT_SIGNER_PK, MOCK_KMS_SIGNER_PK } from \"./constants\";\nimport {\n encryptionBitsFromFheTypeId,\n fheTypeIdFromName,\n isFheTypeName,\n type FheTypeId,\n} from \"./fhe-type\";\nimport { computeInputHandle, computeMockCiphertext } from \"./handle\";\nimport type { CleartextConfig } from \"./types\";\nimport { ConfigurationError, DecryptionFailedError, EncryptionFailedError } from \"../../errors\";\n\nconst ACL_ABI = parseAbi([\n \"function persistAllowed(bytes32 handle, address account) view returns (bool)\",\n \"function isAllowedForDecryption(bytes32 handle) view returns (bool)\",\n \"function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)\",\n]);\n\nconst EXECUTOR_ABI = parseAbi([\"function plaintexts(bytes32 handle) view returns (uint256)\"]);\n\nconst STANDARD_EIP712_DOMAIN = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nconst USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n UserDecryptRequestVerification: USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n} satisfies KmsUserDecryptEIP712Type[\"types\"];\nconst DELEGATED_USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n DelegatedUserDecryptRequestVerification:\n DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n} satisfies KmsDelegatedUserDecryptEIP712Type[\"types\"];\nconst KMS_DECRYPTION_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n PublicDecryptVerification: KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n} satisfies KmsPublicDecryptEIP712Type[\"types\"];\n\nconst FORBIDDEN_CHAIN_IDS = new Set<number>([mainnet.id, sepolia.id]);\n\n// FheTypeId constants for hot-path comparisons\nconst EBOOL_ID: FheTypeId = 0;\nconst EADDRESS_ID: FheTypeId = 7;\n\nfunction decodeClearValueType(handle: Handle, rawValue: bigint): ClearValueType {\n const typeByte = Number((BigInt(handle) >> 8n) & 0xffn);\n if (typeByte === EBOOL_ID) {\n return rawValue !== 0n;\n }\n if (typeByte === EADDRESS_ID) {\n return toHex(rawValue, { size: 20 });\n }\n return rawValue;\n}\n\nfunction normalizeEncryptValue(entry: EncryptParams[\"values\"][number]): {\n fheType: FheTypeId;\n value: bigint;\n} {\n if (!isFheTypeName(entry.type)) {\n throw new EncryptionFailedError(\"Unsupported FHE type\");\n }\n\n const fheType = fheTypeIdFromName(entry.type);\n\n let value: bigint;\n if (entry.type === \"ebool\") {\n if (typeof entry.value === \"boolean\") {\n value = entry.value ? 1n : 0n;\n } else {\n value = entry.value;\n if (value !== 0n && value !== 1n) {\n throw new EncryptionFailedError(\"Bool value must be 0, 1, true, or false\");\n }\n }\n } else if (entry.type === \"eaddress\") {\n value = BigInt(getAddress(entry.value));\n } else {\n value = entry.value;\n }\n\n if (value < 0n) {\n throw new EncryptionFailedError(\"Only non-negative cleartext values are supported\");\n }\n\n const bits = encryptionBitsFromFheTypeId(fheType);\n const maxValue = (1n << BigInt(bits)) - 1n;\n if (value > maxValue) {\n throw new EncryptionFailedError(\n `Value ${value} exceeds max ${maxValue} for FheType ${fheType}`,\n );\n }\n\n return { fheType, value };\n}\n\nexport class RelayerCleartext implements RelayerSDK, Disposable {\n readonly #client: PublicClient;\n readonly #config: CleartextConfig;\n readonly kmsSigner: PrivateKeyAccount;\n readonly inputSigner: PrivateKeyAccount;\n\n constructor(config: CleartextConfig) {\n if (FORBIDDEN_CHAIN_IDS.has(config.chainId)) {\n throw new ConfigurationError(\n `Cleartext mode is not allowed on chain ${config.chainId}. ` +\n `It is intended for local development and testing only.`,\n );\n }\n this.#client = createPublicClient({\n transport: typeof config.network === \"string\" ? http(config.network) : custom(config.network),\n });\n this.#config = config;\n this.kmsSigner = privateKeyToAccount(config.kmsSignerPrivateKey ?? MOCK_KMS_SIGNER_PK);\n this.inputSigner = privateKeyToAccount(config.inputSignerPrivateKey ?? MOCK_INPUT_SIGNER_PK);\n }\n\n async generateKeypair(): Promise<KeypairType<Hex>> {\n const publicKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n let privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n\n while (privateKey === publicKey) {\n privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n }\n\n return { publicKey, privateKey };\n }\n\n async createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays = 7,\n ): Promise<EIP712TypedData> {\n return {\n domain: USER_DECRYPT_EIP712.domain(\n this.#config.chainId,\n this.#config.verifyingContractAddressDecryption,\n ),\n types: USER_DECRYPT_TYPES,\n primaryType: \"UserDecryptRequestVerification\",\n message: {\n publicKey,\n contractAddresses,\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n },\n };\n }\n\n async encrypt(params: EncryptParams): Promise<EncryptResult> {\n const entries = params.values.map(normalizeEncryptValue);\n const contractAddress = getAddress(params.contractAddress);\n const userAddress = getAddress(params.userAddress);\n\n const mockCiphertexts = entries.map(({ fheType, value }) =>\n computeMockCiphertext(fheType, value, crypto.getRandomValues(new Uint8Array(32))),\n );\n\n const ciphertextBlob = keccak256(mockCiphertexts.length > 0 ? concat(mockCiphertexts) : \"0x\");\n\n const handles = entries.map(({ fheType }, index) =>\n computeInputHandle(\n ciphertextBlob,\n index,\n fheType,\n this.#config.aclContractAddress,\n BigInt(this.#config.chainId),\n ),\n );\n\n const cleartextParts = entries.map(({ value }) => pad(toHex(value), { size: 32 }));\n const cleartextBytes: Hex = cleartextParts.length > 0 ? concat(cleartextParts) : \"0x\";\n\n const signature = await this.inputSigner.signTypedData({\n domain: INPUT_VERIFICATION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressInputVerification,\n ),\n types: {\n CiphertextVerification: INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n },\n primaryType: \"CiphertextVerification\",\n message: {\n ctHandles: handles,\n userAddress,\n contractAddress,\n contractChainId: BigInt(this.#config.chainId),\n extraData: cleartextBytes,\n },\n });\n\n const inputProof = toBytes(\n concat([\n toHex(new Uint8Array([handles.length])),\n toHex(new Uint8Array([1])),\n ...handles,\n signature,\n cleartextBytes,\n ]),\n );\n\n return {\n handles: handles.map((handle) => toBytes(handle)),\n inputProof,\n };\n }\n\n async userDecrypt(params: UserDecryptParams): Promise<Readonly<Record<Handle, ClearValueType>>> {\n await this.#assertDecryptAuthorization(\n params.handles,\n getAddress(params.signerAddress),\n getAddress(params.contractAddress),\n \"User\",\n \"user decrypt\",\n );\n\n return this.#decryptHandles(params.handles);\n }\n\n async publicDecrypt(handles: Handle[]): Promise<PublicDecryptResult> {\n const normalizedHandles = handles;\n\n const allowedResults = await Promise.all(\n normalizedHandles.map((handle) => this.#isAllowedForDecryption(handle)),\n );\n const unauthorizedIndex = allowedResults.findIndex((isAllowed) => !isAllowed);\n if (unauthorizedIndex !== -1) {\n throw new DecryptionFailedError(\n `Handle ${normalizedHandles[unauthorizedIndex]!} is not allowed for public decryption`,\n );\n }\n\n const orderedValues = await Promise.all(\n normalizedHandles.map((handle) => this.#readPlaintext(handle)),\n );\n const clearValues: PublicDecryptResult[\"clearValues\"] = Object.fromEntries(\n normalizedHandles.map((handle, index) => [\n handle,\n decodeClearValueType(handle, orderedValues[index]!),\n ]),\n );\n\n const abiEncodedClearValues = concat(orderedValues.map((v) => pad(toHex(v), { size: 32 })));\n\n const signature = await this.kmsSigner.signTypedData({\n domain: KMS_DECRYPTION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressDecryption,\n ),\n types: KMS_DECRYPTION_TYPES,\n primaryType: \"PublicDecryptVerification\",\n message: {\n ctHandles: normalizedHandles,\n decryptedResult: abiEncodedClearValues,\n extraData: \"0x\",\n },\n });\n\n const decryptionProof = concat([toHex(new Uint8Array([1])), signature]);\n\n return {\n clearValues,\n abiEncodedClearValues,\n decryptionProof,\n };\n }\n\n async createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays = 7,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n const message: KmsDelegatedUserDecryptEIP712Type[\"message\"] = {\n publicKey,\n contractAddresses,\n delegatorAddress: getAddress(delegatorAddress),\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n };\n\n return {\n domain: DELEGATED_USER_DECRYPT_EIP712.domain(\n this.#config.chainId,\n this.#config.verifyingContractAddressDecryption,\n ),\n types: DELEGATED_USER_DECRYPT_TYPES,\n primaryType: \"DelegatedUserDecryptRequestVerification\",\n message,\n };\n }\n\n async delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<Handle, ClearValueType>>> {\n await this.#assertDelegation(\n params.handles,\n getAddress(params.delegatorAddress),\n getAddress(params.delegateAddress),\n getAddress(params.contractAddress),\n );\n\n return this.#decryptHandles(params.handles);\n }\n\n async requestZKProofVerification(_zkProof: ZKProofLike): Promise<InputProofBytesType> {\n throw new ConfigurationError(\"Not implemented in cleartext mode\");\n }\n\n async getPublicKey(): Promise<PublicKeyData | null> {\n return { publicKeyId: \"mock-public-key-id\", publicKey: new Uint8Array([32]) };\n }\n\n async getPublicParams(_bits: number): Promise<PublicParamsData | null> {\n return { publicParams: new Uint8Array([32]), publicParamsId: \"mock-public-params-id\" };\n }\n\n async getAclAddress(): Promise<Address> {\n return this.#config.aclContractAddress;\n }\n\n terminate(): void {\n // No resources to release in cleartext mode.\n }\n\n /** Calls {@link terminate} (no-op in cleartext mode). */\n [Symbol.dispose](): void {\n this.terminate();\n }\n\n async #decryptHandles(\n normalizedHandles: Handle[],\n ): Promise<Readonly<Record<Handle, ClearValueType>>> {\n const values = await Promise.all(\n normalizedHandles.map((handle) => this.#readPlaintext(handle)),\n );\n\n return Object.fromEntries(\n normalizedHandles.map((handle, index) => [\n handle,\n decodeClearValueType(handle, values[index]!),\n ]),\n );\n }\n\n async #assertDecryptAuthorization(\n normalizedHandles: Handle[],\n actorAddress: Address,\n contractAddress: Address,\n actorLabel: \"User\" | \"Delegator\",\n operationLabel: \"user decrypt\" | \"delegated decrypt\",\n ): Promise<void> {\n if (actorAddress === contractAddress) {\n throw new DecryptionFailedError(\n `${actorLabel} address ${actorAddress} must not equal contract address for ${operationLabel}`,\n );\n }\n\n const results = await Promise.all(\n normalizedHandles.flatMap((handle) => [\n this.#persistAllowed(handle, actorAddress),\n this.#persistAllowed(handle, contractAddress),\n ]),\n );\n\n for (let i = 0; i < normalizedHandles.length; i++) {\n const actorAllowed = results[i * 2];\n const contractAllowed = results[i * 2 + 1];\n if (!actorAllowed) {\n throw new DecryptionFailedError(\n `${actorLabel} ${actorAddress} is not authorized for ${operationLabel} of handle ${normalizedHandles[i]!}`,\n );\n }\n if (!contractAllowed) {\n throw new DecryptionFailedError(\n `Contract ${contractAddress} is not authorized for ${operationLabel} of handle ${normalizedHandles[i]!}`,\n );\n }\n }\n }\n\n async #assertDelegation(\n handles: Handle[],\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n ): Promise<void> {\n const results = await Promise.all(\n handles.map((handle) =>\n this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, handle],\n }),\n ),\n );\n\n for (let i = 0; i < handles.length; i++) {\n if (!results[i]) {\n throw new DecryptionFailedError(\n `Handle ${handles[i]!} is not delegated for user decryption`,\n );\n }\n }\n }\n\n async #persistAllowed(handle: Handle, account: Address): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"persistAllowed\",\n args: [handle, account],\n });\n }\n\n async #isAllowedForDecryption(handle: Handle): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress,\n abi: ACL_ABI,\n functionName: \"isAllowedForDecryption\",\n args: [handle],\n });\n }\n\n async #readPlaintext(handle: Handle): Promise<bigint> {\n return this.#client.readContract({\n address: this.#config.executorAddress as Address,\n abi: EXECUTOR_ABI,\n functionName: \"plaintexts\",\n args: [handle],\n });\n }\n}\n","import { HardhatConfig } from \"../relayer-utils\";\nimport type { CleartextConfig } from \"./types\";\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n * Ensure that the executor address and other contract addresses correspond to\n * the contracts deployed on your Hardhat network.\n */\nexport const hardhatCleartextConfig = {\n ...HardhatConfig,\n executorAddress: \"0xe3a9105a3a932253A70F126eb1E3b589C643dD24\",\n} satisfies CleartextConfig;\n\nexport const hoodiCleartextConfig = {\n chainId: 560048,\n network: \"https://rpc.hoodi.ethpandaops.io\",\n gatewayChainId: HardhatConfig.gatewayChainId,\n aclContractAddress: \"0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68\",\n executorAddress: \"0xC316692627de536368d82e9121F1D44a550894E6\",\n // The values used when configuring the deployments are the same as those used for a hardhat deployment, since there's no gateway chain.\n verifyingContractAddressDecryption: HardhatConfig.verifyingContractAddressDecryption,\n verifyingContractAddressInputVerification:\n HardhatConfig.verifyingContractAddressInputVerification,\n registryAddress: \"0x1807aE2f693F8530DFB126D0eF98F2F2518F292f\",\n} satisfies CleartextConfig;\n"],"mappings":"2GAUA,eAAsB,EAAa,EAAsB,EAAU,EAAyB,CAC1F,IAAI,EACJ,IAAK,IAAI,EAAU,EAAG,GAAW,EAAS,IACxC,GAAI,CACF,OAAO,MAAM,GAAI,OACV,EAAO,CAEd,GADA,EAAY,EACR,EAAU,GAAW,EAAiB,EAAM,CAAE,CAChD,MAAM,EAAM,IAAgB,GAAK,EAAQ,CACzC,SAEF,MAAM,EAGV,MAAM,EAGR,SAAS,EAAiB,EAAyB,CACjD,GAAI,EAAE,aAAiB,OACrB,MAAO,GAET,IAAM,EAAM,EAAM,QAAQ,aAAa,CACvC,OACE,EAAI,SAAS,YAAY,EACzB,EAAI,SAAS,UAAU,EACvB,EAAI,SAAS,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AAa,CAC/B,QAAS,MAAA,EAAa,mBACtB,IAAK,EACL,aAAc,iBACd,KAAM,CAAC,EAAQ,EAAQ,CACxB,CAAC,CAGJ,MAAA,EAA8B,EAAkC,CAC9D,OAAO,MAAA,EAAa,aAAa,CAC/B,QAAS,MAAA,EAAa,mBACtB,IAAK,EACL,aAAc,yBACd,KAAM,CAAC,EAAO,CACf,CAAC,CAGJ,MAAA,EAAqB,EAAiC,CACpD,OAAO,MAAA,EAAa,aAAa,CAC/B,QAAS,MAAA,EAAa,gBACtB,IAAK,EACL,aAAc,aACd,KAAM,CAAC,EAAO,CACf,CAAC,GCxdN,MAAa,EAAyB,CACpC,GAAG,EACH,gBAAiB,6CAClB,CAEY,EAAuB,CAClC,QAAS,OACT,QAAS,mCACT,eAAgB,EAAc,eAC9B,mBAAoB,6CACpB,gBAAiB,6CAEjB,mCAAoC,EAAc,mCAClD,0CACE,EAAc,0CAChB,gBAAiB,6CAClB"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../wrappers-registry.cjs`),t=require(`../eip1193-subscribe.cjs`);let n=require(`viem`),r=require(`ethers`);var i=class{#e;#t;#n;constructor(e){if(`ethereum`in e){let t=new r.BrowserProvider(e.ethereum);this.#e=t.getSigner(),this.#t=t,this.#n=e.ethereum}else `signer`in e?(this.#e=Promise.resolve(e.signer),this.#t=e.signer.provider??void 0):this.#t=e.provider}async#r(){if(!this.#e)throw TypeError(`No signer configured — read-only mode`);return this.#e}#i(){if(!this.#t)throw TypeError(`Signer has no provider`);return this.#t}async getChainId(){let e=await this.#i().getNetwork();return Number(e.chainId)}async getAddress(){return(0,n.getAddress)(await(await this.#r()).getAddress())}async signTypedData(e){let t=await this.#r(),{domain:r,types:i,message:a}=e,{EIP712Domain:o,...s}=i,c=Object.fromEntries(Object.entries(s).map(([e,t])=>[e,[...t]])),l=await t.signTypedData(r,c,a);if(!(0,n.isHex)(l))throw TypeError(`Expected hex string, got: ${l}`);return l}async writeContract(e){let t=await this.#r(),i=new r.ethers.Contract(e.address,e.abi,t),a={};e.value!==void 0&&(a.value=e.value),e.gas!==void 0&&(a.gasLimit=e.gas);let o=await i[e.functionName](...e.args,a);if(!(0,n.isHex)(o.hash))throw TypeError(`Expected hex string, got: ${o.hash}`);return o.hash}async readContract(e){let t=this.#i();return new r.ethers.Contract(e.address,e.abi,t)[e.functionName](...e.args)}async getBlockTimestamp(){let e=await this.#i().getBlock(`latest`);if(!e)throw Error(`Failed to fetch latest block`);if(e.timestamp===null)throw Error(`Latest block has no timestamp`);return BigInt(e.timestamp)}async waitForTransactionReceipt(e){let t=await this.#i().waitForTransaction(e);if(!t)throw Error(`Transaction receipt not found`);return{logs:t.logs.map(e=>({topics:e.topics.filter(e=>e!==null),data:e.data}))}}subscribe(e){return t.t(this.#n,()=>this.getAddress(),e)}};function a(e){return{to:e.address,data:(0,n.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function o(e,t){let r=await e.call(a(t));if(!(0,n.isHex)(r))throw TypeError(`Expected hex string, got: ${r}`);return(0,n.decodeFunctionResult)({abi:t.abi,functionName:t.functionName,data:r})}async function s(e,t){let r=await e.sendTransaction(a(t));if(!(0,n.isHex)(r.hash))throw TypeError(`Expected hex string, got: ${r.hash}`);return r.hash}function c(t,n,r){return o(t,e.
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../wrappers-registry.cjs`),t=require(`../eip1193-subscribe.cjs`);let n=require(`viem`),r=require(`ethers`);var i=class{#e;#t;#n;constructor(e){if(`ethereum`in e){let t=new r.BrowserProvider(e.ethereum);this.#e=t.getSigner(),this.#t=t,this.#n=e.ethereum}else `signer`in e?(this.#e=Promise.resolve(e.signer),this.#t=e.signer.provider??void 0):this.#t=e.provider}async#r(){if(!this.#e)throw TypeError(`No signer configured — read-only mode`);return this.#e}#i(){if(!this.#t)throw TypeError(`Signer has no provider`);return this.#t}async getChainId(){let e=await this.#i().getNetwork();return Number(e.chainId)}async getAddress(){return(0,n.getAddress)(await(await this.#r()).getAddress())}async signTypedData(e){let t=await this.#r(),{domain:r,types:i,message:a}=e,{EIP712Domain:o,...s}=i,c=Object.fromEntries(Object.entries(s).map(([e,t])=>[e,[...t]])),l=await t.signTypedData(r,c,a);if(!(0,n.isHex)(l))throw TypeError(`Expected hex string, got: ${l}`);return l}async writeContract(e){let t=await this.#r(),i=new r.ethers.Contract(e.address,e.abi,t),a={};e.value!==void 0&&(a.value=e.value),e.gas!==void 0&&(a.gasLimit=e.gas);let o=await i[e.functionName](...e.args,a);if(!(0,n.isHex)(o.hash))throw TypeError(`Expected hex string, got: ${o.hash}`);return o.hash}async readContract(e){let t=this.#i();return new r.ethers.Contract(e.address,e.abi,t)[e.functionName](...e.args)}async getBlockTimestamp(){let e=await this.#i().getBlock(`latest`);if(!e)throw Error(`Failed to fetch latest block`);if(e.timestamp===null)throw Error(`Latest block has no timestamp`);return BigInt(e.timestamp)}async waitForTransactionReceipt(e){let t=await this.#i().waitForTransaction(e);if(!t)throw Error(`Transaction receipt not found`);return{logs:t.logs.map(e=>({topics:e.topics.filter(e=>e!==null),data:e.data}))}}subscribe(e){return t.t(this.#n,()=>this.getAddress(),e)}};function a(e){return{to:e.address,data:(0,n.encodeFunctionData)({abi:e.abi,functionName:e.functionName,args:e.args}),...e.gas===void 0?{}:{gasLimit:e.gas},...e.value===void 0?{}:{value:e.value}}}async function o(e,t){let r=await e.call(a(t));if(!(0,n.isHex)(r))throw TypeError(`Expected hex string, got: ${r}`);return(0,n.decodeFunctionResult)({abi:t.abi,functionName:t.functionName,data:r})}async function s(e,t){let r=await e.sendTransaction(a(t));if(!(0,n.isHex)(r.hash))throw TypeError(`Expected hex string, got: ${r.hash}`);return r.hash}function c(t,n,r){return o(t,e.m(n,r))}function l(t,n){return o(t,e.E(n))}function u(t,n,r){return o(t,e.p(n,r))}function d(t,n,r,i,a){return s(t,e.g(n,r,i,a))}function f(t,n,r,i,a,o){return s(t,e.S(n,r,i,a,o))}function p(t,n,r,i,a){return s(t,e.C(n,r,i,a))}function m(t,n,r,i,a){return s(t,e.w(n,r,i,a))}function h(t,n,r,i){return s(t,e.b(n,r,i))}function g(t,n,r,i){return s(t,e.D(n,r,i))}function _(t,n){return o(t,e.i(n))}function v(t,n){return o(t,e.a(n))}function y(t,n,r,i){return o(t,e.o(n,r,i))}function b(t,n,r){return o(t,e.r(n,r))}function x(t,n,r){return o(t,e.t(n,r))}function S(t,n,r){return o(t,e.n(n,r))}function C(t,n,r){return o(t,e.s(n,r))}exports.EthersSigner=i,Object.defineProperty(exports,`ProviderRpcError`,{enumerable:!0,get:function(){return n.ProviderRpcError}}),exports.readConfidentialBalanceOfContract=c,exports.readConfidentialTokenAddressContract=x,exports.readIsConfidentialTokenValidContract=C,exports.readSupportsInterfaceContract=u,exports.readTokenAddressContract=S,exports.readTokenPairContract=b,exports.readTokenPairsContract=_,exports.readTokenPairsLengthContract=v,exports.readTokenPairsSliceContract=y,exports.readUnderlyingTokenContract=l,exports.writeConfidentialTransferContract=d,exports.writeFinalizeUnwrapContract=m,exports.writeSetOperatorContract=h,exports.writeUnwrapContract=f,exports.writeUnwrapFromBalanceContract=p,exports.writeWrapContract=g;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#readProvider","#eip1193","BrowserProvider","#signerPromise","#requireSigner","#requireProvider","eip1193Subscribe","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/ethers/ethers-signer.ts","../../../src/ethers/contracts.ts"],"sourcesContent":["import { ethers, BrowserProvider, type Signer } from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport type { EIP712TypedData } from \"../relayer/relayer-sdk.types\";\nimport type {\n GenericSigner,\n ReadContractConfig,\n SignerLifecycleCallbacks,\n TransactionReceipt,\n WriteContractConfig,\n} from \"../types\";\nimport { eip1193Subscribe } from \"../token/eip1193-subscribe\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Three variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and `subscribe()` works automatically.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * `subscribe()` is not available since there is no EIP-1193 provider.\n *\n * - **Read-only** — `{ provider }`: pass an ethers `Provider` for read-only contract calls.\n * Signing and write operations will throw at runtime.\n */\nexport type EthersSignerConfig =\n | { ethereum: EIP1193Provider }\n | { signer: Signer }\n | { provider: ethers.Provider };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner implements GenericSigner {\n #signerPromise?: Promise<Signer>;\n readonly #readProvider?: ethers.Provider;\n readonly #eip1193?: EIP1193Provider;\n\n constructor(config: EthersSignerConfig) {\n if (\"ethereum\" in config) {\n const browserProvider = new BrowserProvider(config.ethereum);\n this.#signerPromise = browserProvider.getSigner();\n this.#readProvider = browserProvider;\n this.#eip1193 = config.ethereum;\n } else if (\"signer\" in config) {\n this.#signerPromise = Promise.resolve(config.signer);\n this.#readProvider = config.signer.provider ?? undefined;\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n async #requireSigner(): Promise<Signer> {\n if (!this.#signerPromise) {\n throw new TypeError(\"No signer configured — read-only mode\");\n }\n return this.#signerPromise;\n }\n\n #requireProvider(): ethers.Provider {\n if (!this.#readProvider) {\n throw new TypeError(\"Signer has no provider\");\n }\n return this.#readProvider;\n }\n\n async getChainId(): Promise<number> {\n const network = await this.#requireProvider().getNetwork();\n return Number(network.chainId);\n }\n\n async getAddress(): Promise<Address> {\n const signer = await this.#requireSigner();\n return getAddress(await signer.getAddress());\n }\n\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#requireSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([key, fields]) => [key, [...fields]]),\n );\n const sig = await signer.signTypedData(domain, mutableSigTypes, message);\n if (!isHex(sig)) {\n throw new TypeError(`Expected hex string, got: ${sig}`);\n }\n return sig;\n }\n\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const signer = await this.#requireSigner();\n const contract = new ethers.Contract(config.address, config.abi as ethers.InterfaceAbi, signer);\n const overrides: { gasLimit?: bigint; value?: bigint } = {};\n if (config.value !== undefined) {\n overrides.value = config.value;\n }\n if (config.gas !== undefined) {\n overrides.gasLimit = config.gas;\n }\n const tx = await contract[config.functionName]!(\n ...(config.args as readonly unknown[]),\n overrides,\n );\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n }\n\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n const provider = this.#requireProvider();\n const contract = new ethers.Contract(\n config.address,\n config.abi as ethers.InterfaceAbi,\n provider,\n );\n return contract[config.functionName]!(...(config.args as readonly unknown[])) as Promise<\n ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>\n >;\n }\n\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#requireProvider().getBlock(\"latest\");\n if (!block) {\n throw new Error(\"Failed to fetch latest block\");\n }\n if (block.timestamp === null) {\n throw new Error(\"Latest block has no timestamp\");\n }\n return BigInt(block.timestamp);\n }\n\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#requireProvider().waitForTransaction(hash);\n if (!receipt) {\n throw new Error(\"Transaction receipt not found\");\n }\n return {\n logs: receipt.logs.map((log) => ({\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\n }\n\n subscribe(callbacks: SignerLifecycleCallbacks): () => void {\n return eip1193Subscribe(this.#eip1193, () => this.getAddress(), callbacks);\n }\n}\n","import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { Handle } from \"../relayer/relayer-sdk.types\";\n\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\ninterface TransactionRequestConfig {\n address: Address;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n gas?: bigint;\n value?: bigint;\n}\n\ninterface EthersTransactionRequest {\n to: Address;\n data: Hex;\n gasLimit?: bigint;\n value?: bigint;\n}\n\ninterface EthersTransactionResponse {\n hash: string;\n}\n\ninterface EthersCallProvider {\n call(tx: EthersTransactionRequest): Promise<string>;\n}\n\ninterface EthersTransactionSigner extends EthersCallProvider {\n sendTransaction(tx: EthersTransactionRequest): Promise<EthersTransactionResponse>;\n}\n\nfunction toTransactionRequest(config: TransactionRequestConfig): EthersTransactionRequest {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n args: config.args as never,\n }),\n ...(config.gas !== undefined ? { gasLimit: config.gas } : {}),\n ...(config.value !== undefined ? { value: config.value } : {}),\n };\n}\n\nasync function ethersRead<T>(\n provider: EthersCallProvider,\n config: TransactionRequestConfig,\n): Promise<T> {\n const data = await provider.call(toTransactionRequest(config));\n if (!isHex(data)) {\n throw new TypeError(`Expected hex string, got: ${data}`);\n }\n return decodeFunctionResult({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n data,\n }) as T;\n}\n\nasync function ethersWrite(\n signer: EthersTransactionSigner,\n config: TransactionRequestConfig,\n): Promise<Hex> {\n const tx = await signer.sendTransaction(toTransactionRequest(config));\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\nexport function readConfidentialBalanceOfContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return ethersRead(provider, confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\nexport function readUnderlyingTokenContract(provider: EthersCallProvider, wrapperAddress: Address) {\n return ethersRead(provider, underlyingContract(wrapperAddress));\n}\n\nexport function readSupportsInterfaceContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return ethersRead(provider, supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\nexport function writeConfidentialTransferContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n to: Address,\n handle: Uint8Array,\n inputProof: Uint8Array,\n) {\n return ethersWrite(signer, confidentialTransferContract(tokenAddress, to, handle, inputProof));\n}\n\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: Uint8Array,\n inputProof: Uint8Array,\n) {\n return ethersWrite(signer, unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof));\n}\n\nexport function writeUnwrapFromBalanceContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: Handle,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n burntAmount: Handle,\n burntAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, burntAmount, burntAmountCleartext, decryptionProof),\n );\n}\n\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n spender: Address,\n timestamp?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, spender, timestamp));\n}\n\nexport function writeWrapContract(\n signer: EthersTransactionSigner,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return ethersWrite(signer, wrapContract(wrapperAddress, to, amount));\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\nexport function readTokenPairsContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsContract(registry));\n}\n\nexport function readTokenPairsLengthContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsLengthContract(registry));\n}\n\nexport function readTokenPairsSliceContract(\n provider: EthersCallProvider,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return ethersRead(provider, getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\nexport function readTokenPairContract(\n provider: EthersCallProvider,\n registry: Address,\n index: bigint,\n) {\n return ethersRead(provider, getTokenPairContract(registry, index));\n}\n\nexport function readConfidentialTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n tokenAddress: Address,\n) {\n return ethersRead(provider, getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\nexport function readTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\nexport function readIsConfidentialTokenValidContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"+LAkDA,IAAa,EAAb,KAAmD,CACjD,GACA,GACA,GAEA,YAAY,EAA4B,CACtC,GAAI,aAAc,EAAQ,CACxB,IAAM,EAAkB,IAAIE,EAAAA,gBAAgB,EAAO,SAAS,CAC5D,MAAA,EAAsB,EAAgB,WAAW,CACjD,MAAA,EAAqB,EACrB,MAAA,EAAgB,EAAO,cACd,WAAY,GACrB,MAAA,EAAsB,QAAQ,QAAQ,EAAO,OAAO,CACpD,MAAA,EAAqB,EAAO,OAAO,UAAY,IAAA,IAE/C,MAAA,EAAqB,EAAO,SAIhC,MAAA,GAAwC,CACtC,GAAI,CAAC,MAAA,EACH,MAAU,UAAU,wCAAwC,CAE9D,OAAO,MAAA,EAGT,IAAoC,CAClC,GAAI,CAAC,MAAA,EACH,MAAU,UAAU,yBAAyB,CAE/C,OAAO,MAAA,EAGT,MAAM,YAA8B,CAClC,IAAM,EAAU,MAAM,MAAA,GAAuB,CAAC,YAAY,CAC1D,OAAO,OAAO,EAAQ,QAAQ,CAGhC,MAAM,YAA+B,CAEnC,OAAA,EAAA,EAAA,YAAkB,MADH,MAAM,MAAA,GAAqB,EACX,YAAY,CAAC,CAG9C,MAAM,cAAc,EAA0C,CAC5D,IAAM,EAAS,MAAM,MAAA,GA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CAG1F,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAiC,EAAU,EAAyB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#readProvider","#eip1193","BrowserProvider","#signerPromise","#requireSigner","#requireProvider","eip1193Subscribe","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/ethers/ethers-signer.ts","../../../src/ethers/contracts.ts"],"sourcesContent":["import { ethers, BrowserProvider, type Signer } from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport type { EIP712TypedData } from \"../relayer/relayer-sdk.types\";\nimport type {\n GenericSigner,\n ReadContractConfig,\n SignerLifecycleCallbacks,\n TransactionReceipt,\n WriteContractConfig,\n} from \"../types\";\nimport { eip1193Subscribe } from \"../token/eip1193-subscribe\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Three variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and `subscribe()` works automatically.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * `subscribe()` is not available since there is no EIP-1193 provider.\n *\n * - **Read-only** — `{ provider }`: pass an ethers `Provider` for read-only contract calls.\n * Signing and write operations will throw at runtime.\n */\nexport type EthersSignerConfig =\n | { ethereum: EIP1193Provider }\n | { signer: Signer }\n | { provider: ethers.Provider };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner implements GenericSigner {\n #signerPromise?: Promise<Signer>;\n readonly #readProvider?: ethers.Provider;\n readonly #eip1193?: EIP1193Provider;\n\n constructor(config: EthersSignerConfig) {\n if (\"ethereum\" in config) {\n const browserProvider = new BrowserProvider(config.ethereum);\n this.#signerPromise = browserProvider.getSigner();\n this.#readProvider = browserProvider;\n this.#eip1193 = config.ethereum;\n } else if (\"signer\" in config) {\n this.#signerPromise = Promise.resolve(config.signer);\n this.#readProvider = config.signer.provider ?? undefined;\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n async #requireSigner(): Promise<Signer> {\n if (!this.#signerPromise) {\n throw new TypeError(\"No signer configured — read-only mode\");\n }\n return this.#signerPromise;\n }\n\n #requireProvider(): ethers.Provider {\n if (!this.#readProvider) {\n throw new TypeError(\"Signer has no provider\");\n }\n return this.#readProvider;\n }\n\n async getChainId(): Promise<number> {\n const network = await this.#requireProvider().getNetwork();\n return Number(network.chainId);\n }\n\n async getAddress(): Promise<Address> {\n const signer = await this.#requireSigner();\n return getAddress(await signer.getAddress());\n }\n\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#requireSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([key, fields]) => [key, [...fields]]),\n );\n const sig = await signer.signTypedData(domain, mutableSigTypes, message);\n if (!isHex(sig)) {\n throw new TypeError(`Expected hex string, got: ${sig}`);\n }\n return sig;\n }\n\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const signer = await this.#requireSigner();\n const contract = new ethers.Contract(config.address, config.abi as ethers.InterfaceAbi, signer);\n const overrides: { gasLimit?: bigint; value?: bigint } = {};\n if (config.value !== undefined) {\n overrides.value = config.value;\n }\n if (config.gas !== undefined) {\n overrides.gasLimit = config.gas;\n }\n const tx = await contract[config.functionName]!(\n ...(config.args as readonly unknown[]),\n overrides,\n );\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n }\n\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n const provider = this.#requireProvider();\n const contract = new ethers.Contract(\n config.address,\n config.abi as ethers.InterfaceAbi,\n provider,\n );\n return contract[config.functionName]!(...(config.args as readonly unknown[])) as Promise<\n ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>\n >;\n }\n\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#requireProvider().getBlock(\"latest\");\n if (!block) {\n throw new Error(\"Failed to fetch latest block\");\n }\n if (block.timestamp === null) {\n throw new Error(\"Latest block has no timestamp\");\n }\n return BigInt(block.timestamp);\n }\n\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#requireProvider().waitForTransaction(hash);\n if (!receipt) {\n throw new Error(\"Transaction receipt not found\");\n }\n return {\n logs: receipt.logs.map((log) => ({\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\n }\n\n subscribe(callbacks: SignerLifecycleCallbacks): () => void {\n return eip1193Subscribe(this.#eip1193, () => this.getAddress(), callbacks);\n }\n}\n","import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { Handle } from \"../relayer/relayer-sdk.types\";\n\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\ninterface TransactionRequestConfig {\n address: Address;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n gas?: bigint;\n value?: bigint;\n}\n\ninterface EthersTransactionRequest {\n to: Address;\n data: Hex;\n gasLimit?: bigint;\n value?: bigint;\n}\n\ninterface EthersTransactionResponse {\n hash: string;\n}\n\ninterface EthersCallProvider {\n call(tx: EthersTransactionRequest): Promise<string>;\n}\n\ninterface EthersTransactionSigner extends EthersCallProvider {\n sendTransaction(tx: EthersTransactionRequest): Promise<EthersTransactionResponse>;\n}\n\nfunction toTransactionRequest(config: TransactionRequestConfig): EthersTransactionRequest {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n args: config.args as never,\n }),\n ...(config.gas !== undefined ? { gasLimit: config.gas } : {}),\n ...(config.value !== undefined ? { value: config.value } : {}),\n };\n}\n\nasync function ethersRead<T>(\n provider: EthersCallProvider,\n config: TransactionRequestConfig,\n): Promise<T> {\n const data = await provider.call(toTransactionRequest(config));\n if (!isHex(data)) {\n throw new TypeError(`Expected hex string, got: ${data}`);\n }\n return decodeFunctionResult({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n data,\n }) as T;\n}\n\nasync function ethersWrite(\n signer: EthersTransactionSigner,\n config: TransactionRequestConfig,\n): Promise<Hex> {\n const tx = await signer.sendTransaction(toTransactionRequest(config));\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\nexport function readConfidentialBalanceOfContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return ethersRead(provider, confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\nexport function readUnderlyingTokenContract(provider: EthersCallProvider, wrapperAddress: Address) {\n return ethersRead(provider, underlyingContract(wrapperAddress));\n}\n\nexport function readSupportsInterfaceContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return ethersRead(provider, supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\nexport function writeConfidentialTransferContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n to: Address,\n handle: Uint8Array,\n inputProof: Uint8Array,\n) {\n return ethersWrite(signer, confidentialTransferContract(tokenAddress, to, handle, inputProof));\n}\n\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: Uint8Array,\n inputProof: Uint8Array,\n) {\n return ethersWrite(signer, unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof));\n}\n\nexport function writeUnwrapFromBalanceContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: Handle,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n unwrapRequestId: Handle,\n burntAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, unwrapRequestId, burntAmountCleartext, decryptionProof),\n );\n}\n\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n spender: Address,\n timestamp?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, spender, timestamp));\n}\n\nexport function writeWrapContract(\n signer: EthersTransactionSigner,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return ethersWrite(signer, wrapContract(wrapperAddress, to, amount));\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\nexport function readTokenPairsContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsContract(registry));\n}\n\nexport function readTokenPairsLengthContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsLengthContract(registry));\n}\n\nexport function readTokenPairsSliceContract(\n provider: EthersCallProvider,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return ethersRead(provider, getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\nexport function readTokenPairContract(\n provider: EthersCallProvider,\n registry: Address,\n index: bigint,\n) {\n return ethersRead(provider, getTokenPairContract(registry, index));\n}\n\nexport function readConfidentialTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n tokenAddress: Address,\n) {\n return ethersRead(provider, getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\nexport function readTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\nexport function readIsConfidentialTokenValidContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"+LAkDA,IAAa,EAAb,KAAmD,CACjD,GACA,GACA,GAEA,YAAY,EAA4B,CACtC,GAAI,aAAc,EAAQ,CACxB,IAAM,EAAkB,IAAIE,EAAAA,gBAAgB,EAAO,SAAS,CAC5D,MAAA,EAAsB,EAAgB,WAAW,CACjD,MAAA,EAAqB,EACrB,MAAA,EAAgB,EAAO,cACd,WAAY,GACrB,MAAA,EAAsB,QAAQ,QAAQ,EAAO,OAAO,CACpD,MAAA,EAAqB,EAAO,OAAO,UAAY,IAAA,IAE/C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