@zama-fhe/sdk 3.0.1 → 3.1.0-alpha.2
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 +47 -797
- package/dist/cjs/assertions.cjs +2 -0
- package/dist/cjs/assertions.cjs.map +1 -0
- package/dist/cjs/base-signer.cjs +2 -0
- package/dist/cjs/base-signer.cjs.map +1 -0
- package/dist/cjs/chains/index.cjs +1 -0
- package/dist/cjs/chains.cjs +2 -0
- package/dist/cjs/chains.cjs.map +1 -0
- package/dist/cjs/cleartext/index.cjs +1 -1
- package/dist/cjs/eip1193-subscribe.cjs +1 -1
- package/dist/cjs/eip1193-subscribe.cjs.map +1 -1
- package/dist/cjs/encryption.cjs +2 -0
- package/dist/cjs/encryption.cjs.map +1 -0
- package/dist/cjs/ethers/index.cjs +1 -1
- package/dist/cjs/ethers/index.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -514
- 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/relayer-cleartext.cjs +2 -0
- package/dist/cjs/relayer-cleartext.cjs.map +1 -0
- package/dist/cjs/relayer-sdk.worker.js +75 -75
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/token.cjs +2 -0
- package/dist/cjs/token.cjs.map +1 -0
- package/dist/cjs/validation.cjs +2 -0
- package/dist/cjs/validation.cjs.map +1 -0
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/cjs/web/index.cjs +515 -0
- package/dist/cjs/web/index.cjs.map +1 -0
- package/dist/cjs/wrappers-registry.cjs +1 -1
- package/dist/cjs/wrappers-registry.cjs.map +1 -1
- package/dist/esm/assertions-qxjXTeNw.js +2 -0
- package/dist/esm/{assertions-BARApuMj.js.map → assertions-qxjXTeNw.js.map} +1 -1
- package/dist/esm/base-signer-BKI5njAs.js +2 -0
- package/dist/esm/base-signer-BKI5njAs.js.map +1 -0
- package/dist/esm/base-signer-pKDrNMlE.d.ts +63 -0
- package/dist/esm/chains/index.d.ts +3 -0
- package/dist/esm/chains/index.js +1 -0
- package/dist/esm/chains-DKasII-S.js +2 -0
- package/dist/esm/chains-DKasII-S.js.map +1 -0
- package/dist/esm/cleartext/index.d.ts +2 -86
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/cleartext-Hw0ScIRR.d.ts +19 -0
- package/dist/esm/cleartext-xzeh3Frj.js +2 -0
- package/dist/esm/cleartext-xzeh3Frj.js.map +1 -0
- package/dist/esm/eip1193-subscribe-B7nvT1Mp.js +2 -0
- package/dist/esm/eip1193-subscribe-B7nvT1Mp.js.map +1 -0
- package/dist/esm/{encryption-CmIPBcfP.js → encryption-xcQIQ9NP.js} +2 -2
- package/dist/esm/{encryption-CmIPBcfP.js.map → encryption-xcQIQ9NP.js.map} +1 -1
- package/dist/esm/{error-B6H-mBAh.js → error-BRHDbi2m.js} +1 -1
- package/dist/esm/{error-B6H-mBAh.js.map → error-BRHDbi2m.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +62 -16
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/{hex-D_B-zoId.js → hex-BgMi2Yfs.js} +2 -2
- package/dist/esm/{hex-D_B-zoId.js.map → hex-BgMi2Yfs.js.map} +1 -1
- package/dist/esm/{activity-CUYnGNME.d.ts → index-BFGqQkab.d.ts} +1613 -2472
- package/dist/esm/{relayer-utils-iSPis4x-.d.ts → index-BYVFG3L9.d.ts} +50 -23
- package/dist/esm/index.d.ts +19 -101
- package/dist/esm/index.js +1 -514
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/indexeddb-storage-D2L6iKfO.js +2 -0
- package/dist/esm/indexeddb-storage-D2L6iKfO.js.map +1 -0
- package/dist/esm/memory-storage-CV60XJrC.js +2 -0
- package/dist/esm/memory-storage-CV60XJrC.js.map +1 -0
- package/dist/esm/node/index.d.ts +92 -131
- 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/query/index.d.ts +83 -157
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/relayer-BP6EyPUy.js +2 -0
- package/dist/esm/relayer-BP6EyPUy.js.map +1 -0
- package/dist/esm/relayer-cleartext-CCaAhwgH.js +2 -0
- package/dist/esm/relayer-cleartext-CCaAhwgH.js.map +1 -0
- package/dist/esm/relayer-cleartext-C_5NGHjw.d.ts +702 -0
- package/dist/esm/relayer-sdk.worker.js +75 -75
- package/dist/esm/token-DTgVBH31.js +2 -0
- package/dist/esm/token-DTgVBH31.js.map +1 -0
- package/dist/esm/types-CC0Mp18i.d.ts +652 -0
- package/dist/esm/types-CKtFhknu.d.ts +14 -0
- package/dist/esm/types-DSq1YR39.d.ts +30 -0
- package/dist/esm/types-qTxGTfOc.d.ts +48 -0
- package/dist/esm/validation-D2VCFYWj.js +2 -0
- package/dist/esm/validation-D2VCFYWj.js.map +1 -0
- package/dist/esm/viem/index.d.ts +41 -16
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/web/index.d.ts +21 -0
- package/dist/esm/web/index.js +515 -0
- package/dist/esm/web/index.js.map +1 -0
- package/dist/esm/worker.base-client-pErLQy-p.js +2 -0
- package/dist/esm/worker.base-client-pErLQy-p.js.map +1 -0
- package/dist/esm/wrappers-registry-BNxAZZWS.js +2 -0
- package/dist/esm/wrappers-registry-BNxAZZWS.js.map +1 -0
- package/package.json +33 -6
- package/dist/cjs/activity.cjs +0 -2
- package/dist/cjs/activity.cjs.map +0 -1
- package/dist/cjs/cleartext.cjs +0 -2
- package/dist/cjs/cleartext.cjs.map +0 -1
- package/dist/esm/activity-BAFx7EMt.js +0 -2
- package/dist/esm/activity-BAFx7EMt.js.map +0 -1
- package/dist/esm/assertions-BARApuMj.js +0 -2
- package/dist/esm/cleartext-Cs28cTsa.js +0 -2
- package/dist/esm/cleartext-Cs28cTsa.js.map +0 -1
- package/dist/esm/eip1193-subscribe-Cl_wlVuQ.js +0 -2
- package/dist/esm/eip1193-subscribe-Cl_wlVuQ.js.map +0 -1
- package/dist/esm/memory-storage-F8xjMzVy.js +0 -2
- package/dist/esm/memory-storage-F8xjMzVy.js.map +0 -1
- package/dist/esm/relayer-C6u3eOlN.js +0 -2
- package/dist/esm/relayer-C6u3eOlN.js.map +0 -1
- package/dist/esm/relayer-sdk-DPqytEbO.d.ts +0 -44
- package/dist/esm/relayer-sdk.types-CGfXwKcB.d.ts +0 -528
- package/dist/esm/relayer-utils-BeoTNDM4.js +0 -2
- package/dist/esm/relayer-utils-BeoTNDM4.js.map +0 -1
- package/dist/esm/wrappers-registry-Ckwd2j6g.js +0 -2
- package/dist/esm/wrappers-registry-Ckwd2j6g.js.map +0 -1
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,515 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./activity.cjs`),n=require(`./cleartext.cjs`),r=require(`./wrappers-registry.cjs`);let i=require(`viem`);var a=class extends e.a{constructor(t,n){super(e.o.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},o=class extends e.a{constructor(t,n){super(e.o.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},s=class extends e.a{requested;available;token;constructor(t,n,r){super(e.o.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},c=class extends e.a{requested;available;token;constructor(t,n,r){super(e.o.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},l=class extends e.a{constructor(t,n){super(e.o.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},u=class extends e.a{constructor(t,n){super(e.o.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function d(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const f={AlreadyDelegatedOrRevokedInSameBlock:e=>new t.tt(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new t.et(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new t.$(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new t.ct(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new t.nt(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new t.rt(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new t.at(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new t.ot(`Cannot revoke: no active delegation exists.`,{cause:e})};function p(e){let t=e instanceof Error?e:void 0,n=d(e);if(n&&n in f)return f[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(f))if(r.includes(e))return n(t);return null}var m=class{#e=null;#t=null;#n;#r;#i;constructor(e=`CredentialStore`,t=1,n=`credentials`){this.#n=e,this.#r=t,this.#i=n}#a(){return this.#e?Promise.resolve(this.#e):(this.#t||=new Promise((e,t)=>{let n=indexedDB.open(this.#n,this.#r);n.onupgradeneeded=()=>{let e=n.result;e.objectStoreNames.contains(this.#i)||e.createObjectStore(this.#i,{keyPath:`key`})},n.onsuccess=()=>{this.#e=n.result,this.#t=null,this.#e.onversionchange=()=>{console.warn(`IndexedDB "${this.#n}" closing due to version change from another tab`),this.#e?.close(),this.#e=null,this.#t=null},this.#e.onclose=()=>{this.#e=null,this.#t=null},e(this.#e)},n.onerror=()=>{this.#e=null,this.#t=null,t(n.error)}}),this.#t)}async#o(e,t){let n=await this.#a();return new Promise((r,i)=>{let a=n.transaction(this.#i,e);a.onabort=()=>i(a.error??Error(`Transaction aborted`));let o=t(a.objectStore(this.#i));e===`readonly`?o.onsuccess=()=>r(o.result):a.oncomplete=()=>r(o.result),o.onerror=()=>i(o.error)})}async get(e){return(await this.#o(`readonly`,t=>t.get(e)))?.value??null}async set(e,t){await this.#o(`readwrite`,n=>n.put({key:e,value:t}))}async delete(e){await this.#o(`readwrite`,t=>t.delete(e))}async clear(){await this.#o(`readwrite`,e=>e.clear())}};const h=new m,g=3e4;var _=class{#e=null;#t=new Map;#n=null;config;logger;constructor(e,t){this.config=e,this.logger=t}async initWorker(){return this.#e?this.#e:(this.#n||=this.#r().catch(e=>{throw this.#n=null,e}),this.#n)}async#r(){let e=this.createWorker();this.wireEvents(e);try{let{type:t,payload:n}=this.getInitPayload();await this.sendRequestTo(e,t,n,6e4),this.onWorkerReady?.(e),this.#e=e}catch(t){throw this.terminateWorker(e),t}return this.#e}terminate(){if(this.#e){for(let[e,t]of this.#t)clearTimeout(t.timeoutId),t.reject(Error(`Worker terminated`)),this.#t.delete(e);this.terminateWorker(this.#e),this.#e=null}this.#n=null}handleResponse(e){let t=this.#t.get(e.id);if(!t){this.logger?.warn(`[WorkerClient] Received response for unknown request`,{id:e.id});return}let n=Math.round(performance.now()-t.startTime);if(clearTimeout(t.timeoutId),this.#t.delete(e.id),e.success)this.logger?.debug(`[WorkerClient] ← ${t.type} OK`,{id:e.id,elapsed:n}),t.resolve(e.data);else{this.logger?.error(`[WorkerClient] ← ${t.type} FAILED`,{id:e.id,elapsed:n,error:e.error});let r=Error(e.error);`statusCode`in e&&typeof e.statusCode==`number`&&(r.statusCode=e.statusCode),t.reject(r)}}handleWorkerError(e){this.logger?.error(`[WorkerClient] Worker error`,{error:e});let t=this.#e;this.#e=null,this.#i(`Worker error: ${e}`),t&&this.terminateWorker(t)}handleWorkerMessageError(){this.logger?.error(`[WorkerClient] Message deserialization failed`);let e=this.#e;this.#e=null,this.#i(`Worker message deserialization failed`),e&&this.terminateWorker(e)}sendRequestTo(e,t,n,r=g){return new Promise((i,a)=>{let o=this.generateRequestId(),s=performance.now();this.logger?.debug(`[WorkerClient] → ${t}`,{id:o});let c=setTimeout(()=>{this.#t.delete(o);let e=Math.round(performance.now()-s);this.logger?.error(`[WorkerClient] ${t} timed out after ${r}ms`,{id:o,elapsed:e}),a(Error(`Request ${t} timed out after ${r}ms`))},r);this.#t.set(o,{resolve:i,reject:a,timeoutId:c,startTime:s,type:t});let l={id:o,type:t,payload:n};this.postMessage(e,l)})}async sendRequest(e,t,n=g){let r=await this.initWorker();return this.sendRequestTo(r,e,t,n)}async generateKeypair(){return this.sendRequest(`GENERATE_KEYPAIR`,{})}async createEIP712(e){return this.sendRequest(`CREATE_EIP712`,e)}async encrypt(e){return this.sendRequest(`ENCRYPT`,e)}async userDecrypt(e){return this.sendRequest(`USER_DECRYPT`,e)}async publicDecrypt(e){return this.sendRequest(`PUBLIC_DECRYPT`,{handles:e})}async createDelegatedUserDecryptEIP712(e){return this.sendRequest(`CREATE_DELEGATED_EIP712`,e)}async delegatedUserDecrypt(e){return this.sendRequest(`DELEGATED_USER_DECRYPT`,e)}async requestZKProofVerification(e){return this.sendRequest(`REQUEST_ZK_PROOF_VERIFICATION`,{zkProof:e})}async getPublicKey(){return this.sendRequest(`GET_PUBLIC_KEY`,{})}async getPublicParams(e){return this.sendRequest(`GET_PUBLIC_PARAMS`,{bits:e})}#i(e){for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(Error(e)),this.#t.delete(t)}};function v(e){try{return t.Y(e,`runtime`),t.Z(e,`id`,`runtime.id`),t.q(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function ee(){let e=globalThis;for(let n of[e.chrome,e.browser])try{if(t.Y(n,`ns`),v(n.runtime))return n.runtime}catch{continue}}var y=class extends _{constructor(e){super(e,e.logger)}createWorker(){let e=ee();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
|
|
2
|
-
//#region src/utils/assertions.ts
|
|
3
|
-
function assertNonNullable(value, context) {
|
|
4
|
-
if (value === null || value === void 0) throw new TypeError(\`\${context} must not be null or undefined\`);
|
|
5
|
-
}
|
|
6
|
-
function assertObject(value, context) {
|
|
7
|
-
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(\`\${context} must be an object, got \${typeof value}\`);
|
|
8
|
-
}
|
|
9
|
-
function assertString(value, context) {
|
|
10
|
-
if (typeof value !== "string") throw new TypeError(\`\${context} must be a string, got \${typeof value}\`);
|
|
11
|
-
}
|
|
12
|
-
function assertFunction(value, context) {
|
|
13
|
-
if (typeof value !== "function") throw new TypeError(\`\${context} must be a function, got \${typeof value}\`);
|
|
14
|
-
}
|
|
15
|
-
/** Assert that \`obj[key]\` is a string. Narrows \`obj\` to include \`{ [key]: string }\`. */
|
|
16
|
-
function assertStringProp(obj, key, context) {
|
|
17
|
-
assertString(obj[key], context);
|
|
18
|
-
}
|
|
19
|
-
/** Assert that \`obj[key]\` is a function. Narrows \`obj\` to include \`{ [key]: F }\`. */
|
|
20
|
-
function assertFunctionProp(obj, key, context) {
|
|
21
|
-
assertFunction(obj[key], context);
|
|
22
|
-
}
|
|
23
|
-
function assertCondition(condition, message) {
|
|
24
|
-
if (!condition) throw new TypeError(message);
|
|
25
|
-
}
|
|
26
|
-
//#endregion
|
|
27
|
-
//#region src/utils/hex.ts
|
|
28
|
-
/** Normalize a un-prefixed hex payload to a 0x-prefixed \`Hex\` value. */
|
|
29
|
-
function prefixHex(value) {
|
|
30
|
-
return value.startsWith("0x") ? value : \`0x\${value}\`;
|
|
31
|
-
}
|
|
32
|
-
/** Convert a public \`Hex\` value back an unprefixed format. */
|
|
33
|
-
function unprefixHex(value) {
|
|
34
|
-
assertCondition(value.startsWith("0x"), \`Expected 0x-prefixed hex, got: \${value}\`);
|
|
35
|
-
return value.slice(2);
|
|
36
|
-
}
|
|
37
|
-
//#endregion
|
|
38
|
-
//#region src/worker/browser-extension.ts
|
|
39
|
-
function isValidRuntime(runtime) {
|
|
40
|
-
try {
|
|
41
|
-
assertObject(runtime, "runtime");
|
|
42
|
-
assertStringProp(runtime, "id", "runtime.id");
|
|
43
|
-
assertFunctionProp(runtime, "getURL", "runtime.getURL");
|
|
44
|
-
return true;
|
|
45
|
-
} catch {
|
|
46
|
-
return false;
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* Return the browser extension runtime object, or \`undefined\` outside extensions.
|
|
51
|
-
* Works across Chrome/Edge (\`chrome.runtime\`) and Firefox/Safari (\`browser.runtime\`).
|
|
52
|
-
* Extensions have restricted CSP that blocks \`blob:\` URLs, so callers use
|
|
53
|
-
* this to detect the environment and resolve file URLs via \`runtime.getURL\`.
|
|
54
|
-
*/
|
|
55
|
-
function getBrowserExtensionRuntime() {
|
|
56
|
-
const g = globalThis;
|
|
57
|
-
for (const ns of [g.chrome, g.browser]) try {
|
|
58
|
-
assertObject(ns, "ns");
|
|
59
|
-
if (isValidRuntime(ns.runtime)) return ns.runtime;
|
|
60
|
-
} catch {
|
|
61
|
-
continue;
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
//#endregion
|
|
65
|
-
//#region src/worker/relayer-sdk.worker.ts
|
|
66
|
-
let sdkInstance = null;
|
|
67
|
-
let sdkGlobal = null;
|
|
68
|
-
function assertSdkInstance(instance) {
|
|
69
|
-
try {
|
|
70
|
-
assertNonNullable(instance, "Relayer SDK instance");
|
|
71
|
-
} catch (error) {
|
|
72
|
-
throw new Error("Relayer SDK is not initialized. Call INIT first.", { cause: error });
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
function unreachableFheType(_) {
|
|
76
|
-
throw new Error("Unsupported FHE type");
|
|
77
|
-
}
|
|
78
|
-
let relayerUrlBase = "";
|
|
79
|
-
let csrfTokenBase = "";
|
|
80
|
-
const CSRF_HEADER_NAME = "x-csrf-token";
|
|
81
|
-
const MUTATING_METHODS = new Set([
|
|
82
|
-
"POST",
|
|
83
|
-
"PUT",
|
|
84
|
-
"DELETE",
|
|
85
|
-
"PATCH"
|
|
86
|
-
]);
|
|
87
|
-
/**
|
|
88
|
-
* Send a success response back to the main thread.
|
|
89
|
-
* Optionally transfers ArrayBuffers for zero-copy performance.
|
|
90
|
-
*/
|
|
91
|
-
function sendSuccess(id, type, data, transfer) {
|
|
92
|
-
const response = {
|
|
93
|
-
id,
|
|
94
|
-
type,
|
|
95
|
-
success: true,
|
|
96
|
-
data
|
|
97
|
-
};
|
|
98
|
-
return transfer ? self.postMessage(response, transfer) : self.postMessage(response);
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Send an error response back to the main thread.
|
|
102
|
-
*/
|
|
103
|
-
function sendError(id, type, error, statusCode) {
|
|
104
|
-
const response = {
|
|
105
|
-
id,
|
|
106
|
-
type,
|
|
107
|
-
success: false,
|
|
108
|
-
error
|
|
109
|
-
};
|
|
110
|
-
if (statusCode !== void 0) response.statusCode = statusCode;
|
|
111
|
-
self.postMessage(response);
|
|
112
|
-
}
|
|
113
|
-
const originalFetch = fetch;
|
|
114
|
-
/** Allowed CDN hostnames for loading the relayer SDK script. */
|
|
115
|
-
const ALLOWED_CDN_HOSTS = new Set(["cdn.zama.org"]);
|
|
116
|
-
/**
|
|
117
|
-
* Validate the CDN URL supplied by the caller.
|
|
118
|
-
* Ensures only HTTPS URLs from approved hosts are used when loading
|
|
119
|
-
* SDK code into the worker.
|
|
120
|
-
*/
|
|
121
|
-
function validateCdnUrl(rawUrl) {
|
|
122
|
-
let url;
|
|
123
|
-
try {
|
|
124
|
-
url = new URL(rawUrl);
|
|
125
|
-
} catch {
|
|
126
|
-
throw new Error("Invalid CDN URL");
|
|
127
|
-
}
|
|
128
|
-
if (url.protocol !== "https:") throw new Error("CDN URL must use https");
|
|
129
|
-
if (!ALLOWED_CDN_HOSTS.has(url.hostname)) throw new Error(\`CDN URL host is not allowed: \${url.hostname}\`);
|
|
130
|
-
return url.toString();
|
|
131
|
-
}
|
|
132
|
-
/**
|
|
133
|
-
* Set up fetch interceptor to add credentials and CSRF token for relayer requests.
|
|
134
|
-
* Workers don't automatically include cookies, so we intercept fetch calls
|
|
135
|
-
* targeting our relayer proxy to inject credentials and CSRF headers.
|
|
136
|
-
*/
|
|
137
|
-
function setupFetchInterceptor() {
|
|
138
|
-
globalThis.fetch = async (input, init) => {
|
|
139
|
-
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
140
|
-
const method = init?.method?.toUpperCase() ?? "GET";
|
|
141
|
-
if (relayerUrlBase && url.startsWith(relayerUrlBase)) {
|
|
142
|
-
const headers = new Headers(init?.headers);
|
|
143
|
-
if (MUTATING_METHODS.has(method) && csrfTokenBase) headers.set(CSRF_HEADER_NAME, csrfTokenBase);
|
|
144
|
-
return originalFetch(input, {
|
|
145
|
-
...init,
|
|
146
|
-
headers,
|
|
147
|
-
credentials: "include"
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
return originalFetch(input, init);
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
/**
|
|
154
|
-
* Verify a fetched script's SHA-384 hash matches the expected integrity value.
|
|
155
|
-
*/
|
|
156
|
-
async function verifyIntegrity(content, expectedHash) {
|
|
157
|
-
const encoder = new TextEncoder();
|
|
158
|
-
const hashBuffer = await crypto.subtle.digest("SHA-384", encoder.encode(content));
|
|
159
|
-
const hashHex = [...new Uint8Array(hashBuffer)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
160
|
-
if (hashHex !== expectedHash) throw new Error(\`CDN integrity check failed: expected SHA-384 \${expectedHash}, got \${hashHex}\`);
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Load SDK script from CDN.
|
|
164
|
-
* Uses two strategies depending on the environment:
|
|
165
|
-
* - **Web apps (default):** fetch + blob URL + importScripts. Avoids MIME-type
|
|
166
|
-
* rejections (some CDNs serve .cjs as \`application/node\`) and CSP
|
|
167
|
-
* \`unsafe-eval\` violations.
|
|
168
|
-
* - **Browser extensions (Chrome/Firefox/Safari):** importScripts directly.
|
|
169
|
-
* Blob URLs are blocked by extension CSP, but the CDN must be allowed
|
|
170
|
-
* in the extension's manifest CSP.
|
|
171
|
-
*
|
|
172
|
-
* Integrity is always verified when a hash is provided, regardless of strategy.
|
|
173
|
-
*/
|
|
174
|
-
async function fetchScript(cdnUrl) {
|
|
175
|
-
const response = await originalFetch(cdnUrl);
|
|
176
|
-
if (!response.ok) throw new Error(\`Failed to fetch SDK: \${response.status} \${response.statusText}\`);
|
|
177
|
-
return response.text();
|
|
178
|
-
}
|
|
179
|
-
async function loadSdkScript(cdnUrl, integrity) {
|
|
180
|
-
const validatedUrl = validateCdnUrl(cdnUrl);
|
|
181
|
-
if (getBrowserExtensionRuntime()) {
|
|
182
|
-
if (integrity) await verifyIntegrity(await fetchScript(validatedUrl), integrity);
|
|
183
|
-
return self.importScripts(validatedUrl);
|
|
184
|
-
}
|
|
185
|
-
const scriptContent = await fetchScript(validatedUrl);
|
|
186
|
-
if (integrity) await verifyIntegrity(scriptContent, integrity);
|
|
187
|
-
const blob = new Blob([scriptContent], { type: "application/javascript" });
|
|
188
|
-
const blobUrl = URL.createObjectURL(blob);
|
|
189
|
-
try {
|
|
190
|
-
self.importScripts(blobUrl);
|
|
191
|
-
} finally {
|
|
192
|
-
URL.revokeObjectURL(blobUrl);
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
/**
|
|
196
|
-
* Handle INIT request - load SDK and initialize WASM.
|
|
197
|
-
*/
|
|
198
|
-
async function handleInit(request) {
|
|
199
|
-
const { id, type, payload } = request;
|
|
200
|
-
const { cdnUrl, fhevmConfig, csrfToken, integrity, thread } = payload;
|
|
201
|
-
try {
|
|
202
|
-
relayerUrlBase = fhevmConfig.relayerUrl ?? "";
|
|
203
|
-
csrfTokenBase = csrfToken;
|
|
204
|
-
setupFetchInterceptor();
|
|
205
|
-
await loadSdkScript(cdnUrl, integrity);
|
|
206
|
-
if (!self.relayerSDK) throw new Error("Failed to load relayerSDK from CDN");
|
|
207
|
-
sdkGlobal = self.relayerSDK;
|
|
208
|
-
await sdkGlobal.initSDK(thread !== null && thread !== void 0 ? { thread } : void 0);
|
|
209
|
-
const config = {
|
|
210
|
-
...fhevmConfig,
|
|
211
|
-
batchRpcCalls: false
|
|
212
|
-
};
|
|
213
|
-
sdkInstance = await sdkGlobal.createInstance(config);
|
|
214
|
-
sendSuccess(id, type, { initialized: true });
|
|
215
|
-
} catch (error) {
|
|
216
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
217
|
-
console.error("[Worker] Init error:", message);
|
|
218
|
-
sendError(id, type, message);
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
/** Coerce a boolean to bigint for numeric FHE types. */
|
|
222
|
-
function toBigInt(value) {
|
|
223
|
-
return typeof value === "boolean" ? value ? 1n : 0n : value;
|
|
224
|
-
}
|
|
225
|
-
/**
|
|
226
|
-
* Add a single typed value to the encrypted input builder.
|
|
227
|
-
*/
|
|
228
|
-
function addTypedValue(input, entry) {
|
|
229
|
-
const { value, type: fheType } = entry;
|
|
230
|
-
switch (fheType) {
|
|
231
|
-
case "ebool":
|
|
232
|
-
input.addBool(typeof value === "boolean" ? value : value !== 0n);
|
|
233
|
-
break;
|
|
234
|
-
case "euint8":
|
|
235
|
-
input.add8(toBigInt(value));
|
|
236
|
-
break;
|
|
237
|
-
case "euint16":
|
|
238
|
-
input.add16(toBigInt(value));
|
|
239
|
-
break;
|
|
240
|
-
case "euint32":
|
|
241
|
-
input.add32(toBigInt(value));
|
|
242
|
-
break;
|
|
243
|
-
case "euint64":
|
|
244
|
-
input.add64(toBigInt(value));
|
|
245
|
-
break;
|
|
246
|
-
case "euint128":
|
|
247
|
-
input.add128(toBigInt(value));
|
|
248
|
-
break;
|
|
249
|
-
case "euint256":
|
|
250
|
-
input.add256(toBigInt(value));
|
|
251
|
-
break;
|
|
252
|
-
case "eaddress":
|
|
253
|
-
input.addAddress(value);
|
|
254
|
-
break;
|
|
255
|
-
default: unreachableFheType(fheType);
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
/**
|
|
259
|
-
* Handle ENCRYPT request.
|
|
260
|
-
*/
|
|
261
|
-
async function handleEncrypt(request) {
|
|
262
|
-
const { id, type, payload } = request;
|
|
263
|
-
const { values, contractAddress, userAddress } = payload;
|
|
264
|
-
try {
|
|
265
|
-
assertSdkInstance(sdkInstance);
|
|
266
|
-
const input = sdkInstance.createEncryptedInput(contractAddress, userAddress);
|
|
267
|
-
for (const entry of values) addTypedValue(input, entry);
|
|
268
|
-
const encrypted = await input.encrypt();
|
|
269
|
-
sendSuccess(id, type, {
|
|
270
|
-
handles: encrypted.handles,
|
|
271
|
-
inputProof: encrypted.inputProof
|
|
272
|
-
}, [encrypted.inputProof.buffer, ...encrypted.handles.map((h) => h.buffer)]);
|
|
273
|
-
} catch (error) {
|
|
274
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
275
|
-
console.error("[Worker] Encrypt error:", message);
|
|
276
|
-
sendError(id, type, message);
|
|
277
|
-
}
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Handle USER_DECRYPT request.
|
|
281
|
-
*/
|
|
282
|
-
async function handleUserDecrypt(request) {
|
|
283
|
-
const { id, type, payload } = request;
|
|
284
|
-
try {
|
|
285
|
-
assertSdkInstance(sdkInstance);
|
|
286
|
-
const handleContractPairs = payload.handles.map((handle) => ({
|
|
287
|
-
handle,
|
|
288
|
-
contractAddress: payload.contractAddress
|
|
289
|
-
}));
|
|
290
|
-
sendSuccess(id, type, { clearValues: await sdkInstance.userDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.signerAddress, payload.startTimestamp, payload.durationDays) });
|
|
291
|
-
} catch (error) {
|
|
292
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
293
|
-
const statusCode = extractHttpStatus(error);
|
|
294
|
-
console.error("[Worker] UserDecrypt error:", message);
|
|
295
|
-
sendError(id, type, message, statusCode);
|
|
296
|
-
}
|
|
297
|
-
}
|
|
298
|
-
/**
|
|
299
|
-
* Extract an HTTP status code from an error, if present.
|
|
300
|
-
* Relayer SDK errors may carry a \`status\` or \`statusCode\` property.
|
|
301
|
-
*/
|
|
302
|
-
function extractHttpStatus(error) {
|
|
303
|
-
if (error === null || error === void 0 || typeof error !== "object") return;
|
|
304
|
-
const e = error;
|
|
305
|
-
if (typeof e.statusCode === "number") return e.statusCode;
|
|
306
|
-
if (typeof e.status === "number") return e.status;
|
|
307
|
-
if (e.cause !== null && e.cause !== void 0 && typeof e.cause === "object") {
|
|
308
|
-
const cause = e.cause;
|
|
309
|
-
if (typeof cause.statusCode === "number") return cause.statusCode;
|
|
310
|
-
if (typeof cause.status === "number") return cause.status;
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
/**
|
|
314
|
-
* Handle PUBLIC_DECRYPT request.
|
|
315
|
-
*/
|
|
316
|
-
async function handlePublicDecrypt(request) {
|
|
317
|
-
const { id, type, payload } = request;
|
|
318
|
-
try {
|
|
319
|
-
assertSdkInstance(sdkInstance);
|
|
320
|
-
sendSuccess(id, type, { ...await sdkInstance.publicDecrypt(payload.handles) });
|
|
321
|
-
} catch (error) {
|
|
322
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
323
|
-
console.error("[Worker] PublicDecrypt error:", message);
|
|
324
|
-
sendError(id, type, message);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* Handle GENERATE_KEYPAIR request.
|
|
329
|
-
*/
|
|
330
|
-
function handleGenerateKeypair(request) {
|
|
331
|
-
const { id, type } = request;
|
|
332
|
-
try {
|
|
333
|
-
assertSdkInstance(sdkInstance);
|
|
334
|
-
const keypair = sdkInstance.generateKeypair();
|
|
335
|
-
sendSuccess(id, type, {
|
|
336
|
-
publicKey: prefixHex(keypair.publicKey),
|
|
337
|
-
privateKey: prefixHex(keypair.privateKey)
|
|
338
|
-
});
|
|
339
|
-
} catch (error) {
|
|
340
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
341
|
-
console.error("[Worker] GenerateKeypair error:", message);
|
|
342
|
-
sendError(id, type, message);
|
|
343
|
-
}
|
|
344
|
-
}
|
|
345
|
-
/**
|
|
346
|
-
* Handle CREATE_EIP712 request.
|
|
347
|
-
*/
|
|
348
|
-
function handleCreateEIP712(request) {
|
|
349
|
-
const { id, type, payload } = request;
|
|
350
|
-
try {
|
|
351
|
-
assertSdkInstance(sdkInstance);
|
|
352
|
-
const eip712 = sdkInstance.createEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.startTimestamp, payload.durationDays);
|
|
353
|
-
sendSuccess(id, type, {
|
|
354
|
-
domain: {
|
|
355
|
-
name: eip712.domain.name,
|
|
356
|
-
version: eip712.domain.version,
|
|
357
|
-
chainId: Number(eip712.domain.chainId),
|
|
358
|
-
verifyingContract: eip712.domain.verifyingContract
|
|
359
|
-
},
|
|
360
|
-
types: { UserDecryptRequestVerification: eip712.types.UserDecryptRequestVerification.map((field) => ({
|
|
361
|
-
name: field.name,
|
|
362
|
-
type: field.type
|
|
363
|
-
})) },
|
|
364
|
-
message: {
|
|
365
|
-
publicKey: prefixHex(eip712.message.publicKey),
|
|
366
|
-
contractAddresses: [...eip712.message.contractAddresses],
|
|
367
|
-
startTimestamp: BigInt(eip712.message.startTimestamp),
|
|
368
|
-
durationDays: BigInt(eip712.message.durationDays),
|
|
369
|
-
extraData: prefixHex(eip712.message.extraData)
|
|
370
|
-
}
|
|
371
|
-
});
|
|
372
|
-
} catch (error) {
|
|
373
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
374
|
-
console.error("[Worker] CreateEIP712 error:", message);
|
|
375
|
-
sendError(id, type, message);
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
/**
|
|
379
|
-
* Handle CREATE_DELEGATED_EIP712 request.
|
|
380
|
-
*/
|
|
381
|
-
function handleCreateDelegatedEIP712(request) {
|
|
382
|
-
const { id, type, payload } = request;
|
|
383
|
-
try {
|
|
384
|
-
assertSdkInstance(sdkInstance);
|
|
385
|
-
sendSuccess(id, type, sdkInstance.createDelegatedUserDecryptEIP712(unprefixHex(payload.publicKey), payload.contractAddresses, payload.delegatorAddress, payload.startTimestamp, payload.durationDays));
|
|
386
|
-
} catch (error) {
|
|
387
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
388
|
-
console.error("[Worker] CreateDelegatedEIP712 error:", message);
|
|
389
|
-
sendError(id, type, message);
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
/**
|
|
393
|
-
* Handle DELEGATED_USER_DECRYPT request.
|
|
394
|
-
*/
|
|
395
|
-
async function handleDelegatedUserDecrypt(request) {
|
|
396
|
-
const { id, type, payload } = request;
|
|
397
|
-
try {
|
|
398
|
-
assertSdkInstance(sdkInstance);
|
|
399
|
-
const handleContractPairs = payload.handles.map((handle) => ({
|
|
400
|
-
handle,
|
|
401
|
-
contractAddress: payload.contractAddress
|
|
402
|
-
}));
|
|
403
|
-
sendSuccess(id, type, { clearValues: await sdkInstance.delegatedUserDecrypt(handleContractPairs, unprefixHex(payload.privateKey), unprefixHex(payload.publicKey), payload.signature, payload.signedContractAddresses, payload.delegatorAddress, payload.delegateAddress, payload.startTimestamp, payload.durationDays) });
|
|
404
|
-
} catch (error) {
|
|
405
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
406
|
-
const statusCode = extractHttpStatus(error);
|
|
407
|
-
console.error("[Worker] DelegatedUserDecrypt error:", message);
|
|
408
|
-
sendError(id, type, message, statusCode);
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
/**
|
|
412
|
-
* Handle REQUEST_ZK_PROOF_VERIFICATION request.
|
|
413
|
-
*/
|
|
414
|
-
async function handleRequestZKProofVerification(request) {
|
|
415
|
-
const { id, type, payload } = request;
|
|
416
|
-
try {
|
|
417
|
-
assertSdkInstance(sdkInstance);
|
|
418
|
-
const result = await sdkInstance.requestZKProofVerification(payload.zkProof);
|
|
419
|
-
sendSuccess(id, type, result, [result.inputProof.buffer, ...result.handles.map((h) => h.buffer)]);
|
|
420
|
-
} catch (error) {
|
|
421
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
422
|
-
console.error("[Worker] RequestZKProofVerification error:", message);
|
|
423
|
-
sendError(id, type, message);
|
|
424
|
-
}
|
|
425
|
-
}
|
|
426
|
-
/**
|
|
427
|
-
* Handle GET_PUBLIC_KEY request.
|
|
428
|
-
*/
|
|
429
|
-
function handleGetPublicKey(request) {
|
|
430
|
-
const { id, type } = request;
|
|
431
|
-
try {
|
|
432
|
-
assertSdkInstance(sdkInstance);
|
|
433
|
-
sendSuccess(id, type, { result: sdkInstance.getPublicKey() });
|
|
434
|
-
} catch (error) {
|
|
435
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
436
|
-
console.error("[Worker] GetPublicKey error:", message);
|
|
437
|
-
sendError(id, type, message);
|
|
438
|
-
}
|
|
439
|
-
}
|
|
440
|
-
/**
|
|
441
|
-
* Handle GET_PUBLIC_PARAMS request.
|
|
442
|
-
*/
|
|
443
|
-
function handleGetPublicParams(request) {
|
|
444
|
-
const { id, type, payload } = request;
|
|
445
|
-
try {
|
|
446
|
-
assertSdkInstance(sdkInstance);
|
|
447
|
-
sendSuccess(id, type, { result: sdkInstance.getPublicParams(payload.bits) });
|
|
448
|
-
} catch (error) {
|
|
449
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
450
|
-
console.error("[Worker] GetPublicParams error:", message);
|
|
451
|
-
sendError(id, type, message);
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
/**
|
|
455
|
-
* Handle UPDATE_CSRF request - update the stored CSRF token.
|
|
456
|
-
*/
|
|
457
|
-
function handleUpdateCsrf(request) {
|
|
458
|
-
const { id, type, payload } = request;
|
|
459
|
-
csrfTokenBase = payload.csrfToken;
|
|
460
|
-
sendSuccess(id, type, { updated: true });
|
|
461
|
-
}
|
|
462
|
-
/**
|
|
463
|
-
* Main message handler.
|
|
464
|
-
*/
|
|
465
|
-
self.onmessage = async (event) => {
|
|
466
|
-
const request = event.data;
|
|
467
|
-
try {
|
|
468
|
-
switch (request.type) {
|
|
469
|
-
case "INIT":
|
|
470
|
-
await handleInit(request);
|
|
471
|
-
break;
|
|
472
|
-
case "UPDATE_CSRF":
|
|
473
|
-
handleUpdateCsrf(request);
|
|
474
|
-
break;
|
|
475
|
-
case "ENCRYPT":
|
|
476
|
-
await handleEncrypt(request);
|
|
477
|
-
break;
|
|
478
|
-
case "USER_DECRYPT":
|
|
479
|
-
await handleUserDecrypt(request);
|
|
480
|
-
break;
|
|
481
|
-
case "PUBLIC_DECRYPT":
|
|
482
|
-
await handlePublicDecrypt(request);
|
|
483
|
-
break;
|
|
484
|
-
case "GENERATE_KEYPAIR":
|
|
485
|
-
handleGenerateKeypair(request);
|
|
486
|
-
break;
|
|
487
|
-
case "CREATE_EIP712":
|
|
488
|
-
handleCreateEIP712(request);
|
|
489
|
-
break;
|
|
490
|
-
case "CREATE_DELEGATED_EIP712":
|
|
491
|
-
handleCreateDelegatedEIP712(request);
|
|
492
|
-
break;
|
|
493
|
-
case "DELEGATED_USER_DECRYPT":
|
|
494
|
-
await handleDelegatedUserDecrypt(request);
|
|
495
|
-
break;
|
|
496
|
-
case "REQUEST_ZK_PROOF_VERIFICATION":
|
|
497
|
-
await handleRequestZKProofVerification(request);
|
|
498
|
-
break;
|
|
499
|
-
case "GET_PUBLIC_KEY":
|
|
500
|
-
handleGetPublicKey(request);
|
|
501
|
-
break;
|
|
502
|
-
case "GET_PUBLIC_PARAMS":
|
|
503
|
-
handleGetPublicParams(request);
|
|
504
|
-
break;
|
|
505
|
-
default: console.error("[Worker] Unknown request type:", request.type);
|
|
506
|
-
}
|
|
507
|
-
} catch (error) {
|
|
508
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
509
|
-
sendError(request?.id ?? "unknown", request?.type ?? "UNKNOWN", message);
|
|
510
|
-
}
|
|
511
|
-
};
|
|
512
|
-
//#endregion
|
|
513
|
-
})();
|
|
514
|
-
`],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};const b=8192,x=300*1e3;function S(e){let t=[];for(let n=0;n<e.length;n+=b)t.push(String.fromCharCode(...e.subarray(n,n+b)));return btoa(t.join(``))}function C(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function w(e){return`fhe:pubkey:${e}`}function T(e,t){return`fhe:params:${e}:${t}`}function E(e){return`fhe:params-index:${e}`}function D(e){t.Y(e,`CachedPublicKey`),t.Z(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),t.Z(e,`publicKey`,`CachedPublicKey.publicKey`)}function O(e){t.Y(e,`CachedPublicParams`),t.Z(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),t.Z(e,`publicParams`,`CachedPublicParams.publicParams`)}var k=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let n=w(this.#t);try{let e=await this.#e.get(n);if(e){D(e);let t={publicKeyId:e.publicKeyId,publicKey:C(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(n),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:t.U(e).message})}let r=await e();if(r===null)return null;this.#a=r;try{let e={publicKeyId:r.publicKeyId,publicKey:S(r.publicKey),lastValidatedAt:Date.now()};await this.#e.set(n,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:t.U(e).message})}return r}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,n){let r=T(this.#t,e);try{let t=await this.#e.get(r);if(t){O(t);let n={publicParamsId:t.publicParamsId,publicParams:C(t.publicParams)};return this.#o.set(e,n),n}}catch(n){await this.#g(r),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:t.U(n).message})}let i=await n();if(i===null)return null;this.#o.set(e,i);try{let n={publicParamsId:i.publicParamsId,publicParams:S(i.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,n);let a=E(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:t.U(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.U(n).message})}return i}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let n=w(this.#t),r=null,i=[];try{let[a,o]=await Promise.all([this.#e.get(n),this.#h()]);if(a)try{D(a),r={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:t.U(e).message}),await this.#g(n)}if(i=o,!r)return!1;if([r,...i.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let t=e-this.#r+x;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let c=await s.json();if(!c||typeof c!=`object`||!(`fhePublicKey`in c)||!c.fhePublicKey?.urls?.length||!(`crs`in c)||typeof c.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let t=e-this.#r+x;return await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let l=c,u=l.fhePublicKey.urls[0];if(r.artifactUrl&&u&&u!==r.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let d={...r,lastValidatedAt:e};if(u){let e=await this.#m(u,r);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;d={...d,artifactUrl:u,etag:e.etag,lastModified:e.lastModified}}let f=[];for(let t of i){let r=l.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let a={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;a={...a,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}f.push({...t,data:a})}return await this.#v(n,d,f),this.#u=e,!1}catch(a){let o=t.U(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+x;try{r&&await this.#v(n,{...r,lastValidatedAt:l},i.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:t.U(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=E(this.#t),n=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:t.U(e).message}),null))??[],r=new Set([...this.#o.keys(),...n]),i=Array.from(r);return(await Promise.all(i.map(async e=>{let n=T(this.#t,e),r;try{r=await this.#e.get(n)}catch(n){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:t.U(n).message}),null}if(!r)return null;try{return O(r),{bits:e,key:n,data:{...r,lastValidatedAt:r.lastValidatedAt??0}}}catch(r){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:t.U(r).message}),await this.#g(n),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.U(n).message})})}async#_(e,n){let r=E(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(r),...n.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:t.U(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,n,r){let i=[this.#e.set(e,n).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:t.U(e).message})}),...r.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:t.U(e).message})}))];await Promise.all(i)}},A=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:r,threads:i}=this.#l;if(i!==void 0&&(!Number.isInteger(i)||i<1))throw Error(`Invalid thread count: ${i}. Must be a positive integer.`);return i!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},n.i[e],t[e]),csrfToken:r?.getCsrfToken?.()??``,integrity:r?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:i}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let t=await this.#l.getChainId();if(this.#i!==null&&t!==this.#i&&this.#p(),this.#i=t,this.#o||=this.#l.fheArtifactStorage??new m(`FheArtifactCache`,1,`artifacts`),!this.#a){let e=Object.assign({},n.i[t],this.#l.transports[t]);this.#a=new k({storage:this.#o,chainId:t,relayerUrl:e.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(t=>{this.#t=null;let n=t instanceof e.a?t:new e.t(`Failed to initialize FHE worker`,{cause:t});throw this.#u(`error`,n),n})),this.#t}async#h(){let e=new y(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,r,i=7){let a=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:r,durationDays:i}),o={name:a.domain.name,version:a.domain.version,chainId:a.domain.chainId,verifyingContract:a.domain.verifyingContract};return{domain:o,types:{EIP712Domain:n.c(o),UserDecryptRequestVerification:a.types.UserDecryptRequestVerification},message:{publicKey:a.message.publicKey,contractAddresses:a.message.contractAddresses,startTimestamp:a.message.startTimestamp,durationDays:a.message.durationDays,extraData:a.message.extraData}}}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;return n.l(async()=>{let e=await this.#f();await this.#g();let n=await e.encrypt({values:t,contractAddress:r,userAddress:i});return{handles:n.handles,inputProof:n.inputProof}})}async userDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return n.l(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let t=await this.#l.getChainId(),r=Object.assign({},n.i[t],this.#l.transports[t]);if(!r.aclContractAddress)throw new e.t(`No ACL address configured for chain ${t}`);return r.aclContractAddress}},j=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#o(e,t,n);return await this.#e.get(r)}catch(e){return console.warn(`[zama-sdk] DecryptCache.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#o(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#c(i).catch(e=>{console.warn(`[zama-sdk] DecryptCache index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] DecryptCache.set failed:`,e)}}async clearForRequester(e){this.#r=this.#r.then(()=>this.#i(e).catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearForRequester failed:`,e)})),await this.#r}async#i(e){let t=(0,i.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),a=[],o=[];for(let e of r)e.startsWith(n)?a.push(e):o.push(e);await Promise.all(a.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,o)}async clearAll(){this.#r=this.#r.then(()=>this.#a().catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearAll failed:`,e)})),await this.#r}async#a(){let e=await this.#s();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#o(e,t,n){return`${this.#t}:${(0,i.getAddress)(e)}:${(0,i.getAddress)(t)}:${n.toLowerCase()}`}async#s(){return await this.#e.get(this.#n)??[]}async#c(e){let t=await this.#s();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}},M=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const N=new M;var P=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,n,r){let i=await this.#n(n,r),a=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),o=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),s=await crypto.subtle.decrypt({name:`AES-GCM`,iv:a},i,o);return t.V(new TextDecoder().decode(s))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function F(e){t.Y(e,`Stored credentials`),t.X(e.publicKey,`credentials.publicKey`),t.W(e.contractAddresses,`credentials.contractAddresses`);for(let n of e.contractAddresses)t.K(typeof n==`string`&&(0,i.isAddress)(n,{strict:!1}),`Expected each contractAddress to be a valid hex address`);t.Y(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),t.X(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),t.X(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),t.K(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),t.K(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function I(e){F(e);let n=e;t.K(typeof n.delegatorAddress==`string`&&(0,i.isAddress)(n.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),t.K(typeof n.delegateAddress==`string`&&(0,i.isAddress)(n.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),t.K(typeof n.startTimestamp==`number`,`Expected startTimestamp to be a number`),t.K(typeof n.durationDays==`number`,`Expected durationDays to be a number`)}function L(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function R(e,t){let n=new Set(t.map(e=>(0,i.getAddress)(e))),r=new Set(e.map(e=>(0,i.getAddress)(e)));return n.isSubsetOf(r)}function z(e,t){return L(e)?R(e.contractAddresses,t):!1}function B(e){return[...new Set(e.map(e=>(0,i.getAddress)(e)))].toSorted()}async function V(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var H=class{#e;constructor(e){this.#e=e}#t(e){t.Y(e,`Session entry`),t.X(e.signature,`session.signature`),t.K(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),t.K(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},U=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;#i=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new H(e.sessionStorage),this.crypto=new P,this.keypairTTL=e.keypairTTL??2592e3,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`);typeof this.sessionTTL==`number`&&this.sessionTTL>this.keypairTTL&&(this.sessionTTL=this.keypairTTL,console.warn(`[zama-sdk] sessionTTL was clamped to keypairTTL (${this.keypairTTL}s). A session that outlives the keypair causes isAllowed() to return true after the keypair expires, leading to unexpected wallet prompts.`))}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:n,contracts:r,createKey:i,createFn:a}){this.emit({type:t.E.CredentialsLoading,contractAddresses:r});try{let e=await this.storage.get(n);if(e){this.assertEncrypted(e);let i=await this.sessionSignatures.get(n);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(n),this.emit({type:t.E.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(e,i.signature);if(z(a,r))return this.emit({type:t.E.CredentialsCached,contractAddresses:r}),this.emit({type:t.E.CredentialsAllowed,contractAddresses:r}),a;if(L(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.E.CredentialsExpired,contractAddresses:r})}if(L(e)){if(R(e.contractAddresses,r)){let i=await this.signForContracts(e,e.contractAddresses);await this.sessionSignatures.set({key:n,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(e,i);return this.emit({type:t.E.CredentialsCached,contractAddresses:r}),this.emit({type:t.E.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(e,e.contractAddresses),a=await this.decryptCredentials(e,i);return this.#a({key:n,credentials:a,requiredContracts:r})}this.emit({type:t.E.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof e.a)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:t.E.CredentialsCorrupted,error:t.U(r)}),await this.#s(n)}return(!this.#t||this.#n!==i)&&(this.#n=i,this.#t=a().then(e=>(this.emit({type:t.E.CredentialsAllowed,contractAddresses:r}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!z(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,n){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:t.E.CredentialsRevoked,...n?{contractAddresses:n}:{}})}async checkAllowed(e,t){if(t.length===0)return!1;let n=await this.sessionSignatures.get(e);if(n===null||this.sessionSignatures.isExpired(n))return!1;try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),z(n,t)):!1}catch{return!1}}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#s(e)}clearCaches(){this.crypto.clearCache(),this.#i=null}async createCredentials({key:n,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:t.E.CredentialsCreating,contractAddresses:r});try{let e=await i();return await this.persistCredentials(n,e),await this.sessionSignatures.set({key:n,signature:e.signature,ttl:this.sessionTTL}),this.emit({type:t.E.CredentialsCreated,contractAddresses:r}),e}catch(n){if(n instanceof e.a)throw n;return t.mt(n,a)}}async#a({key:e,credentials:n,requiredContracts:r}){if(this.#r){let e=await this.#r;if(R(e.contractAddresses,r))return this.emit({type:t.E.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(R(e.contractAddresses,r))return this.emit({type:t.E.CredentialsAllowed,contractAddresses:r}),e;n=e}let i=this.#o({key:e,credentials:n,requiredContracts:r});this.#r=i;try{let e=await i;return this.#i=e,e}finally{this.#r===i&&(this.#r=null)}}async#o({key:e,credentials:n,requiredContracts:r}){let i=B([...n.contractAddresses,...r]),a=await this.signForContracts(n,i),o={...n,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:t.E.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,n){try{let t=await this.encryptCredentials(n);await this.storage.set(e,t)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:t.E.CredentialsPersistFailed,error:t.U(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:t.E.CredentialsPersistFailed,error:t.U(e)})}}};function te(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var W=class e extends U{#e;#t=null;#n=null;static async computeStoreKey(e,t){return V((0,i.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,te(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof M&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=B(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeByKey(e){await this.revokeSession(e)}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=B(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){F(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,i.getAddress)(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let a=await e.computeStoreKey(t,n);return this.#n=r,this.#t=a,a}},G=class e extends U{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return V((0,i.getAddress)(e),(0,i.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,i.getAddress)(e),r=B(t),a=await this.#i(n);return this.resolveCredentials({key:a,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,i.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,i.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,i.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,i.getAddress)(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){I(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let n=await this.signer.getAddress(),r=await this.signer.getChainId(),a=`${(0,i.getAddress)(n)}:${(0,i.getAddress)(t)}:${r}`;if(this.#t&&this.#n===a)return this.#t;let o=await e.computeStoreKey(n,t,r);return this.#n=a,this.#t=o,o}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData({domain:{...n.domain,chainId:Number(n.domain.chainId)},types:n.types,message:{...n.message,startTimestamp:BigInt(n.message.startTimestamp),durationDays:BigInt(n.message.durationDays)}})}},K=class n extends t.w{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,i.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.signer.readContract(r.T(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(n,a,s){let{skipBalanceCheck:c=!1,onEncryptComplete:l,onTransferSubmitted:u}=s??{},d=(0,i.getAddress)(n);c||await this.#i(a);let f,p,m=Date.now();try{this.emit({type:t.E.EncryptStart}),{handles:f,inputProof:p}=await this.sdk.relayer.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:t.E.EncryptEnd,durationMs:Date.now()-m}),q(()=>l?.())}catch(n){throw this.emit({type:t.E.EncryptError,error:t.U(n),durationMs:Date.now()-m}),n instanceof e.a?n:new e.i(`Failed to encrypt transfer amount`,{cause:n})}if(f.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.h(this.address,d,f[0],p));return this.emit({type:t.E.TransferSubmitted,txHash:e}),q(()=>u?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`transfer`,error:t.U(n)}),n instanceof e.a?n:new o(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(n,a,s,c){let l=(0,i.getAddress)(n),u=(0,i.getAddress)(a),d,f,p=Date.now();try{this.emit({type:t.E.EncryptStart}),{handles:d,inputProof:f}=await this.sdk.relayer.encrypt({values:[{value:s,type:`euint64`}],contractAddress:this.address,userAddress:l}),this.emit({type:t.E.EncryptEnd,durationMs:Date.now()-p}),q(()=>c?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.E.EncryptError,error:t.U(n),durationMs:Date.now()-p}),n instanceof e.a?n:new e.i(`Failed to encrypt transferFrom amount`,{cause:n})}if(d.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.g(this.address,l,u,d[0],f));return this.emit({type:t.E.TransferFromSubmitted,txHash:e}),q(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`transferFrom`,error:t.U(n)}),n instanceof e.a?n:new o(`TransferFrom transaction failed`,{cause:n})}}async approve(n,o){let s=(0,i.getAddress)(n);try{let e=await this.sdk.signer.writeContract(r.y(this.address,s,o));return this.emit({type:t.E.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`approve`,error:t.U(n)}),n instanceof e.a?n:new a(`Operator approval failed`,{cause:n})}}async isApproved(e,t){let n=(0,i.getAddress)(e),a=t?(0,i.getAddress)(t):await this.sdk.signer.getAddress();return this.sdk.signer.readContract(r._(this.address,a,n))}async shield(n,a){let s=await this.#n(),l;try{let e=await this.sdk.signer.getAddress();l=await this.sdk.signer.readContract(t.P(s,e))}catch(n){throw n instanceof e.a?n:new u(`Could not read ERC-20 balance for shield validation (token: ${s})`,{cause:t.U(n)})}if(l<n)throw new c(`Insufficient ERC-20 balance: requested ${n}, available ${l} (token: ${s})`,{requested:n,available:l,token:s});let d=a?.approvalStrategy??`exact`;d!==`skip`&&await this.#o(n,d===`max`,a);try{let e=a?.to?(0,i.getAddress)(a.to):await this.sdk.signer.getAddress(),o=await this.sdk.signer.writeContract(r.E(this.wrapper,e,n));return this.emit({type:t.E.ShieldSubmitted,txHash:o}),q(()=>a?.onShieldSubmitted?.(o)),{txHash:o,receipt:await this.sdk.signer.waitForTransactionReceipt(o)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`shield`,error:t.U(n)}),n instanceof e.a?n:new o(`Shield transaction failed`,{cause:n})}}async unwrap(n){let i=await this.sdk.signer.getAddress(),a,s,c=Date.now();try{this.emit({type:t.E.EncryptStart}),{handles:a,inputProof:s}=await this.sdk.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.wrapper,userAddress:i}),this.emit({type:t.E.EncryptEnd,durationMs:Date.now()-c})}catch(n){throw this.emit({type:t.E.EncryptError,error:t.U(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.i(`Failed to encrypt unshield amount`,{cause:n})}if(a.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.x(this.address,i,i,a[0],s));return this.emit({type:t.E.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`unwrap`,error:t.U(n)}),n instanceof e.a?n:new o(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let n=await this.sdk.signer.getAddress(),i=await this.readConfidentialBalanceOf(n);if(t.B(i))throw new e.r(`Cannot unshield: balance is zero`);try{let e=await this.sdk.signer.writeContract(r.S(this.address,n,n,i));return this.emit({type:t.E.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`unwrap`,error:t.U(n)}),n instanceof e.a?n:new o(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return q(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return q(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];t.G(a,`finalizeUnwrap: clearValue`);try{let e=await this.sdk.signer.writeContract(r.C(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.E.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`finalizeUnwrap`,error:t.U(n)}),n instanceof e.a?n:new o(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=await this.#n(),i=n??2n**256n-1n;try{if(i>0n){let e=await this.sdk.signer.getAddress();await this.sdk.signer.readContract(t.M(r,e,this.wrapper))>0n&&await this.sdk.signer.writeContract(t.N(r,this.wrapper,0n))}let e=await this.sdk.signer.writeContract(t.N(r,this.wrapper,i));return this.emit({type:t.E.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`approveUnderlying`,error:t.U(n)}),n instanceof e.a?n:new a(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){if(r&&r.getTime()<Date.now()+36e5)throw new t.rt(`Expiration date must be at least 1 hour in the future`);let a=(0,i.getAddress)(n),s=await this.sdk.signer.getAddress();if(a===(0,i.getAddress)(s))throw new t.ct(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new t.nt(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.D,u;try{u=await this.getDelegationExpiry({delegatorAddress:s,delegateAddress:a})}catch{u=-1n}if(u===l)throw new t.at(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await this.sdk.signer.writeContract(t.O(c,a,this.address,l));return this.emit({type:t.E.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`delegateDecryption`,error:t.U(n)}),n instanceof e.a?n:p(n)||new o(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=(0,i.getAddress)(n),a=await this.sdk.signer.getAddress(),s=await this.getAclAddress(),c;try{c=await this.getDelegationExpiry({delegatorAddress:a,delegateAddress:r})}catch{c=1n}if(c===0n)throw new t.ot(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await this.sdk.signer.writeContract(t.j(s,r,this.address));return this.emit({type:t.E.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.E.TransactionError,operation:`revokeDelegation`,error:t.U(n)}),n instanceof e.a?n:p(n)||new o(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:r}){return n.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return n.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.a?i.set(t[a].address,n):i.set(t[a].address,new o(r,{cause:n}))}return i}async#i(t){if(t===0n)return;let n;try{n=await this.balanceOf()}catch(t){throw t instanceof e.a?t:new l(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new s(`Insufficient confidential balance: requested ${t}, available ${n} (token: ${this.address})`,{requested:t,available:n,token:this.address})}async#a(n,r,i){this.emit({type:t.E.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.sdk.signer.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.a?t:new o(`Failed to get unshield receipt`,{cause:t})}let s=t.S(a.logs);if(!s)throw new o(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.E.UnshieldPhase2Started,operationId:r}),q(()=>i?.onFinalizing?.());let c=await this.finalizeUnwrap(s.encryptedAmount);return this.emit({type:t.E.UnshieldPhase2Submitted,txHash:c.txHash,operationId:r}),q(()=>i?.onFinalizeSubmitted?.(c.txHash)),c}async#o(n,r,i){let o=await this.#n(),s=await this.sdk.signer.getAddress(),c=await this.sdk.signer.readContract(t.M(o,s,this.wrapper));if(!(c>=n))try{c>0n&&await this.sdk.signer.writeContract(t.N(o,this.wrapper,0n));let e=r?2n**256n-1n:n,a=await this.sdk.signer.writeContract(t.N(o,this.wrapper,e));this.emit({type:t.E.ApproveUnderlyingSubmitted,txHash:a}),q(()=>i?.onApprovalSubmitted?.(a))}catch(t){throw t instanceof e.a?t:new a(`ERC-20 approval failed`,{cause:t})}}};function q(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const J={[n.o.chainId]:n.o.registryAddress,[n.s.chainId]:n.s.registryAddress,[n.n.chainId]:n.n.registryAddress},Y=300*1e3;var X=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},J,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.signer.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,i.getAddress)(n)}async listPairs(t={}){let n=t.page??1,i=t.pageSize??100,a=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.signer.readContract(r.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.signer.readContract(r.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Y:void 0)}return{items:m,total:c,page:n,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.signer.readContract(t.L(e.tokenAddress)),this.signer.readContract(t.R(e.tokenAddress)),this.signer.readContract(t.F(e.tokenAddress)),this.signer.readContract(t.I(e.tokenAddress)),this.signer.readContract(t.L(e.confidentialTokenAddress)),this.signer.readContract(t.R(e.confidentialTokenAddress)),this.signer.readContract(t.F(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ct:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.t(t,n));if(!s)return this.#i(a,null,Y);let l=await this.signer.readContract(r.s(t,c));return this.#i(a,{confidentialTokenAddress:c,isValid:l})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ut:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.n(t,n));if(!s)return this.#i(a,null,Y);let l=await this.signer.readContract(r.s(t,n));return this.#i(a,{tokenAddress:c,isValid:l})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(r.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(r.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(r.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.t(t,(0,i.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.n(t,(0,i.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.s(t,(0,i.getAddress)(e)))}};const Z=365*86400;var ne=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new M,this.cache=new j(e.storage),this.#t=e.onEvent??function(){},this.registry=new X({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>Z?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${Z}s); capping to ${Z}s.`),Z):t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new W(n),this.delegatedCredentials=new G(n),this.#r=this.#o(),this.signer.subscribe){let n=e.signerLifecycleCallbacks,r=(e,n)=>{n().catch(n=>{this.emitEvent({type:t.E.TransactionError,operation:e,error:t.U(n)})})};this.#n=this.signer.subscribe({onDisconnect:()=>{r(`signerDisconnect`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=null,this.#a=null,n?.onDisconnect?.()})},onAccountChange:e=>{r(`signerAccountChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=(0,i.getAddress)(e);try{this.#a=await this.signer.getChainId()}catch{}n?.onAccountChange?.(e)})},onChainChange:e=>{r(`signerChainChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}n?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await W.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new t.w(this,e)}createToken(e,t){return new K(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new X({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.credentials.allow(...e)}async userDecrypt(e){if(e.length===0)return{};let n=e.map(e=>({handle:e.handle,contractAddress:(0,i.getAddress)(e.contractAddress)})),r={},a=[];for(let e of n)t.B(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;let o=await this.signer.getAddress(),s=[];for(let e of a){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?s.push(e):r[e.handle]=t}if(s.length===0)return r;let c=await this.credentials.allow(...new Set(n.map(e=>e.contractAddress))),l=new Map;for(let e of s){let t=l.get(e.contractAddress);t?t.push(e.handle):l.set(e.contractAddress,[e.handle])}let u=Date.now(),d=s.map(e=>e.handle);try{this.emitEvent({type:t.E.DecryptStart,handles:d}),await t.T([...l.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:c.contractAddresses,privateKey:c.privateKey,publicKey:c.publicKey,signature:c.signature,signerAddress:o,startTimestamp:c.startTimestamp,durationDays:c.durationDays});for(let[t,i]of Object.entries(n))r[t]=i,await this.cache.set(o,e,t,i)}),5);let e={};for(let t of d){let n=r[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.E.DecryptEnd,durationMs:Date.now()-u,handles:d,result:e}),r}catch(e){throw this.emitEvent({type:t.E.DecryptError,error:t.U(e),durationMs:Date.now()-u,handles:d}),t.Q(e,`Failed to decrypt handles`)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw t.Q(e,`Public decryption failed`)}}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await W.computeStoreKey(e,t);await this.credentials.revokeByKey(n),await this.cache.clearForRequester(e)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}async function re(e,t,n){await e.set(Q(t),n)}async function ie(e,t){return e.get(Q(t))}async function ae(e,t){await e.delete(Q(t))}var $=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const oe=new $;exports.ACL_TOPICS=t.a,exports.AclPausedError=t.$,exports.AclTopics=t.o,exports.ApprovalFailedError=a,exports.BalanceCheckUnavailableError=l,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.CredentialsManager=W,exports.DecryptCache=j,exports.DecryptionFailedError=e.r,exports.DefaultRegistryAddresses=J,exports.DelegatedCredentialsManager=G,exports.DelegationContractIsSelfError=t.et,exports.DelegationCooldownError=t.tt,exports.DelegationDelegateEqualsContractError=t.nt,exports.DelegationExpirationTooSoonError=t.rt,exports.DelegationExpiredError=t.it,exports.DelegationExpiryUnchangedError=t.at,exports.DelegationNotFoundError=t.ot,exports.DelegationNotPropagatedError=t.st,exports.DelegationSelfNotAllowedError=t.ct,exports.ERC20ReadFailedError=u,exports.ERC7984_INTERFACE_ID=r.c,exports.ERC7984_WRAPPER_INTERFACE_ID=r.l,exports.EncryptionFailedError=e.i,exports.HardhatConfig=n.a,exports.IndexedDBStorage=m,exports.InsufficientConfidentialBalanceError=s,exports.InsufficientERC20BalanceError=c,exports.InvalidKeypairError=t.lt,exports.KeypairExpiredError=t.ut,exports.MainnetConfig=n.o,exports.MemoryStorage=M,exports.NoCiphertextError=t.dt,exports.ReadonlyToken=t.w,exports.RelayerRequestFailedError=e.n,exports.RelayerWeb=A,exports.SepoliaConfig=n.s,exports.SigningFailedError=t.ft,exports.SigningRejectedError=t.pt,exports.TOKEN_TOPICS=t.s,exports.Token=K,exports.Topics=t.c,exports.TransactionRevertedError=o,exports.WrappersRegistry=X,exports.ZERO_HANDLE=t.z,exports.ZamaError=e.a,exports.ZamaErrorCode=e.o,exports.ZamaSDK=ne,exports.ZamaSDKEvents=t.E,exports.allowanceContract=t.M,exports.applyDecryptedValues=t.t,exports.approveContract=t.N,exports.balanceOfContract=t.P,exports.chromeSessionStorage=oe,exports.clearPendingUnshield=ae,exports.confidentialBalanceOfContract=r.p,exports.confidentialTotalSupplyContract=r.m,exports.confidentialTransferContract=r.h,exports.confidentialTransferFromContract=r.g,exports.decimalsContract=t.F,exports.decodeAclEvent=t.l,exports.decodeAclEvents=t.u,exports.decodeConfidentialTransfer=t.d,exports.decodeDelegatedForUserDecryption=t.f,exports.decodeOnChainEvent=t.p,exports.decodeOnChainEvents=t.m,exports.decodeRevokedDelegationForUserDecryption=t.h,exports.decodeUnwrapRequested=t.g,exports.decodeUnwrappedFinalized=t._,exports.decodeUnwrappedStarted=t.v,exports.decodeWrapped=t.y,exports.delegateForUserDecryptionContract=t.O,exports.extractEncryptedHandles=t.n,exports.finalizeUnwrapContract=r.C,exports.findDelegatedForUserDecryption=t.b,exports.findRevokedDelegationForUserDecryption=t.x,exports.findUnwrapRequested=t.S,exports.findWrapped=t.C,exports.getConfidentialTokenAddressContract=r.t,exports.getDelegationExpiryContract=t.k,exports.getTokenAddressContract=r.n,exports.getTokenPairContract=r.r,exports.getTokenPairsContract=r.i,exports.getTokenPairsLengthContract=r.a,exports.getTokenPairsSliceContract=r.o,exports.indexedDBStorage=h,exports.inferredTotalSupplyContract=r.w,exports.isConfidentialTokenContract=r.u,exports.isConfidentialTokenValidContract=r.s,exports.isConfidentialWrapperContract=r.d,exports.isHandleDelegatedContract=t.A,exports.isOperatorContract=r._,exports.isZeroHandle=t.B,exports.loadPendingUnshield=ie,exports.matchAclRevert=p,exports.matchZamaError=e.s,exports.memoryStorage=N,exports.nameContract=t.L,exports.parseActivityFeed=t.r,exports.rateContract=r.v,exports.revokeDelegationContract=t.j,exports.savePendingUnshield=re,exports.setOperatorContract=r.y,exports.sortByBlockNumber=t.i,exports.supportsInterfaceContract=r.f,exports.symbolContract=t.R,exports.totalSupplyContract=r.b,exports.underlyingContract=r.T,exports.unwrapContract=r.x,exports.unwrapFromBalanceContract=r.S,exports.wrapContract=r.E;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./wrappers-registry.cjs`),n=require(`./encryption.cjs`),r=require(`./token.cjs`),i=require(`./relayer-cleartext.cjs`),a=require(`./base-signer.cjs`),o=require(`./validation.cjs`),s=require(`./assertions.cjs`),c=require(`./chains.cjs`);let l=require(`viem`),u=require(`zod/mini`);var d=class extends e.r{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},f=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},p=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},b=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},x=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},S=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},C=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};function w(r,i,a=!1){if(r instanceof n.t||r instanceof p||r instanceof e.n||r instanceof C||r instanceof t.H||r instanceof t.V)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new p(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new C(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet — after granting delegation, allow 1–2 minutes for cross-chain synchronization before retrying. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):o===void 0?new n.t(i,{cause:r}):new e.n(r instanceof Error?r.message:i,o,{cause:r})}function ee(){return{type:`cleartext`,createRelayer:t=>{if(!t.executorAddress)throw new e.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new i.t(t)}}}function T(e){return e.startsWith(`0x`)?e:`0x${e}`}const te=[{type:`function`,name:`transferAndCall`,stateMutability:`nonpayable`,inputs:[{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`data`,type:`bytes`}],outputs:[{name:``,type:`bool`}]}];function E(e,t,n,r=`0x`){return{address:e,abi:te,functionName:`transferAndCall`,args:[t,n,r]}}function ne(e){return a.i(e.signer,e.provider,e)}var D=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.relayer,this.#r=e.decryptionService}#i(e){return t.B(this.#r,e)}async userDecrypt(e){let t=this.#i(`userDecrypt`),n=await r.a(`userDecrypt`,this.#e,this.#t);return t.userDecrypt(e,n.address)}async delegatedDecrypt(e,t,n=t){let i=this.#i(`delegatedDecrypt`),a=await r.a(`delegatedDecrypt`,this.#e,this.#t);return i.delegatedUserDecrypt(e,t,a.address,n)}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.#n.publicDecrypt(e)}catch(e){throw w(e,`Public decryption failed`)}}async delegatedBatchDecrypt({encryptedInputs:e,delegatorAddress:t,accountAddress:n=t,maxConcurrency:i}){let a=this.#i(`delegatedBatchDecrypt`),o=await r.a(`delegatedBatchDecrypt`,this.#e,this.#t);return a.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:o.address,accountAddress:n,maxConcurrency:i})}},O=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.B(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:n}){let i=this.#r(`delegateDecryption`),a=await r.a(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:n})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let n=this.#r(`revokeDelegation`),i=await r.a(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(n,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}},k=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService}#i(e){return t.B(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#i(`grantPermit`);await r.o(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let n=this.#i(`grantDelegationPermit`);await r.o(`grantDelegationPermit`,this.#e,this.#t),await n.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmKeypair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmKeypair(t.address)}async revokePermits(e){let n=this.#i(`revokePermits`),i=(0,l.getAddress)((await r.a(`revokePermits`,this.#e,this.#t)).address);try{await n.revokePermits(e)}finally{await t.F(`clear decrypt cache`,()=>this.#n.clearForRequester(i))}}async clear(){let e=this.#i(`clear`),n=(0,l.getAddress)((await r.a(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await t.F(`clear decrypt cache`,()=>this.#n.clearForRequester(n))}}};const re=u.z.union([u.z.bigint(),u.z.boolean(),a.p]),ie=u.z.array(u.z.string());var ae=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#s(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=re.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return console.warn(`[zama-sdk] CachingService.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#s(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#l(i).catch(e=>{console.warn(`[zama-sdk] CachingService index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] CachingService.set failed:`,e)}}async delete(e,t,n){let r=this.#s(e,t,n);this.#r=this.#r.then(()=>this.#i(r).catch(e=>{console.warn(`[zama-sdk] CachingService.delete failed:`,e)})),await this.#r}async clearForRequester(e){this.#r=this.#r.then(()=>this.#a(e).catch(e=>{console.warn(`[zama-sdk] CachingService.clearForRequester failed:`,e)})),await this.#r}async clearAll(){this.#r=this.#r.then(()=>this.#o().catch(e=>{console.warn(`[zama-sdk] CachingService.clearAll failed:`,e)})),await this.#r}async#i(e){await this.#e.delete(e).catch(()=>{});let t=await this.#c(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#n,n)}async#a(e){let t=(0,l.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#c(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,a)}async#o(){let e=await this.#c();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#s(e,t,n){return`${this.#t}:${(0,l.getAddress)(e)}:${(0,l.getAddress)(t)}:${n.toLowerCase()}`}async#c(){let e=await this.#e.get(this.#n);if(e===null)return[];let t=ie.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#n).catch(()=>{}),[])}async#l(e){let t=await this.#c();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}};function oe(e,t){let r=j(e,t);if(!r)throw new n.t(`No permit covers contract ${t} after allow()`);return A(e,r)}function se(e,t){let r=j(e,t);if(!r)throw new n.t(`No delegated permit covers contract ${t} after allow()`);return{...A(e,r),delegatorAddress:r.delegatorAddress}}function A(e,t){return{signedContractAddresses:t.signedContractAddresses,privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,signature:t.signature,startTimestamp:t.startTimestamp,durationDays:t.durationDays}}function j(e,t){let n=a.f(t);return e.permits.find(e=>e.signedContractAddresses.includes(n))}var ce=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,relayer:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async userDecrypt(e,t){let n=(0,l.getAddress)(t);return this.#a(e,{requesterAddress:n,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:r})=>this.#r.userDecrypt({encryptedValues:r,contractAddress:t,...oe(e,t),signerAddress:n}),errorMessage:`Failed to decrypt handles`})}async delegatedUserDecrypt(e,t,n,r){let i=(0,l.getAddress)(t),a=(0,l.getAddress)(n);return this.#a(e,{requesterAddress:(0,l.getAddress)(r),resolveCredentials:e=>this.#t.grantPermit(e,i),validate:e=>this.#l(e,{delegatorAddress:i,delegateAddress:a}),decryptContract:async({credentials:e,contractAddress:t,encryptedValues:n})=>this.#r.delegatedUserDecrypt({encryptedValues:n,contractAddress:t,...se(e,t),delegateAddress:a}),errorMessage:`Failed to decrypt delegated handles`,delegated:!0})}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:n,accountAddress:i,maxConcurrency:a=5}){let o=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,l.getAddress)(e.contractAddress)}));if(o.length===0)return{items:o};let s=(0,l.getAddress)(i);try{let e=await this.delegatedUserDecrypt(o.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,n,s);for(let t of o)this.#o(t,e);return{items:o}}catch(e){if(r.m(e))throw e;if(o.length===1){let[t=this.#c()]=o;return t.error=this.#s(e,`Failed to decrypt delegated handles`,!0),{items:o}}}return await r.r(o.map(e=>async()=>{try{let r=await this.delegatedUserDecrypt([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,n,s);this.#o(e,r)}catch(t){if(r.m(t))throw t;e.error=this.#s(t,`Failed to decrypt delegated handles`,!0)}}),a),{items:o}}async#a(e,t){if(e.length===0)return{};let n=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,l.getAddress)(e.contractAddress)})),i={},a=[];for(let e of n)r.p(e.encryptedValue)?i[e.encryptedValue]=0n:a.push(e);if(a.length===0)return i;let o=Array.from(new Set(n.map(e=>e.contractAddress))),c=Array.from(new Set(a.map(e=>e.contractAddress)));t.validate&&await t.validate(c);let u=[];for(let e of a){let n=await this.#e.get(t.requesterAddress,e.contractAddress,e.encryptedValue);n===null?u.push(e):i[e.encryptedValue]=n}if(u.length===0)return i;let d=await t.resolveCredentials(o),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.encryptedValue):f.set(e.contractAddress,[e.encryptedValue])}let p=Date.now(),m=u.map(e=>e.encryptedValue);try{this.#i({type:r.i.DecryptStart,encryptedValues:m}),await r.r([...f.entries()].map(([e,n])=>async()=>{let r=await t.decryptContract({credentials:d,contractAddress:e,encryptedValues:n});for(let[n,a]of Object.entries(r))i[n]=a,await this.#e.set(t.requesterAddress,e,n,a)}),5);let e={};for(let t of m){let n=i[t];n!==void 0&&(e[t]=n)}return this.#i({type:r.i.DecryptEnd,durationMs:Date.now()-p,encryptedValues:m,result:e}),i}catch(e){throw this.#i({type:r.i.DecryptError,error:s.s(e),durationMs:Date.now()-p,encryptedValues:m}),w(e,t.errorMessage,t.delegated)}}#o(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n.t(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#s(t,n,r=!1){return t instanceof e.r?t:w(t,n,r)}#c(){throw new n.t(`Batch delegated decryption invariant failed: missing item`)}async#l(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function le(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const M={AlreadyDelegatedOrRevokedInSameBlock:e=>new h(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new b(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new x(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new m(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new y(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new S(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new v(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new g(`Cannot revoke: no active delegation exists.`,{cause:e})};function ue(e){return e in M}function de(e,t){let n=le(e);if(n&&ue(n))return M[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(M))if(r.includes(e))return n(t);return null}var fe=class{#e;#t;#n;constructor({provider:e,relayer:t,emitEvent:n=()=>{}}){this.#e=e,this.#t=t,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i,expirationDate:a}){if(a&&a.getTime()<Date.now()+36e5)throw new S(`Expiration date must be at least 1 hour in the future`);let o=(0,l.getAddress)(t),s=(0,l.getAddress)(n),c=(0,l.getAddress)(i);if(s===c)throw new m(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===o)throw new y(`Delegate address cannot be the same as the contract address (${o}).`);let u=await this.#t.getAclAddress(),d=a?BigInt(Math.floor(a.getTime()/1e3)):r.s,f;try{f=await this.getDelegationExpiry({contractAddress:o,delegatorAddress:c,delegateAddress:s})}catch(e){console.warn(`[zama-sdk] delegateDecryption: pre-flight expiry check failed:`,e),f=-1n}if(f===d)throw new v(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);return this.#r({operation:`delegateDecryption`,signer:e,contractAddress:t,config:r.c(u,s,o,d)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:i}){let a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=(0,l.getAddress)(i),c=await this.#t.getAclAddress(),u;try{u=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:s,delegateAddress:o})}catch(e){console.warn(`[zama-sdk] revokeDelegation: pre-flight expiry check failed:`,e),u=1n}if(u===0n)throw new g(`No active delegation found for delegate ${o} on contract ${a}.`);return this.#r({operation:`revokeDelegation`,signer:e,contractAddress:t,config:r.d(c,o,a)})}async isDelegated(e){let t=await this.getDelegationExpiry(e);return t===0n?!1:t===r.s?!0:t>await this.#e.getBlockTimestamp()}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let i=await this.#t.getAclAddress();return this.#e.readContract(r.l(i,(0,l.getAddress)(t),(0,l.getAddress)(n),(0,l.getAddress)(e)))}async#r({operation:e,signer:t,contractAddress:n,config:i}){try{return await r.n({operation:e,signer:t,provider:this.#e,config:i,emit:e=>this.#n(e,n)})}catch(e){throw this.#i(e),e}}#i(e){if(!(e instanceof r.b))return;let t=de(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof g||t instanceof _){let n=(0,l.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let i=(0,l.getAddress)(e),a=(0,l.getAddress)(t),o=(0,l.getAddress)(n),s=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:a,delegateAddress:o});if(s===0n)throw new g(`No active delegation from ${a} to ${o} for ${i}`);if(s!==r.s&&s<=await this.#e.getBlockTimestamp())throw new _(`Delegation from ${a} to ${o} for ${i} has expired`)}},pe=class{#e;#t;constructor({relayer:e,emitEvent:t}){this.#e=e,this.#t=t}async encrypt(t){let i=Date.now();try{this.#t({type:r.i.EncryptStart},t.contractAddress);let e=await this.#e.encrypt(t);return this.#t({type:r.i.EncryptEnd,durationMs:Date.now()-i},t.contractAddress),e}catch(a){throw this.#t({type:r.i.EncryptError,error:s.s(a),durationMs:Date.now()-i},t.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}},me=class{#e;#t;#n;#r;#i=new Set;#a;constructor(e){this.#e=e.signer,this.#t=e.relayer,this.#n=e.cachingService,this.#r=e.credentialService,this.#e&&(this.#a=this.#e.walletAccount.subscribe(e=>{this.#o(e).catch(e=>{console.warn(`[zama-sdk] wallet account handler failed:`,e)})}))}onWalletAccountChange(e){return this.#i.add(e),()=>{this.#i.delete(e)}}dispose(){this.#a?.(),this.#a=void 0,this.#i.clear()}async#o(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.F(`switch relayer chain`,()=>this.#t.switchChain(i));let a=this.#r;a&&await t.F(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r)),n&&await t.F(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address)),await Promise.all(Array.from(this.#i,n=>t.F(`wallet account listener`,()=>n(e))))}};function N(e){return(0,l.keccak256)((0,l.toBytes)(e))}const P={ConfidentialTransfer:N(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:N(`Wrapped(address,uint256)`),UnwrapRequested:N(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:N(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function F(e){return(0,l.getAddress)(T(e.slice(-40)))}function I(e){return BigInt(e)}function L(e){return e}function R(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function z(e,t){return(0,l.getAddress)(T(R(e,t).slice(-40)))}function B(e,t){return BigInt(`0x`+R(e,t))}function he(e,t){return BigInt(`0x`+R(e,t))!==0n}function V(e,t){return T(R(e,t))}function H(e){return e.topics[0]!==P.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmountHandle:L(e.topics[3])}}function U(e){return e.topics[0]!==P.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:F(e.topics[1]),amountIn:B(e.data,0)}}function W(e){return e.topics[0]!==P.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:L(e.topics[2]),encryptedAmount:V(e.data,0)}}function G(e){return e.topics[0]!==P.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:L(e.topics[2]),encryptedAmount:V(e.data,0),cleartextAmount:B(e.data,1)}}function K(e){return e.topics[0]!==P.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:I(e.topics[1]),txId:I(e.topics[2]),to:F(e.topics[3]),returnVal:he(e.data,0),refund:z(e.data,1),requestedAmount:V(e.data,2),burnAmount:V(e.data,3)}}function q(e){return H(e)??U(e)??W(e)??G(e)??K(e)}function ge(e){let t=[];for(let n of e){let e=q(n);e&&t.push(e)}return t}function J(e){for(let t of e){let e=W(t);if(e)return e}return null}function _e(e){for(let t of e){let e=U(t);if(e)return e}return null}const ve=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrapFinalized,P.UnwrappedStarted],Y={DelegatedForUserDecryption:N(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:N(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function X(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:z(e.data,0),delegationCounter:B(e.data,1),oldExpirationDate:B(e.data,2),newExpirationDate:B(e.data,3)}}function Z(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:z(e.data,0),delegationCounter:B(e.data,1),oldExpirationDate:B(e.data,2)}}function Q(e){return X(e)??Z(e)}function ye(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function be(e){for(let t of e){let e=X(t);if(e)return e}return null}function xe(e){for(let t of e){let e=Z(t);if(e)return e}return null}const Se=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];var Ce=class extends r.t{#e;#t=null;#n=null;#r(e){try{return s.r(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.I(e,{cause:n})}}async underlying(){return this.#o()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#o();this.#n=await this.sdk.provider.readContract(t.p(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#o();return this.sdk.provider.readContract(t.h(n,(0,l.getAddress)(e),this.address))}async shield(n,i){let a=await r.a(`shield`,this.sdk.signer,this.sdk.provider),o=await this.isPayable(),c=await this.#o(),u=(0,l.getAddress)(a.address),d;try{d=await this.sdk.provider.readContract(t._(c,u))}catch(t){throw t instanceof e.r?t:new r.g(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:s.s(t)})}if(d<n)throw new r.v(`Insufficient ERC-20 balance: requested ${n}, available ${d} (token: ${c})`,{requested:n,available:d,token:c});return o?this.#i(n,c,u,i):this.#a(n,u,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,l.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:E(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#c(e,i===`max`,r);let a=r?.to?(0,l.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.T(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let n=await r.a(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#o(),a=(0,l.getAddress)(n.address),o=e??2n**256n-1n;return o>0n&&await this.sdk.provider.readContract(t.h(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.g(i,this.address,o)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.F(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash)),this.#s(l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.F(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash)),this.#s(r.txHash,n,e)}async resumeUnshield(e,t){return this.#s(e,crypto.randomUUID(),t)}async unwrap(e){this.#r(`unwrap`);let i=(0,l.getAddress)((await r.a(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{handles:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i}),[s]=a;if(!s)throw new n.n(`Encryption returned no handles`);return this.submitTransaction({operation:`unwrap`,config:t.N(this.address,i,i,s,o)})}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,l.getAddress)((await r.a(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),i=await this.readConfidentialBalanceOf(e);if(r.p(i))throw new n.t(`Cannot unshield: balance is zero`);return this.submitTransaction({operation:`unwrapAll`,config:t.P(this.address,e,e,i)})}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await r.o(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.publicDecrypt([e]),i=n.clearValues[e];return s.t(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.S(this.address,e,i,n.decryptionProof)})}async#o(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.w(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#s(n,i,a){this.emit({type:r.i.UnshieldPhase1Submitted,txHash:n,operationId:i});let o;try{o=await this.sdk.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new r.b(`Failed to get unshield receipt`,{cause:t})}let s=J(o.logs);if(!s)throw new r.b(`No UnwrapRequested event found in unshield receipt`);this.emit({type:r.i.UnshieldPhase2Started,operationId:i}),t.F(`unshield: onFinalizing`,()=>a?.onFinalizing?.());let c=await this.finalizeUnwrap(s.unwrapRequestId??s.encryptedAmount);return this.emit({type:r.i.UnshieldPhase2Submitted,txHash:c.txHash,operationId:i}),t.F(`unshield: onFinalizeSubmitted`,()=>a?.onFinalizeSubmitted?.(c.txHash)),c}async#c(e,n,i){this.#r(`approveUnderlying`);let a=await this.#o(),o=(0,l.getAddress)((await r.a(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),s=await this.sdk.provider.readContract(t.h(a,o,this.address));if(s>=e)return;s>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(a,this.address,0n)});let c=n?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.g(a,this.address,c),onSubmitted:i?.onApprovalSubmitted})}},we=class{relayer;provider;signer;storage;registry;permits;delegations;decryption;#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#t=e.onEvent??function(){},this.#n=new ae(e.storage),this.#s=new fe({provider:this.provider,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new a.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#e=e.registryTTL,e.signer&&(this.#o=new a.d({relayer:this.relayer,signer:e.signer,keypairTTL:e.keypairTTL,permitTTL:e.permitTTL,storage:this.storage,permitStorage:e.permitStorage}),this.#a=new ce({cache:this.#n,credentialService:this.#o,delegationService:this.#s,relayer:this.relayer,emitEvent:this.emitEvent.bind(this)})),this.#i=new pe({relayer:this.relayer,emitEvent:this.emitEvent.bind(this)}),this.#r=new me({signer:e.signer,relayer:this.relayer,cachingService:this.#n,credentialService:this.#o}),this.permits=new k({signer:this.signer,provider:this.provider,cachingService:this.#n,credentialService:this.#o}),this.delegations=new O({signer:this.signer,provider:this.provider,delegationService:this.#s}),this.decryption=new D({signer:this.signer,provider:this.provider,relayer:this.relayer,decryptionService:this.#a})}onWalletAccountChange(e){return this.#r.onWalletAccountChange(e)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new a.o({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async encrypt(e){return this.#i.encrypt(e)}createToken(e){return new r.t(this,e)}createWrappedToken(e){return new Ce(this,e)}dispose(){this.#r.dispose()}terminate(){this.dispose(),this.relayer.terminate(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${a.f(e)}`}const Te=u.z.union([u.z.pipe(a.m,u.z.transform(e=>({unwrapTxHash:e}))),u.z.pipe(u.z.object({version:u.z.literal(1),unwrapTxHash:a.m,unwrapRequestId:u.z.optional(a.m)}),u.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function Ee(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function De(e,t){return(await Oe(e,t))?.unwrapTxHash??null}async function Oe(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=Te.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function ke(e,t){await e.delete($(t))}var Ae=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const je=new Ae;exports.ACL_TOPICS=Se,exports.AclPausedError=x,exports.AclTopics=Y,exports.BalanceCheckUnavailableError=r.h,exports.BaseSigner=a.t,exports.ChainMismatchError=r.y,exports.ChromeSessionStorage=Ae,exports.ConfigurationError=e.t,exports.Decryption=D,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=a.a,exports.DelegationContractIsSelfError=b,exports.DelegationCooldownError=h,exports.DelegationDelegateEqualsContractError=y,exports.DelegationExpirationTooSoonError=S,exports.DelegationExpiredError=_,exports.DelegationExpiryUnchangedError=v,exports.DelegationNotFoundError=g,exports.DelegationNotPropagatedError=C,exports.DelegationSelfNotAllowedError=m,exports.Delegations=O,exports.ERC1363_INTERFACE_ID=t.c,exports.ERC20ReadFailedError=r.g,exports.ERC7984_INTERFACE_ID=t.l,exports.ERC7984_WRAPPER_INTERFACE_ID=t.u,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=o.n,exports.InsufficientConfidentialBalanceError=r._,exports.InsufficientERC20BalanceError=r.v,exports.InvalidKeypairError=f,exports.KeypairExpiredError=d,exports.MemoryStorage=a.l,exports.MutableWalletAccountStore=a.n,exports.NoCiphertextError=p,exports.Permits=k,exports.RelayerRequestFailedError=e.n,exports.SignerNotConfiguredError=t.I,exports.SignerRequiredError=t.L,exports.SigningFailedError=t.V,exports.SigningRejectedError=t.H,exports.TOKEN_TOPICS=ve,exports.Token=r.t,exports.Topics=P,exports.TransactionRevertedError=r.b,exports.WalletAccountNotReadyError=t.R,exports.WalletNotConnectedError=t.z,exports.WrappedToken=Ce,exports.WrappersRegistry=a.o,exports.ZERO_HANDLE=r.f,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=we,exports.ZamaSDKEvents=r.i,exports.allowanceContract=t.h,exports.anvil=c.t,exports.approveContract=t.g,exports.balanceOfContract=t._,exports.chains=c.n,exports.chromeSessionStorage=je,exports.clearPendingUnshield=ke,exports.cleartext=ee,exports.confidentialBalanceOfContract=t.E,exports.confidentialTotalSupplyContract=t.D,exports.confidentialTransferContract=t.O,exports.confidentialTransferFromContract=t.k,exports.createConfig=ne,exports.createWalletAccountStore=a.r,exports.decimalsContract=t.v,exports.decodeAclEvent=Q,exports.decodeAclEvents=ye,exports.decodeConfidentialTransfer=H,exports.decodeDelegatedForUserDecryption=X,exports.decodeOnChainEvent=q,exports.decodeOnChainEvents=ge,exports.decodeRevokedDelegationForUserDecryption=Z,exports.decodeUnwrapFinalized=G,exports.decodeUnwrapRequested=W,exports.decodeUnwrappedStarted=K,exports.decodeWrapped=U,exports.delegateForUserDecryptionContract=r.c,exports.finalizeUnwrapContract=t.S,exports.findDelegatedForUserDecryption=be,exports.findRevokedDelegationForUserDecryption=xe,exports.findUnwrapRequested=J,exports.findWrapped=_e,exports.getConfidentialTokenAddressContract=t.t,exports.getDelegationExpiryContract=r.l,exports.getTokenAddressContract=t.n,exports.getTokenPairContract=t.r,exports.getTokenPairsContract=t.i,exports.getTokenPairsLengthContract=t.a,exports.getTokenPairsSliceContract=t.o,exports.hardhat=c.r,exports.hoodi=c.i,exports.indexedDBStorage=o.r,exports.inferredTotalSupplyContract=t.C,exports.isConfidentialTokenContract=t.d,exports.isConfidentialTokenValidContract=t.s,exports.isConfidentialWrapperContract=t.f,exports.isHandleDelegatedContract=r.u,exports.isOperatorContract=t.A,exports.isZeroHandle=r.p,exports.loadPendingUnshield=De,exports.loadPendingUnshieldRequest=Oe,exports.mainnet=c.a,exports.matchZamaError=e.a,exports.memoryStorage=a.u,exports.nameContract=t.b,exports.rateContract=t.j,exports.resolveChainRelayers=a.s,exports.resolveStorage=a.c,exports.revokeDelegationContract=r.d,exports.savePendingUnshield=Ee,exports.sepolia=c.o,exports.setOperatorContract=t.M,exports.supportsInterfaceContract=t.m,exports.symbolContract=t.x,exports.transferAndCallContract=E,exports.underlyingContract=t.w,exports.unwrapContract=t.N,exports.unwrapFromBalanceContract=t.P,exports.wrapContract=t.T;
|
|
515
2
|
//# sourceMappingURL=index.cjs.map
|