@medialane/sdk 0.210.0 → 0.211.0
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/dist/{chunk-W3XFKULQ.cjs → chunk-IE2YYAF5.cjs} +36 -10
- package/dist/chunk-IE2YYAF5.cjs.map +1 -0
- package/dist/{chunk-BFG3VTJQ.js → chunk-PVU5AYOO.js} +35 -11
- package/dist/chunk-PVU5AYOO.js.map +1 -0
- package/dist/starknet/index.cjs +71 -63
- package/dist/starknet/index.d.cts +1 -1
- package/dist/starknet/index.d.ts +1 -1
- package/dist/starknet/index.js +1 -1
- package/dist/wallet/index.cjs +67 -59
- package/dist/wallet/index.d.cts +15 -5
- package/dist/wallet/index.d.ts +15 -5
- package/dist/wallet/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-BFG3VTJQ.js.map +0 -1
- package/dist/chunk-W3XFKULQ.cjs.map +0 -1
|
@@ -696,9 +696,18 @@ function sponsoredExecutor(deps) {
|
|
|
696
696
|
}
|
|
697
697
|
};
|
|
698
698
|
}
|
|
699
|
+
var SponsoredDeployError = class extends Error {
|
|
700
|
+
constructor(message, status, code) {
|
|
701
|
+
super(message);
|
|
702
|
+
this.status = status;
|
|
703
|
+
this.code = code;
|
|
704
|
+
this.name = "SponsoredDeployError";
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
var isAccountRefusal = (err) => err instanceof SponsoredDeployError && (err.status === 401 || err.status === 409);
|
|
699
708
|
async function describeFailure(res, fallback) {
|
|
700
709
|
const body = await res.json().catch(() => null);
|
|
701
|
-
throw new
|
|
710
|
+
throw new SponsoredDeployError(body?.error || fallback, res.status, body?.code);
|
|
702
711
|
}
|
|
703
712
|
async function deploySponsored(input) {
|
|
704
713
|
const doFetch = input.fetchImpl ?? fetch;
|
|
@@ -726,7 +735,7 @@ async function deploySponsored(input) {
|
|
|
726
735
|
const executeRes = await doFetch(`${base}/execute`, {
|
|
727
736
|
method: "POST",
|
|
728
737
|
headers: { "Content-Type": "application/json" },
|
|
729
|
-
body: JSON.stringify({ ownerAddress: input.ownerAddress, typedData, signature, deployment, calls })
|
|
738
|
+
body: JSON.stringify({ ownerAddress: input.ownerAddress, typedData, signature, deployment, calls, replace: input.replace === true })
|
|
730
739
|
});
|
|
731
740
|
if (!executeRes.ok) {
|
|
732
741
|
await describeFailure(executeRes, "We couldn't complete your wallet deployment. Please try again.");
|
|
@@ -765,7 +774,7 @@ async function waitUntilDeployed(provider, address, timeoutMs = 9e4, sleep = (ms
|
|
|
765
774
|
wait = Math.min(Math.round(wait * 1.5), 5e3);
|
|
766
775
|
}
|
|
767
776
|
}
|
|
768
|
-
async function deployWallet(deps, wallet) {
|
|
777
|
+
async function deployWallet(deps, wallet, replace) {
|
|
769
778
|
const sponsored = deps.deploySponsoredImpl ?? deploySponsored;
|
|
770
779
|
const selfFunded = deps.deploySelfFundedImpl ?? deploySelfFunded;
|
|
771
780
|
if (deps.deployProxyUrl) {
|
|
@@ -774,9 +783,11 @@ async function deployWallet(deps, wallet) {
|
|
|
774
783
|
proxyUrl: deps.deployProxyUrl,
|
|
775
784
|
provider: deps.provider(),
|
|
776
785
|
fetchImpl: deps.fetchImpl,
|
|
786
|
+
replace,
|
|
777
787
|
...wallet
|
|
778
788
|
});
|
|
779
789
|
} catch (sponsoredErr) {
|
|
790
|
+
if (replace || isAccountRefusal(sponsoredErr)) throw sponsoredErr;
|
|
780
791
|
try {
|
|
781
792
|
await selfFunded({ provider: deps.provider(), ...wallet });
|
|
782
793
|
} catch (selfFundedErr) {
|
|
@@ -790,9 +801,17 @@ async function deployWallet(deps, wallet) {
|
|
|
790
801
|
}
|
|
791
802
|
await (deps.waitUntilDeployedImpl ?? waitUntilDeployed)(deps.provider(), wallet.ownerAddress);
|
|
792
803
|
}
|
|
804
|
+
async function unfinishedReplacement(deps) {
|
|
805
|
+
const pending = deps.store.loadPending();
|
|
806
|
+
if (!pending) return null;
|
|
807
|
+
const deployed = await (deps.isDeployedImpl ?? isDeployed)(deps.provider(), pending.address).catch(() => true);
|
|
808
|
+
return deployed ? null : pending;
|
|
809
|
+
}
|
|
793
810
|
async function completeDeployment(deps, onStep, options = {}) {
|
|
794
|
-
|
|
795
|
-
|
|
811
|
+
const pending = await unfinishedReplacement(deps);
|
|
812
|
+
const replacing = options.replace === true || pending !== null;
|
|
813
|
+
let sealed = replacing ? pending : deps.store.load();
|
|
814
|
+
if (!replacing && sealed && await (deps.isDeployedImpl ?? isDeployed)(deps.provider(), sealed.address).catch(() => false)) {
|
|
796
815
|
sealed = null;
|
|
797
816
|
}
|
|
798
817
|
let privateKeyHex;
|
|
@@ -801,12 +820,17 @@ async function completeDeployment(deps, onStep, options = {}) {
|
|
|
801
820
|
const created = await deps.passkey.createOwnerKey();
|
|
802
821
|
sealed = created.sealed;
|
|
803
822
|
privateKeyHex = created.privateKeyHex;
|
|
804
|
-
deps.store.
|
|
823
|
+
if (replacing) deps.store.savePending(sealed);
|
|
824
|
+
else deps.store.save(sealed);
|
|
805
825
|
} else {
|
|
806
826
|
privateKeyHex = await deps.passkey.unlockOwnerKey(sealed);
|
|
807
827
|
}
|
|
808
828
|
onStep("deploying");
|
|
809
|
-
await deployWallet(deps, { ownerAddress: sealed.address, ownerPubKey: sealed.ownerPubKey, privateKeyHex });
|
|
829
|
+
await deployWallet(deps, { ownerAddress: sealed.address, ownerPubKey: sealed.ownerPubKey, privateKeyHex }, replacing);
|
|
830
|
+
if (replacing) {
|
|
831
|
+
deps.store.save(sealed);
|
|
832
|
+
deps.store.clearPending();
|
|
833
|
+
}
|
|
810
834
|
deps.store.notifyChange();
|
|
811
835
|
return { sealed };
|
|
812
836
|
}
|
|
@@ -817,7 +841,7 @@ function createDeploymentCoordinator(execute) {
|
|
|
817
841
|
return {
|
|
818
842
|
run(onStep, options = {}) {
|
|
819
843
|
if (inFlight) {
|
|
820
|
-
if (options.
|
|
844
|
+
if (options.replace) {
|
|
821
845
|
return Promise.reject(new Error("A wallet setup is already in progress."));
|
|
822
846
|
}
|
|
823
847
|
if (currentStep) onStep(currentStep);
|
|
@@ -989,6 +1013,7 @@ exports.InvalidPairingPayloadError = InvalidPairingPayloadError;
|
|
|
989
1013
|
exports.InvalidRecoveryKeyError = InvalidRecoveryKeyError;
|
|
990
1014
|
exports.InvalidStarkPrivateKeyError = InvalidStarkPrivateKeyError;
|
|
991
1015
|
exports.SponsoredCallRejectedError = SponsoredCallRejectedError;
|
|
1016
|
+
exports.SponsoredDeployError = SponsoredDeployError;
|
|
992
1017
|
exports.accountFor = accountFor;
|
|
993
1018
|
exports.allowsFallbackFunding = allowsFallbackFunding;
|
|
994
1019
|
exports.buildAddOwnerCall = buildAddOwnerCall;
|
|
@@ -1030,6 +1055,7 @@ exports.getEscapeSecurityPeriod = getEscapeSecurityPeriod;
|
|
|
1030
1055
|
exports.getGuardians = getGuardians;
|
|
1031
1056
|
exports.getOwners = getOwners;
|
|
1032
1057
|
exports.indexedDbDeviceKeys = indexedDbDeviceKeys;
|
|
1058
|
+
exports.isAccountRefusal = isAccountRefusal;
|
|
1033
1059
|
exports.isDeployed = isDeployed;
|
|
1034
1060
|
exports.isValidStarknetAddress = isValidStarknetAddress;
|
|
1035
1061
|
exports.normalizeWalletAddress = normalizeWalletAddress;
|
|
@@ -1046,5 +1072,5 @@ exports.startSessionRecovery = startSessionRecovery;
|
|
|
1046
1072
|
exports.turnOnRecovery = turnOnRecovery;
|
|
1047
1073
|
exports.unsealPrivateKey = unsealPrivateKey;
|
|
1048
1074
|
exports.waitUntilDeployed = waitUntilDeployed;
|
|
1049
|
-
//# sourceMappingURL=chunk-
|
|
1050
|
-
//# sourceMappingURL=chunk-
|
|
1075
|
+
//# sourceMappingURL=chunk-IE2YYAF5.cjs.map
|
|
1076
|
+
//# sourceMappingURL=chunk-IE2YYAF5.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/starknet/erc20.ts","../src/starknet/services/sponsoredExecutor.ts","../src/starknet/media-wallet/derive.ts","../src/starknet/media-wallet/account.ts","../src/starknet/media-wallet/owners.ts","../src/starknet/media-wallet/deploy.ts","../src/starknet/media-wallet/guardian.ts","../src/starknet/passkey-wallet/crypto.ts","../src/wallet/store.ts","../src/wallet/pairing.ts","../src/wallet/recovery-key.ts","../src/wallet/guardian-status.ts","../src/wallet/addresses.ts","../src/wallet/self-fund-consent.ts","../src/wallet/device-keys.ts","../src/wallet/passkey.ts","../src/wallet/executors.ts","../src/wallet/deployment.ts","../src/wallet/client.ts","../src/session/session-wallet.ts","../src/session/wallet-recovery.ts"],"names":["UserFacingError","extract","sha256","expand","num","ec","hash","STARKNET_MEDIAWALLET_CLASS_HASH","normalizeAddress","validateAndParseAddress","PasskeyUnsupportedError","PasskeyCancelledError","DeviceKeyMissingError","Account","getTokenBySymbol","consented","starknetTypedData","stark","getCoordinates","sponsored","selfFunded","run","ApiClient"],"mappings":";;;;;;;;;AAEA,eAAsB,YAAA,CACpB,QAAA,EACA,KAAA,EACA,MAAA,EACiB;AACjB,EAAA,MAAM,IAAA,GAAO,CAAC,UAAA,KAAuB,QAAA,CAAS,aAAa,EAAE,eAAA,EAAiB,KAAA,EAAO,UAAA,EAAY,QAAA,EAAU,CAAC,MAAM,CAAA,IAAK,QAAQ,CAAA;AAC/H,EAAA,MAAM,CAAC,GAAA,GAAM,KAAA,EAAO,IAAA,GAAO,KAAK,CAAA,GAAI,MAAM,IAAA,CAAK,WAAW,CAAA,CAAE,KAAA,CAAM,MAAM,IAAA,CAAK,YAAY,CAAC,CAAA;AAC1F,EAAA,OAAO,MAAA,CAAO,GAAG,CAAA,IAAK,MAAA,CAAO,IAAI,CAAA,IAAK,IAAA,CAAA;AACxC;;;ACmBO,IAAM,0BAAA,GAAN,cAAyCA,iCAAA,CAAgB;AAAA,EAO9D,WAAA,CAAY,OAAA,EAAiB,IAAA,GAA2B,EAAC,EAAG;AAC1D,IAAA,KAAA,CAAM,OAAA,EAAS,EAAE,SAAA,EAAW,KAAA,EAAO,CAAA;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YYAF5.cjs","sourcesContent":["import type { ProviderInterface } from \"starknet\";\n\nexport async function erc20Balance(\n provider: Pick<ProviderInterface, \"callContract\">,\n token: string,\n holder: string,\n): Promise<bigint> {\n const read = (entrypoint: string) => provider.callContract({ contractAddress: token, entrypoint, calldata: [holder] }, \"latest\");\n const [low = \"0x0\", high = \"0x0\"] = await read(\"balanceOf\").catch(() => read(\"balance_of\"));\n return BigInt(low) + (BigInt(high) << 128n);\n}\n","import type { FetchLike } from \"../../utils/fetch.js\";\nimport type { TypedData } from \"starknet\";\nimport { UserFacingError } from \"../../errors.js\";\n\nexport interface TypedDataSigner {\n address: string;\n signTypedData(typedData: TypedData): Promise<string[]>;\n}\n\nexport interface SponsoredExecuteConfig {\n proxyUrl: string;\n fetchImpl?: FetchLike;\n headers?: Record<string, string>;\n}\n\nexport type SponsoredRequest = { intentIds: string[] } | { userAddress: string };\n\nexport type SponsoredExecuteResult =\n | { status: \"sponsored\"; transactionHash: string }\n | { status: \"unavailable\"; reason: string };\n\nexport interface SponsoredRejection {\n code?: string;\n detail?: string;\n status?: number;\n stage?: \"build\" | \"execute\";\n requestId?: string;\n}\n\nexport class SponsoredCallRejectedError extends UserFacingError {\n readonly code?: string;\n readonly detail?: string;\n readonly status?: number;\n readonly stage?: \"build\" | \"execute\";\n readonly requestId?: string;\n\n constructor(message: string, info: SponsoredRejection = {}) {\n super(message, { retryable: false });\n this.code = info.code;\n this.detail = info.detail;\n this.status = info.status;\n this.stage = info.stage;\n this.requestId = info.requestId;\n }\n}\n\nexport type SponsorshipFailureCode =\n | \"sponsor_unavailable\"\n | \"credits_exhausted\"\n | \"account_not_deployed\"\n | \"not_executable\"\n | \"invalid_request\"\n | \"not_authorized\"\n | \"rate_limited\"\n | \"may_have_broadcast\";\n\nconst FALLBACK_FUNDING_FAILURES: ReadonlySet<string> = new Set([\"sponsor_unavailable\", \"credits_exhausted\"]);\n\nexport function allowsFallbackFunding(code: string | undefined, status: number, stage: \"build\" | \"execute\"): boolean {\n if (code) return FALLBACK_FUNDING_FAILURES.has(code);\n return stage === \"build\" ? status >= 500 : status === 503;\n}\n\nasync function failureOf(res: Response, fallback: string): Promise<{ reason: string; code?: string; detail?: string; requestId?: string }> {\n const body = (await res.json().catch(() => null)) as { error?: string; code?: string; detail?: string } | null;\n return {\n reason: body?.error || fallback,\n code: typeof body?.code === \"string\" ? body.code : undefined,\n detail: typeof body?.detail === \"string\" ? body.detail : undefined,\n requestId: res.headers.get(\"x-request-id\") ?? undefined,\n };\n}\n\nexport async function executeSponsored(\n config: SponsoredExecuteConfig,\n signer: TypedDataSigner,\n request: SponsoredRequest,\n): Promise<SponsoredExecuteResult> {\n const doFetch = config.fetchImpl ?? fetch;\n const base = config.proxyUrl.replace(/\\/$/, \"\");\n const headers = { \"Content-Type\": \"application/json\", ...config.headers };\n\n const buildRes = await doFetch(`${base}/build`, {\n method: \"POST\",\n headers,\n body: JSON.stringify(request),\n });\n if (!buildRes.ok) {\n const { reason, code, detail, requestId } = await failureOf(buildRes, \"We couldn't prepare this transaction.\");\n if (allowsFallbackFunding(code, buildRes.status, \"build\")) return { status: \"unavailable\", reason };\n throw new SponsoredCallRejectedError(reason, { code, detail, status: buildRes.status, stage: \"build\", requestId });\n }\n const { typedData } = (await buildRes.json()) as { typedData: TypedData };\n\n const signature = await signer.signTypedData(typedData);\n\n const executeRes = await doFetch(`${base}/execute`, {\n method: \"POST\",\n headers,\n body: JSON.stringify({ ...request, typedData, signature }),\n });\n if (!executeRes.ok) {\n const { reason, code, detail, requestId } = await failureOf(executeRes, \"We couldn't submit this transaction.\");\n if (allowsFallbackFunding(code, executeRes.status, \"execute\")) {\n return { status: \"unavailable\", reason };\n }\n throw new SponsoredCallRejectedError(reason, { code, detail, status: executeRes.status, stage: \"execute\", requestId });\n }\n const { transactionHash } = (await executeRes.json()) as { transactionHash: string };\n return { status: \"sponsored\", transactionHash };\n}\n","import { extract, expand } from \"@noble/hashes/hkdf.js\";\nimport { sha256 } from \"@noble/hashes/sha2.js\";\nimport { ec, num } from \"starknet\";\n\nconst STARK_ORDER = 3618502788666131213697322783095070105526743751716087489154079457884512865583n;\n\nexport function deriveOwnerKeyPair(\n secret: Uint8Array,\n recipientId: string,\n): { privateKey: string; publicKey: string } {\n const prk = extract(sha256, secret);\n const okm = expand(sha256, prk, new TextEncoder().encode(recipientId), 32);\n let scalar = BigInt(\"0x\" + Buffer.from(okm).toString(\"hex\")) % STARK_ORDER;\n if (scalar === 0n) scalar = 1n;\n const privateKey = num.toHex(scalar);\n const publicKey = ec.starkCurve.getStarkKey(privateKey);\n return { privateKey, publicKey };\n}\n","import { hash, num, type BigNumberish } from \"starknet\";\nimport { STARKNET_MEDIAWALLET_CLASS_HASH } from \"../../constants.js\";\n\nexport function ownerConstructorCalldata(ownerPubkey: BigNumberish): string[] {\n return [\"0x0\", num.toHex(ownerPubkey), \"0x1\"];\n}\n\nexport function computeAccountAddress(ownerPubkey: BigNumberish, salt: BigNumberish = 0): string {\n return hash.calculateContractAddressFromHash(\n num.toHex(salt),\n STARKNET_MEDIAWALLET_CLASS_HASH,\n ownerConstructorCalldata(ownerPubkey),\n 0,\n );\n}\n","import { hash, num, type BigNumberish, type Call } from \"starknet\";\n\nconst STARKNET_SIGNER_TYPE = \"0x537461726b6e6574205369676e6572\";\nconst OPTION_NONE = \"0x1\";\nconst SIGNER_STARKNET = \"0x0\";\n\nexport function computeOwnerGuid(ownerPubkey: BigNumberish): string {\n return hash.computePoseidonHash(STARKNET_SIGNER_TYPE, num.toHex(ownerPubkey));\n}\n\nfunction changeOwners(accountAddress: string, guidsToRemove: string[], pubkeysToAdd: BigNumberish[]): Call {\n return {\n contractAddress: accountAddress,\n entrypoint: \"change_owners\",\n calldata: [\n num.toHex(guidsToRemove.length),\n ...guidsToRemove,\n num.toHex(pubkeysToAdd.length),\n ...pubkeysToAdd.flatMap((p) => [SIGNER_STARKNET, num.toHex(p)]),\n OPTION_NONE,\n ],\n };\n}\n\nexport function buildAddOwnerCall(accountAddress: string, addOwnerPubkey: BigNumberish): Call {\n return changeOwners(accountAddress, [], [addOwnerPubkey]);\n}\n\nexport function buildRemoveOwnerCall(accountAddress: string, removeOwnerPubkey: BigNumberish): Call {\n return changeOwners(accountAddress, [computeOwnerGuid(removeOwnerPubkey)], []);\n}\n\nexport function buildRemoveOwnerByGuidCall(accountAddress: string, ownerGuid: BigNumberish): Call {\n return changeOwners(accountAddress, [num.toHex(ownerGuid)], []);\n}\n","import { num, type BigNumberish, type DeployAccountContractPayload } from \"starknet\";\nimport { STARKNET_MEDIAWALLET_CLASS_HASH } from \"../../constants.js\";\nimport { ownerConstructorCalldata, computeAccountAddress } from \"./account.js\";\n\nexport function buildDeployAccountParams(\n ownerPubkey: BigNumberish,\n salt: BigNumberish = 0,\n): DeployAccountContractPayload {\n return {\n classHash: STARKNET_MEDIAWALLET_CLASS_HASH,\n constructorCalldata: ownerConstructorCalldata(ownerPubkey),\n addressSalt: num.toHex(salt),\n contractAddress: computeAccountAddress(ownerPubkey, salt),\n };\n}\n","import { num, type Call, type ProviderInterface } from \"starknet\";\nimport { normalizeAddress } from \"../../utils/address.js\";\n\nconst norm = (address: string): string => normalizeAddress(\"STARKNET\", address);\n\nconst SIGNER_TYPE_NAMES = [\"Starknet\", \"Secp256k1\", \"Secp256r1\"] as const;\ntype SignerTypeName = (typeof SIGNER_TYPE_NAMES)[number];\n\nexport interface GuardianInfo {\n type: SignerTypeName;\n guid: string;\n storedValue: string;\n}\n\nfunction encodeFeltArray(items: string[]): string[] {\n return [num.toHex(items.length), ...items];\n}\n\nfunction encodeStarknetSigner(pubkey: string): string[] {\n return [\"0x0\", num.toHex(pubkey)];\n}\n\nfunction encodeStarknetSignerArray(pubkeys: string[]): string[] {\n return [num.toHex(pubkeys.length), ...pubkeys.flatMap(encodeStarknetSigner)];\n}\n\nexport function buildSetFirstGuardianCall(address: string, guardianPubkey: string): Call {\n return {\n contractAddress: norm(address),\n entrypoint: \"change_guardians\",\n calldata: [...encodeFeltArray([]), ...encodeStarknetSignerArray([guardianPubkey])],\n };\n}\n\nexport function buildTriggerEscapeOwnerCall(targetAddress: string, newOwnerPubkey: string): Call {\n return {\n contractAddress: norm(targetAddress),\n entrypoint: \"trigger_escape_owner\",\n calldata: encodeStarknetSigner(newOwnerPubkey),\n };\n}\n\nexport function buildCompleteEscapeOwnerCall(targetAddress: string): Call {\n return { contractAddress: norm(targetAddress), entrypoint: \"escape_owner\", calldata: [] };\n}\n\nexport function buildCancelEscapeCall(address: string): Call {\n return { contractAddress: norm(address), entrypoint: \"cancel_escape\", calldata: [] };\n}\n\nexport function decodeGuardiansInfo(res: string[]): GuardianInfo[] {\n const len = Number(res[0]);\n const out: GuardianInfo[] = [];\n for (let i = 0; i < len; i++) {\n const base = 1 + i * 3;\n out.push({\n type: SIGNER_TYPE_NAMES[Number(res[base])] ?? \"Starknet\",\n guid: res[base + 1],\n storedValue: res[base + 2],\n });\n }\n return out;\n}\n\nexport type EscapeTypeName = \"None\" | \"Guardian\" | \"Owner\";\nexport type EscapeStatusName = \"None\" | \"NotReady\" | \"Ready\" | \"Expired\";\nconst ESCAPE_TYPE_NAMES: EscapeTypeName[] = [\"None\", \"Guardian\", \"Owner\"];\nconst ESCAPE_STATUS_NAMES: EscapeStatusName[] = [\"None\", \"NotReady\", \"Ready\", \"Expired\"];\n\nexport interface EscapeInfo {\n readyAt: number;\n escapeType: EscapeTypeName;\n status: EscapeStatusName;\n}\n\nexport function decodeEscapeAndStatus(res: string[]): EscapeInfo {\n\n const readyAt = Number(res[0]);\n const escapeType = ESCAPE_TYPE_NAMES[Number(res[1])] ?? \"None\";\n const optionTag = Number(res[2]);\n const statusIndex = optionTag === 0 ? 5 : 3;\n const status = ESCAPE_STATUS_NAMES[Number(res[statusIndex])] ?? \"None\";\n return { readyAt, escapeType, status };\n}\n\nexport async function getGuardians(provider: ProviderInterface, address: string): Promise<GuardianInfo[]> {\n const res = await provider.callContract({\n contractAddress: norm(address),\n entrypoint: \"get_guardians_info\",\n calldata: [],\n });\n return decodeGuardiansInfo(res as unknown as string[]);\n}\n\nexport async function getOwners(provider: ProviderInterface, address: string): Promise<GuardianInfo[]> {\n const res = await provider.callContract({\n contractAddress: norm(address),\n entrypoint: \"get_owners_info\",\n calldata: [],\n });\n return decodeGuardiansInfo(res as unknown as string[]);\n}\n\nexport async function getEscape(provider: ProviderInterface, address: string): Promise<EscapeInfo> {\n const res = await provider.callContract({\n contractAddress: norm(address),\n entrypoint: \"get_escape_and_status\",\n calldata: [],\n });\n return decodeEscapeAndStatus(res as unknown as string[]);\n}\n\nexport async function getEscapeSecurityPeriod(provider: ProviderInterface, address: string): Promise<number> {\n const res = await provider.callContract({\n contractAddress: norm(address),\n entrypoint: \"get_escape_security_period\",\n calldata: [],\n });\n return Number((res as unknown as string[])[0]);\n}\n","import { ec, num } from \"starknet\";\n\nexport async function deriveAesKey(prfSecret: Uint8Array, hkdfInfo: Uint8Array): Promise<CryptoKey> {\n const hkdf = await crypto.subtle.importKey(\"raw\", prfSecret as BufferSource, \"HKDF\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey(\n { name: \"HKDF\", hash: \"SHA-256\", salt: new Uint8Array(0), info: hkdfInfo as BufferSource },\n hkdf,\n { name: \"AES-GCM\", length: 256 },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n}\n\nexport function generateDeviceKey(): Promise<CryptoKey> {\n return crypto.subtle.generateKey({ name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n}\n\nexport function generateStarkKeyPair(): { privateKeyHex: string; publicKeyHex: string } {\n const privateKeyHex =\n \"0x\" +\n Array.from(ec.starkCurve.utils.randomPrivateKey())\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return { privateKeyHex, publicKeyHex: ec.starkCurve.getStarkKey(privateKeyHex) };\n}\n\nexport class InvalidStarkPrivateKeyError extends Error {\n constructor(reason: string) {\n super(`Not a valid Starknet private key: ${reason}`);\n this.name = \"InvalidStarkPrivateKeyError\";\n }\n}\n\nexport function starkKeyPairFromPrivateKey(input: string): { privateKeyHex: string; publicKeyHex: string } {\n const trimmed = input.trim().replace(/\\s+/g, \"\");\n const body = trimmed.startsWith(\"0x\") || trimmed.startsWith(\"0X\") ? trimmed.slice(2) : trimmed;\n\n if (body.length === 0) throw new InvalidStarkPrivateKeyError(\"it is empty\");\n if (!/^[0-9a-fA-F]+$/.test(body)) throw new InvalidStarkPrivateKeyError(\"it is not hexadecimal\");\n if (body.length > 64) throw new InvalidStarkPrivateKeyError(\"it is too long\");\n\n const value = BigInt(\"0x\" + body);\n if (value === 0n) throw new InvalidStarkPrivateKeyError(\"it is zero\");\n if (value >= ec.starkCurve.CURVE.n) throw new InvalidStarkPrivateKeyError(\"it is outside the curve order\");\n\n const privateKeyHex = \"0x\" + value.toString(16).padStart(64, \"0\");\n return { privateKeyHex, publicKeyHex: ec.starkCurve.getStarkKey(privateKeyHex) };\n}\n\nexport async function sealPrivateKey(\n aesKey: CryptoKey,\n iv: Uint8Array,\n privateKeyHex: string,\n): Promise<ArrayBuffer> {\n return crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv: iv as BufferSource },\n aesKey,\n new TextEncoder().encode(privateKeyHex),\n );\n}\n\nexport async function unsealPrivateKey(\n aesKey: CryptoKey,\n iv: Uint8Array,\n ciphertext: BufferSource,\n): Promise<string> {\n const buf = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: iv as BufferSource }, aesKey, ciphertext);\n return new TextDecoder().decode(buf);\n}\n\nexport function signWithPrivateKey(privateKeyHex: string, msgHash: string): [string, string] {\n const sig = ec.starkCurve.sign(msgHash, privateKeyHex);\n return [num.toHex(sig.r), num.toHex(sig.s)];\n}\n","import type { SealedOwner } from \"./types.js\";\n\nexport interface OwnerStore {\n load(): SealedOwner | null;\n loadAddress(): string | null;\n save(sealed: SealedOwner): void;\n clear(): void;\n loadPending(): SealedOwner | null;\n savePending(sealed: SealedOwner): void;\n clearPending(): void;\n notifyChange(): void;\n onChange(listener: () => void): () => void;\n}\n\nexport function createOwnerStore(config: { storeKey: string; changeEvent: string }): OwnerStore {\n const { storeKey, changeEvent } = config;\n const announce = (): void => {\n if (typeof window === \"undefined\") return;\n window.dispatchEvent(new Event(changeEvent));\n };\n return {\n load() {\n if (typeof window === \"undefined\") return null;\n try {\n const raw = localStorage.getItem(storeKey);\n return raw ? (JSON.parse(raw) as SealedOwner) : null;\n } catch {\n return null;\n }\n },\n loadAddress() {\n return this.load()?.address ?? null;\n },\n save(sealed) {\n const previous = this.load();\n if (previous && previous.address !== sealed.address) {\n localStorage.setItem(`${storeKey}:${previous.address}`, JSON.stringify(previous));\n }\n localStorage.setItem(storeKey, JSON.stringify(sealed));\n announce();\n },\n clear() {\n localStorage.removeItem(storeKey);\n announce();\n },\n loadPending() {\n if (typeof window === \"undefined\") return null;\n try {\n const raw = localStorage.getItem(`${storeKey}:pending`);\n return raw ? (JSON.parse(raw) as SealedOwner) : null;\n } catch {\n return null;\n }\n },\n savePending(sealed) {\n localStorage.setItem(`${storeKey}:pending`, JSON.stringify(sealed));\n },\n clearPending() {\n localStorage.removeItem(`${storeKey}:pending`);\n },\n notifyChange: announce,\n onChange(listener) {\n window.addEventListener(changeEvent, listener);\n return () => window.removeEventListener(changeEvent, listener);\n },\n };\n}\n","const SCHEME = \"medialane-device\";\nconst VERSION = 1;\nconst LABEL_MAX = 32;\nconst STARK_PRIME = (1n << 251n) + 17n * (1n << 192n) + 1n;\n\nexport class InvalidPairingPayloadError extends Error {\n constructor(message = \"This code is not a Medialane device request.\") {\n super(message);\n this.name = \"InvalidPairingPayloadError\";\n }\n}\n\nexport interface PairingPayload {\n publicKey: string;\n label: string;\n}\n\nfunction normalisePublicKey(input: unknown): string {\n if (typeof input !== \"string\" || !/^0x[0-9a-fA-F]+$/.test(input)) {\n throw new InvalidPairingPayloadError(\"That device key is not valid.\");\n }\n const value = BigInt(input);\n if (value === 0n || value >= STARK_PRIME) {\n throw new InvalidPairingPayloadError(\"That device key is not valid.\");\n }\n return `0x${value.toString(16)}`;\n}\n\nfunction sanitiseLabel(input: unknown): string {\n const raw = typeof input === \"string\" ? input : \"\";\n return raw.replace(/\\s+/g, \" \").trim().slice(0, LABEL_MAX);\n}\n\nexport function encodePairingPayload(payload: PairingPayload): string {\n return JSON.stringify({\n scheme: SCHEME,\n version: VERSION,\n publicKey: normalisePublicKey(payload.publicKey),\n label: sanitiseLabel(payload.label),\n });\n}\n\nexport function parsePairingPayload(encoded: string): PairingPayload {\n let data: Record<string, unknown>;\n try {\n data = JSON.parse(encoded) as Record<string, unknown>;\n } catch {\n throw new InvalidPairingPayloadError();\n }\n if (data === null || typeof data !== \"object\") throw new InvalidPairingPayloadError();\n if (data.scheme !== SCHEME || data.version !== VERSION) throw new InvalidPairingPayloadError();\n return {\n publicKey: normalisePublicKey(data.publicKey),\n label: sanitiseLabel(data.label),\n };\n}\n\nexport function parseAccountAddress(input: string): string {\n const trimmed = typeof input === \"string\" ? input.trim() : \"\";\n if (!/^0x[0-9a-fA-F]{50,64}$/.test(trimmed)) {\n throw new InvalidPairingPayloadError(\"That does not look like an account address.\");\n }\n if (BigInt(trimmed) === 0n) {\n throw new InvalidPairingPayloadError(\"That does not look like an account address.\");\n }\n return trimmed;\n}\n","import { computeAccountAddress } from \"../starknet/media-wallet/account.js\";\nimport { starkKeyPairFromPrivateKey } from \"../starknet/passkey-wallet/crypto.js\";\n\nconst PREFIX = \"medialane-recovery:v1:\";\nconst ADDRESS = /^0x[0-9a-fA-F]{1,64}$/;\n\nexport class InvalidRecoveryKeyError extends Error {\n constructor(message = \"This is not a valid recovery key.\") {\n super(message);\n this.name = \"InvalidRecoveryKeyError\";\n }\n}\n\nexport interface RecoveryKey {\n walletAddress: string;\n privateKey: string;\n}\n\nconst canonicalAddress = (address: string) => `0x${BigInt(address).toString(16).padStart(64, \"0\")}`;\n\nfunction keyPair(privateKey: string) {\n try {\n return starkKeyPairFromPrivateKey(privateKey);\n } catch {\n throw new InvalidRecoveryKeyError();\n }\n}\n\nexport function encodeRecoveryKey(key: RecoveryKey): string {\n if (!ADDRESS.test(key.walletAddress) || BigInt(key.walletAddress) === 0n) throw new InvalidRecoveryKeyError();\n return `${PREFIX}${canonicalAddress(key.walletAddress)}:${keyPair(key.privateKey).privateKeyHex}`;\n}\n\nexport function parseRecoveryKey(input: string): RecoveryKey {\n const trimmed = input.trim();\n if (!trimmed.startsWith(PREFIX)) {\n const { privateKeyHex, publicKeyHex } = keyPair(trimmed);\n return { walletAddress: computeAccountAddress(publicKeyHex, 0), privateKey: privateKeyHex };\n }\n const parts = trimmed.slice(PREFIX.length).split(\":\");\n const [walletAddress, privateKey] = parts;\n if (parts.length !== 2 || !walletAddress || !privateKey || !ADDRESS.test(walletAddress) || BigInt(walletAddress) === 0n) {\n throw new InvalidRecoveryKeyError();\n }\n return { walletAddress: canonicalAddress(walletAddress), privateKey: keyPair(privateKey).privateKeyHex };\n}\n","import type { GuardianInfo, EscapeInfo } from \"../starknet/media-wallet/guardian.js\";\n\nexport type GuardianStatus = { kind: \"none\" } | { kind: \"active\"; guardian: GuardianInfo };\n\nexport function describeGuardianStatus(guardians: GuardianInfo[]): GuardianStatus {\n if (guardians.length === 0) return { kind: \"none\" };\n return { kind: \"active\", guardian: guardians[0] };\n}\n\nexport type RecoveryAction = \"start\" | \"complete\" | \"none\";\n\nexport function describeRecoveryAction(escape: EscapeInfo): RecoveryAction {\n if (escape.escapeType !== \"Owner\") return \"none\";\n if (escape.status === \"Ready\") return \"complete\";\n if (escape.status === \"Expired\") return \"start\";\n return \"none\";\n}\n","import { validateAndParseAddress } from \"starknet\";\nimport { normalizeAddress } from \"../utils/address.js\";\nimport type { ReceiptProviderLike } from \"./types.js\";\n\nexport function normalizeWalletAddress(address: string): string {\n return normalizeAddress(\"STARKNET\", address);\n}\n\nexport function isValidStarknetAddress(address: string): boolean {\n try {\n validateAndParseAddress(address.trim());\n return true;\n } catch {\n return false;\n }\n}\n\nconst CONTRACT_NOT_FOUND = 20;\n\nexport async function isDeployed(provider: ReceiptProviderLike, address: string): Promise<boolean> {\n try {\n await provider.getClassHashAt(normalizeWalletAddress(address));\n return true;\n } catch (err) {\n if ((err as { code?: unknown } | null)?.code === CONTRACT_NOT_FOUND) return false;\n throw err;\n }\n}\n","import type { Call } from \"starknet\";\n\nexport interface SelfFundFeeEstimate {\n feeRaw: bigint;\n unit: string;\n balanceRaw: bigint | null;\n}\n\nexport type SelfFundConsentHandler = (\n feeEstimate: Promise<SelfFundFeeEstimate | null>,\n) => Promise<boolean>;\n\nexport interface SelfFundConsent {\n registerHandler(handler: SelfFundConsentHandler | null): void;\n request(input: { address?: string; calls?: Call[] }): Promise<boolean>;\n}\n\nexport function createSelfFundConsent(\n estimateFee: (address: string, calls: Call[]) => Promise<SelfFundFeeEstimate>,\n): SelfFundConsent {\n let handler: SelfFundConsentHandler | null = null;\n return {\n registerHandler(next) {\n handler = next;\n },\n async request({ address, calls }) {\n if (!handler) return false;\n const feeEstimate =\n address && calls ? estimateFee(address, calls).catch(() => null) : Promise.resolve(null);\n return handler(feeEstimate);\n },\n };\n}\n","export interface DeviceKeyStore {\n save(credentialId: string, key: CryptoKey): Promise<void>;\n load(credentialId: string): Promise<CryptoKey | null>;\n}\n\nconst DATABASE = \"medialane-wallet\";\nconst STORE = \"device-keys\";\n\nfunction open(): Promise<IDBDatabase> {\n return new Promise((resolve, reject) => {\n const request = indexedDB.open(DATABASE, 1);\n request.onupgradeneeded = () => request.result.createObjectStore(STORE);\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n}\n\nasync function run<T>(mode: IDBTransactionMode, act: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {\n const db = await open();\n try {\n return await new Promise<T>((resolve, reject) => {\n const request = act(db.transaction(STORE, mode).objectStore(STORE));\n request.onsuccess = () => resolve(request.result);\n request.onerror = () => reject(request.error);\n });\n } finally {\n db.close();\n }\n}\n\nexport const indexedDbDeviceKeys: DeviceKeyStore = {\n async save(credentialId, key) {\n await run(\"readwrite\", (store) => store.put(key, credentialId));\n },\n async load(credentialId) {\n return ((await run(\"readonly\", (store) => store.get(credentialId))) as CryptoKey | undefined) ?? null;\n },\n};\n","import {\n deriveAesKey,\n generateDeviceKey,\n generateStarkKeyPair,\n sealPrivateKey,\n starkKeyPairFromPrivateKey,\n unsealPrivateKey,\n} from \"../starknet/passkey-wallet/crypto.js\";\nimport { computeAccountAddress } from \"../starknet/media-wallet/account.js\";\nimport type { SealedOwner } from \"./types.js\";\nimport type { RecoveryKey } from \"./recovery-key.js\";\nimport { indexedDbDeviceKeys, type DeviceKeyStore } from \"./device-keys.js\";\nimport { PasskeyCancelledError, DeviceKeyMissingError, PasskeyUnsupportedError, type PasskeyUnsupportedReason } from \"./passkey-errors.js\";\n\nexport { PasskeyCancelledError, DeviceKeyMissingError, PasskeyUnsupportedError, type PasskeyUnsupportedReason };\n\nexport interface PasskeyConfig {\n appName: string;\n relyingPartyName: string;\n relyingPartyId: () => string;\n prfSalt: Uint8Array<ArrayBuffer>;\n hkdfInfo: Uint8Array<ArrayBuffer>;\n passkeyUser: () => Promise<PublicKeyCredentialUserEntity>;\n knownCredentials: () => PublicKeyCredentialDescriptor[];\n credentials?: CredentialsContainer;\n deviceKeys?: DeviceKeyStore;\n randomBytes?: (length: number) => Uint8Array<ArrayBuffer>;\n}\n\nexport interface CreatedOwner {\n sealed: SealedOwner;\n privateKeyHex: string;\n}\n\nexport interface PasskeyOwner {\n createOwnerKey(): Promise<CreatedOwner>;\n unlockOwnerKey(sealed: SealedOwner): Promise<string>;\n sealImportedOwnerKey(recovery: RecoveryKey): Promise<SealedOwner>;\n}\n\ninterface Registration {\n credentialId: string;\n prfFirst: ArrayBuffer | null;\n}\n\ninterface OwnerLock {\n aes: CryptoKey;\n lock?: \"device\";\n}\n\nconst encodeBase64 = (buf: ArrayBuffer | Uint8Array): string => {\n const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);\n let binary = \"\";\n for (const byte of bytes) binary += String.fromCharCode(byte);\n return btoa(binary);\n};\n\nconst decodeBase64 = (value: string): Uint8Array<ArrayBuffer> => {\n const binary = atob(value);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n};\n\nfunction isPasskeyCancellation(err: unknown): boolean {\n const name = (err as { name?: string } | null)?.name;\n return name === \"NotAllowedError\" || name === \"AbortError\";\n}\n\nexport function createPasskeyOwner(config: PasskeyConfig): PasskeyOwner {\n const randomBytes: (length: number) => Uint8Array<ArrayBuffer> =\n config.randomBytes ?? ((length: number) => crypto.getRandomValues(new Uint8Array(length)));\n const credentialsApi = (): CredentialsContainer => {\n const api = config.credentials ?? (typeof navigator === \"undefined\" ? undefined : navigator.credentials);\n if (!api) throw new PasskeyUnsupportedError(\"no-webauthn\");\n return api;\n };\n\n async function registerPasskey(): Promise<Registration> {\n let credential: PublicKeyCredential;\n try {\n credential = (await credentialsApi().create({\n publicKey: {\n challenge: randomBytes(32),\n rp: { name: config.relyingPartyName, id: config.relyingPartyId() },\n user: await config.passkeyUser(),\n excludeCredentials: config.knownCredentials(),\n pubKeyCredParams: [\n { type: \"public-key\", alg: -7 },\n { type: \"public-key\", alg: -257 },\n ],\n authenticatorSelection: {\n authenticatorAttachment: \"platform\",\n residentKey: \"required\",\n userVerification: \"required\",\n },\n extensions: { prf: { eval: { first: config.prfSalt } } } as AuthenticationExtensionsClientInputs,\n },\n })) as PublicKeyCredential;\n } catch (err) {\n if (isPasskeyCancellation(err)) throw new PasskeyCancelledError();\n throw err;\n }\n const prf = (\n credential.getClientExtensionResults() as {\n prf?: { enabled?: boolean; results?: { first?: ArrayBuffer } };\n }\n ).prf;\n return {\n credentialId: encodeBase64(credential.rawId),\n prfFirst: prf?.results?.first ?? null,\n };\n }\n\n async function assertPasskey(\n credentialId: string,\n extensions?: AuthenticationExtensionsClientInputs,\n ): Promise<PublicKeyCredential> {\n try {\n return (await credentialsApi().get({\n publicKey: {\n challenge: randomBytes(32),\n rpId: config.relyingPartyId(),\n allowCredentials: [{ type: \"public-key\", id: decodeBase64(credentialId) }],\n userVerification: \"required\",\n ...(extensions ? { extensions } : {}),\n },\n })) as PublicKeyCredential;\n } catch (err) {\n if (isPasskeyCancellation(err)) throw new PasskeyCancelledError();\n throw err;\n }\n }\n\n async function prfSecret(credentialId: string): Promise<Uint8Array<ArrayBuffer>> {\n const assertion = await assertPasskey(credentialId, {\n prf: { eval: { first: config.prfSalt } },\n } as AuthenticationExtensionsClientInputs);\n const result = (assertion.getClientExtensionResults() as { prf?: { results?: { first?: ArrayBuffer } } }).prf\n ?.results?.first;\n if (!result) throw new PasskeyUnsupportedError(\"no-prf\");\n return new Uint8Array(result);\n }\n\n const deviceKeys = config.deviceKeys ?? indexedDbDeviceKeys;\n\n async function lockFor(registration: Registration): Promise<OwnerLock> {\n if (registration.prfFirst) {\n return { aes: await deriveAesKey(new Uint8Array(registration.prfFirst), config.hkdfInfo) };\n }\n try {\n return { aes: await deriveAesKey(await prfSecret(registration.credentialId), config.hkdfInfo) };\n } catch (err) {\n if (!(err instanceof PasskeyUnsupportedError) || err.reason !== \"no-prf\") throw err;\n }\n const aes = await generateDeviceKey();\n await deviceKeys.save(registration.credentialId, aes);\n return { aes, lock: \"device\" };\n }\n\n async function unlockFor(sealed: SealedOwner): Promise<CryptoKey> {\n if (sealed.lock !== \"device\") return deriveAesKey(await prfSecret(sealed.credentialId), config.hkdfInfo);\n await assertPasskey(sealed.credentialId);\n const aes = await deviceKeys.load(sealed.credentialId);\n if (!aes) throw new DeviceKeyMissingError();\n return aes;\n }\n\n async function seal(aes: CryptoKey, privateKeyHex: string): Promise<{ iv: string; ciphertext: string }> {\n const iv = randomBytes(12);\n const ciphertext = await sealPrivateKey(aes, iv, privateKeyHex);\n return { iv: encodeBase64(iv), ciphertext: encodeBase64(ciphertext) };\n }\n\n return {\n async createOwnerKey() {\n const registration = await registerPasskey();\n const { aes, lock } = await lockFor(registration);\n const { privateKeyHex, publicKeyHex } = generateStarkKeyPair();\n const { iv, ciphertext } = await seal(aes, privateKeyHex);\n return {\n sealed: {\n credentialId: registration.credentialId,\n ownerPubKey: publicKeyHex,\n address: computeAccountAddress(publicKeyHex, 0),\n iv,\n ciphertext,\n ...(lock ? { lock } : {}),\n },\n privateKeyHex,\n };\n },\n\n async unlockOwnerKey(sealed) {\n const aes = await unlockFor(sealed);\n return unsealPrivateKey(aes, decodeBase64(sealed.iv), decodeBase64(sealed.ciphertext));\n },\n\n async sealImportedOwnerKey(recovery) {\n const { privateKeyHex, publicKeyHex } = starkKeyPairFromPrivateKey(recovery.privateKey);\n const registration = await registerPasskey();\n const { aes, lock } = await lockFor(registration);\n const { iv, ciphertext } = await seal(aes, privateKeyHex);\n return {\n credentialId: registration.credentialId,\n ownerPubKey: publicKeyHex,\n address: recovery.walletAddress,\n iv,\n ciphertext,\n ...(lock ? { lock } : {}),\n };\n },\n };\n}\n","import type { FetchLike } from \"../utils/fetch.js\";\nimport { Account, typedData as starknetTypedData, type Call, type ProviderInterface } from \"starknet\";\nimport { signWithPrivateKey } from \"../starknet/passkey-wallet/crypto.js\";\nimport { UserFacingError } from \"../errors.js\";\nimport { executeSponsored } from \"../starknet/services/sponsoredExecutor.js\";\nimport type { SelfFundConsent, SelfFundFeeEstimate } from \"./self-fund-consent.js\";\nimport type { ExecutedTransaction, WalletExecutor } from \"./types.js\";\nimport { getTokenBySymbol } from \"../utils/token.js\";\nimport { erc20Balance } from \"../starknet/erc20.js\";\nimport { getGuardians } from \"../starknet/media-wallet/guardian.js\";\n\nexport const GUARDIAN_WALLET_BUSY = \"This can't go through right now. Please try again in a moment.\";\n\nexport interface SelfFundedDeps {\n provider: () => ProviderInterface;\n}\n\nexport function accountFor(\n provider: ProviderInterface,\n address: string,\n privateKeyHex: string,\n): Account {\n return new Account({ provider, address, signer: privateKeyHex, cairoVersion: \"1\" });\n}\n\nexport async function estimateSelfFundedFee(\n provider: ProviderInterface,\n address: string,\n calls: Call[],\n): Promise<SelfFundFeeEstimate> {\n const account = new Account({ provider, address, signer: \"0x1\", cairoVersion: \"1\" });\n const estimate = await account.estimateInvokeFee(calls);\n const balanceRaw = await feeTokenBalance(provider, address, estimate.unit).catch(() => null);\n return { feeRaw: estimate.overall_fee, unit: estimate.unit, balanceRaw };\n}\n\nasync function feeTokenBalance(provider: ProviderInterface, address: string, unit: string): Promise<bigint> {\n const token = getTokenBySymbol(unit === \"FRI\" ? \"STRK\" : \"ETH\");\n if (!token) throw new Error(`No fee token for unit ${unit}`);\n return erc20Balance(provider, token.address, address);\n}\n\nexport function selfFundedExecutor(deps: SelfFundedDeps): WalletExecutor {\n return {\n async execute({ userAddress, privateKeyHex, calls }): Promise<ExecutedTransaction> {\n const account = accountFor(deps.provider(), userAddress, privateKeyHex);\n const { transaction_hash } = await account.execute(calls);\n return { transactionHash: transaction_hash };\n },\n };\n}\n\nexport interface SponsoredDeps extends SelfFundedDeps {\n proxyUrl: string;\n consent: SelfFundConsent;\n fetchImpl?: FetchLike;\n fallback?: WalletExecutor;\n guardians?: (address: string) => Promise<unknown[]>;\n}\n\nexport function sponsoredExecutor(deps: SponsoredDeps): WalletExecutor {\n const fallback = deps.fallback ?? selfFundedExecutor(deps);\n const guardians = deps.guardians ?? ((address: string) => getGuardians(deps.provider(), address));\n const hasGuardian = async (address: string): Promise<boolean> => {\n try {\n return (await guardians(address)).length > 0;\n } catch {\n return false;\n }\n };\n const refuseSelfFundingWithGuardian = async (address: string): Promise<void> => {\n if (await hasGuardian(address)) throw new UserFacingError(GUARDIAN_WALLET_BUSY);\n };\n return {\n async execute(input): Promise<ExecutedTransaction> {\n const { userAddress, privateKeyHex, calls, intentIds } = input;\n if (!intentIds?.length) {\n await refuseSelfFundingWithGuardian(userAddress);\n const consented = await deps.consent.request({ address: userAddress, calls });\n if (!consented) throw new UserFacingError(\"This action can't be sponsored\");\n return fallback.execute(input);\n }\n const result = await executeSponsored(\n { proxyUrl: deps.proxyUrl, fetchImpl: deps.fetchImpl },\n {\n address: userAddress,\n signTypedData: async (data) =>\n signWithPrivateKey(privateKeyHex, starknetTypedData.getMessageHash(data, userAddress)),\n },\n { intentIds },\n );\n if (result.status === \"sponsored\") return { transactionHash: result.transactionHash };\n\n await refuseSelfFundingWithGuardian(userAddress);\n const consented = await deps.consent.request({ address: userAddress, calls });\n if (!consented) throw new UserFacingError(result.reason);\n return fallback.execute(input);\n },\n };\n}\n","import type { FetchLike } from \"../utils/fetch.js\";\nimport { Account, stark, type ProviderInterface } from \"starknet\";\nimport { getCoordinates } from \"../chains.js\";\nimport { ownerConstructorCalldata } from \"../starknet/media-wallet/account.js\";\nimport { isDeployed } from \"./addresses.js\";\nimport type { ExecutedTransaction, SealedOwner } from \"./types.js\";\n\nexport type DeploymentStep = \"creating-passkey\" | \"deploying\";\n\nexport interface DeploymentResult {\n sealed: SealedOwner;\n}\n\nexport class SponsoredDeployError extends Error {\n constructor(\n message: string,\n readonly status: number,\n readonly code?: string,\n ) {\n super(message);\n this.name = \"SponsoredDeployError\";\n }\n}\n\nexport const isAccountRefusal = (err: unknown): boolean =>\n err instanceof SponsoredDeployError && (err.status === 401 || err.status === 409);\n\nasync function describeFailure(res: Response, fallback: string): Promise<never> {\n const body = (await res.json().catch(() => null)) as { error?: string; code?: string } | null;\n throw new SponsoredDeployError(body?.error || fallback, res.status, body?.code);\n}\n\nexport async function deploySponsored(input: {\n proxyUrl: string;\n provider: ProviderInterface;\n ownerAddress: string;\n ownerPubKey: string;\n privateKeyHex: string;\n salt?: string;\n replace?: boolean;\n fetchImpl?: FetchLike;\n}): Promise<ExecutedTransaction> {\n const doFetch = input.fetchImpl ?? fetch;\n const base = input.proxyUrl.replace(/\\/$/, \"\");\n\n const buildRes = await doFetch(`${base}/build`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({\n ownerPubkey: input.ownerPubKey,\n ownerAddress: input.ownerAddress,\n salt: input.salt ?? \"0x0\",\n }),\n });\n if (!buildRes.ok) {\n await describeFailure(buildRes, \"We couldn't prepare your wallet deployment. Please try again.\");\n }\n const { typedData, deployment, calls } = (await buildRes.json()) as {\n typedData: object;\n deployment: object;\n calls: object[];\n };\n\n const account = new Account({\n provider: input.provider,\n address: input.ownerAddress,\n signer: input.privateKeyHex,\n cairoVersion: \"1\",\n });\n const signature = stark.signatureToHexArray(await account.signMessage(typedData as never));\n\n const executeRes = await doFetch(`${base}/execute`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ ownerAddress: input.ownerAddress, typedData, signature, deployment, calls, replace: input.replace === true }),\n });\n if (!executeRes.ok) {\n await describeFailure(executeRes, \"We couldn't complete your wallet deployment. Please try again.\");\n }\n const { transactionHash } = (await executeRes.json()) as { transactionHash: string };\n return { transactionHash };\n}\n\nexport async function deploySelfFunded(input: {\n provider: ProviderInterface;\n ownerAddress: string;\n ownerPubKey: string;\n privateKeyHex: string;\n}): Promise<ExecutedTransaction> {\n const classHash = getCoordinates(\"STARKNET\").mediaWalletClassHash;\n if (!classHash) throw new Error(\"Media Wallet class hash is not configured\");\n const account = new Account({\n provider: input.provider,\n address: input.ownerAddress,\n signer: input.privateKeyHex,\n cairoVersion: \"1\",\n });\n const { transaction_hash } = await account.deployAccount({\n classHash,\n constructorCalldata: ownerConstructorCalldata(input.ownerPubKey),\n addressSalt: 0,\n contractAddress: input.ownerAddress,\n });\n return { transactionHash: transaction_hash };\n}\n\nexport async function waitUntilDeployed(\n provider: ProviderInterface,\n address: string,\n timeoutMs = 90_000,\n sleep: (ms: number) => Promise<void> = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n let wait = 1_000;\n for (;;) {\n if (await isDeployed(provider, address).catch(() => false)) return;\n if (Date.now() >= deadline) {\n throw new Error(\n \"Your wallet was submitted but has not appeared on Starknet yet. Please try again in a moment.\",\n );\n }\n await sleep(wait);\n wait = Math.min(Math.round(wait * 1.5), 5_000);\n }\n}\n\nexport interface DeploymentDeps {\n store: {\n load(): SealedOwner | null;\n save(sealed: SealedOwner): void;\n loadPending(): SealedOwner | null;\n savePending(sealed: SealedOwner): void;\n clearPending(): void;\n notifyChange(): void;\n };\n passkey: {\n createOwnerKey(): Promise<{ sealed: SealedOwner; privateKeyHex: string }>;\n unlockOwnerKey(sealed: SealedOwner): Promise<string>;\n };\n provider: () => ProviderInterface;\n deployProxyUrl?: string;\n fetchImpl?: FetchLike;\n deploySponsoredImpl?: typeof deploySponsored;\n deploySelfFundedImpl?: typeof deploySelfFunded;\n waitUntilDeployedImpl?: typeof waitUntilDeployed;\n isDeployedImpl?: typeof isDeployed;\n}\n\nasync function deployWallet(\n deps: DeploymentDeps,\n wallet: { ownerAddress: string; ownerPubKey: string; privateKeyHex: string },\n replace: boolean,\n): Promise<void> {\n const sponsored = deps.deploySponsoredImpl ?? deploySponsored;\n const selfFunded = deps.deploySelfFundedImpl ?? deploySelfFunded;\n\n if (deps.deployProxyUrl) {\n try {\n await sponsored({\n proxyUrl: deps.deployProxyUrl,\n provider: deps.provider(),\n fetchImpl: deps.fetchImpl,\n replace,\n ...wallet,\n });\n } catch (sponsoredErr) {\n if (replace || isAccountRefusal(sponsoredErr)) throw sponsoredErr;\n try {\n await selfFunded({ provider: deps.provider(), ...wallet });\n } catch (selfFundedErr) {\n const sponsored = sponsoredErr instanceof Error ? sponsoredErr.message : String(sponsoredErr);\n const selfFunded = selfFundedErr instanceof Error ? selfFundedErr.message : String(selfFundedErr);\n throw new Error(`Sponsored deploy failed: ${sponsored}. Self-funded fallback failed: ${selfFunded}`);\n }\n }\n } else {\n await selfFunded({ provider: deps.provider(), ...wallet });\n }\n\n await (deps.waitUntilDeployedImpl ?? waitUntilDeployed)(deps.provider(), wallet.ownerAddress);\n}\n\nasync function unfinishedReplacement(deps: DeploymentDeps): Promise<SealedOwner | null> {\n const pending = deps.store.loadPending();\n if (!pending) return null;\n const deployed = await (deps.isDeployedImpl ?? isDeployed)(deps.provider(), pending.address).catch(() => true);\n return deployed ? null : pending;\n}\n\nexport async function completeDeployment(\n deps: DeploymentDeps,\n onStep: (step: DeploymentStep) => void,\n options: { replace?: boolean } = {},\n): Promise<DeploymentResult> {\n const pending = await unfinishedReplacement(deps);\n const replacing = options.replace === true || pending !== null;\n let sealed: SealedOwner | null = replacing ? pending : deps.store.load();\n if (!replacing && sealed && (await (deps.isDeployedImpl ?? isDeployed)(deps.provider(), sealed.address).catch(() => false))) {\n sealed = null;\n }\n let privateKeyHex: string;\n\n if (!sealed) {\n onStep(\"creating-passkey\");\n const created = await deps.passkey.createOwnerKey();\n sealed = created.sealed;\n privateKeyHex = created.privateKeyHex;\n if (replacing) deps.store.savePending(sealed);\n else deps.store.save(sealed);\n } else {\n privateKeyHex = await deps.passkey.unlockOwnerKey(sealed);\n }\n\n onStep(\"deploying\");\n await deployWallet(deps, { ownerAddress: sealed.address, ownerPubKey: sealed.ownerPubKey, privateKeyHex }, replacing);\n\n if (replacing) {\n deps.store.save(sealed);\n deps.store.clearPending();\n }\n deps.store.notifyChange();\n return { sealed };\n}\n\nexport interface DeploymentCoordinator {\n run(onStep: (step: DeploymentStep) => void, options?: { replace?: boolean }): Promise<DeploymentResult>;\n isDeploying(): boolean;\n}\n\nexport function createDeploymentCoordinator(\n execute: (onStep: (step: DeploymentStep) => void, options: { replace?: boolean }) => Promise<DeploymentResult>,\n): DeploymentCoordinator {\n let inFlight: Promise<DeploymentResult> | null = null;\n let currentStep: DeploymentStep | null = null;\n const listeners = new Set<(step: DeploymentStep) => void>();\n\n return {\n run(onStep, options = {}) {\n if (inFlight) {\n if (options.replace) {\n return Promise.reject(new Error(\"A wallet setup is already in progress.\"));\n }\n if (currentStep) onStep(currentStep);\n listeners.add(onStep);\n return inFlight.finally(() => listeners.delete(onStep));\n }\n listeners.add(onStep);\n let started: Promise<DeploymentResult>;\n try {\n started = execute((step) => {\n currentStep = step;\n for (const listener of listeners) listener(step);\n }, options);\n } catch (err) {\n listeners.clear();\n return Promise.reject(err);\n }\n const run = started.finally(() => {\n inFlight = null;\n currentStep = null;\n listeners.clear();\n });\n inFlight = run;\n return run;\n },\n isDeploying: () => inFlight !== null,\n };\n}\n","import type { FetchLike } from \"../utils/fetch.js\";\nimport { typedData as starknetTypedData, type Call, type ProviderInterface, type TypedData } from \"starknet\";\nimport { signWithPrivateKey } from \"../starknet/passkey-wallet/crypto.js\";\nimport {\n getEscape,\n getEscapeSecurityPeriod,\n getGuardians,\n getOwners,\n type EscapeInfo,\n type GuardianInfo,\n} from \"../starknet/media-wallet/guardian.js\";\nimport { computeOwnerGuid } from \"../starknet/media-wallet/owners.js\";\nimport { normalizeWalletAddress } from \"./addresses.js\";\nimport { ApiClient } from \"../api/client.js\";\nimport type { CreateWalletManageIntentParams } from \"../types/api.js\";\nimport {\n completeDeployment,\n createDeploymentCoordinator,\n type DeploymentDeps,\n type DeploymentResult,\n type DeploymentStep,\n} from \"./deployment.js\";\nimport type { OwnerStore } from \"./store.js\";\nimport type { PasskeyOwner } from \"./passkey.js\";\nimport type { ExecutedTransaction, SealedOwner, WalletExecutor } from \"./types.js\";\n\nexport interface DeviceEntry {\n guid: string;\n type: GuardianInfo[\"type\"];\n isThisDevice: boolean;\n}\n\nexport function describeDevices(owners: GuardianInfo[], thisDevicePubkey: string): DeviceEntry[] {\n const mine = computeOwnerGuid(thisDevicePubkey);\n return owners.map((owner) => ({\n guid: owner.guid,\n type: owner.type,\n isThisDevice: BigInt(owner.guid) === BigInt(mine),\n }));\n}\n\nexport function canRemoveDevice(devices: DeviceEntry[], guid: string): boolean {\n if (devices.length <= 1) return false;\n return devices.some((device) => BigInt(device.guid) === BigInt(guid));\n}\n\nexport interface MediaWalletConfig {\n store: OwnerStore;\n passkey: PasskeyOwner;\n executor: WalletExecutor;\n provider: () => ProviderInterface;\n unlockTtlMs?: number;\n backendUrl?: string;\n deployProxyUrl?: string;\n fetchImpl?: FetchLike;\n walletIntents?: (params: CreateWalletManageIntentParams) => Promise<{ id: string; calls: Call[] }>;\n}\n\nexport interface MediaWallet {\n store: OwnerStore;\n passkey: PasskeyOwner;\n lock(address: string): void;\n signerFor(sealed: SealedOwner): {\n address: string;\n signTypedData(data: TypedData): Promise<string[]>;\n execute(calls: Call[], opts?: { intentIds?: string[] }): Promise<{ txHash: string }>;\n };\n run(sealed: SealedOwner, calls: Call[], userAddress?: string, intentIds?: string[]): Promise<ExecutedTransaction>;\n getGuardians(address: string): Promise<GuardianInfo[]>;\n getEscape(address: string): Promise<EscapeInfo>;\n getEscapeSecurityPeriod(address: string): Promise<number>;\n setFirstGuardian(sealed: SealedOwner, guardianPubkey: string): Promise<string>;\n triggerEscapeOwner(guardianSealed: SealedOwner, targetAddress: string, newOwnerPubkey: string): Promise<string>;\n completeEscapeOwner(guardianSealed: SealedOwner, targetAddress: string): Promise<string>;\n cancelEscape(sealed: SealedOwner): Promise<string>;\n getOwners(address: string): Promise<GuardianInfo[]>;\n isOwnerOf(accountAddress: string, devicePubkey: string): Promise<boolean>;\n addDevice(sealed: SealedOwner, devicePubkey: string): Promise<string>;\n removeDevice(sealed: SealedOwner, ownerGuid: string): Promise<string>;\n completeDeployment(\n onStep: (step: DeploymentStep) => void,\n options?: { replace?: boolean },\n ): Promise<DeploymentResult>;\n isDeploying(): boolean;\n}\n\nexport function createMediaWallet(config: MediaWalletConfig): MediaWallet {\n const ttl = config.unlockTtlMs ?? 20_000;\n const deployments = createDeploymentCoordinator((onStep, options) => {\n const deps: DeploymentDeps = {\n store: config.store,\n passkey: config.passkey,\n provider: config.provider,\n deployProxyUrl: config.deployProxyUrl,\n fetchImpl: config.fetchImpl,\n };\n return completeDeployment(deps, onStep, options);\n });\n const unlockCache = new Map<string, { promise: Promise<string>; timer: ReturnType<typeof setTimeout> }>();\n\n const lock = (address: string): void => {\n const entry = unlockCache.get(address);\n if (!entry) return;\n clearTimeout(entry.timer);\n unlockCache.delete(address);\n };\n\n const unlockOnce = (sealed: SealedOwner): Promise<string> => {\n const existing = unlockCache.get(sealed.address);\n if (existing) return existing.promise;\n const promise = config.passkey.unlockOwnerKey(sealed).catch((err) => {\n lock(sealed.address);\n throw err;\n });\n const timer = setTimeout(() => lock(sealed.address), ttl);\n unlockCache.set(sealed.address, { promise, timer });\n return promise;\n };\n\n const run = async (sealed: SealedOwner, calls: Call[], userAddress?: string, intentIds?: string[]): Promise<ExecutedTransaction> => {\n const privateKeyHex = await unlockOnce(sealed);\n return config.executor.execute({\n userAddress: userAddress ?? sealed.address,\n privateKeyHex,\n calls,\n intentIds,\n });\n };\n\n const walletIntents = config.walletIntents ?? (async (params: CreateWalletManageIntentParams) => {\n if (!config.backendUrl) throw new Error(\"This wallet has no backend url configured\");\n const created = await new ApiClient({ baseUrl: config.backendUrl }).intents.create(\"wallet-manage\", params);\n return created as { id: string; calls: Call[] };\n });\n\n const manage = async (sealed: SealedOwner, params: CreateWalletManageIntentParams): Promise<string> => {\n const intent = await walletIntents(params);\n const { transactionHash } = await run(sealed, intent.calls, params.owner, [intent.id]);\n return transactionHash;\n };\n\n return {\n store: config.store,\n passkey: config.passkey,\n lock,\n\n signerFor(sealed) {\n return {\n address: sealed.address,\n signTypedData: async (data) => {\n const privateKeyHex = await unlockOnce(sealed);\n return signWithPrivateKey(privateKeyHex, starknetTypedData.getMessageHash(data, sealed.address));\n },\n execute: async (calls, opts) => {\n const { transactionHash } = await run(sealed, calls, undefined, opts?.intentIds);\n return { txHash: transactionHash };\n },\n };\n },\n\n run,\n\n getGuardians: (address) => getGuardians(config.provider(), address),\n getEscape: (address) => getEscape(config.provider(), address),\n getEscapeSecurityPeriod: (address) => getEscapeSecurityPeriod(config.provider(), address),\n getOwners: (address) => getOwners(config.provider(), address),\n\n async isOwnerOf(accountAddress, devicePubkey) {\n const owners = await getOwners(config.provider(), accountAddress);\n const guid = BigInt(computeOwnerGuid(devicePubkey));\n return owners.some((owner) => BigInt(owner.guid) === guid);\n },\n\n setFirstGuardian: (sealed, guardianPubkey) => manage(sealed, { owner: sealed.address, action: \"set_first_guardian\", pubkey: guardianPubkey }),\n\n triggerEscapeOwner: (guardianSealed, targetAddress, newOwnerPubkey) =>\n manage(guardianSealed, { owner: normalizeWalletAddress(targetAddress), action: \"trigger_escape\", newOwnerPubkey }),\n\n completeEscapeOwner: (guardianSealed, targetAddress) =>\n manage(guardianSealed, { owner: normalizeWalletAddress(targetAddress), action: \"complete_escape\" }),\n\n cancelEscape: (sealed) => manage(sealed, { owner: sealed.address, action: \"cancel_escape\" }),\n\n addDevice: (sealed, devicePubkey) => manage(sealed, { owner: sealed.address, action: \"add_owner\", pubkey: devicePubkey }),\n\n removeDevice: (sealed, ownerGuid) => manage(sealed, { owner: sealed.address, action: \"remove_owner\", ownerGuid }),\n\n completeDeployment: (onStep, options) => deployments.run(onStep, options),\n isDeploying: () => deployments.isDeploying(),\n };\n}\n","import type { AccountApi } from \"../api/domains/account.js\";\nimport type { CreatedOwner } from \"../wallet/passkey.js\";\nimport type { SealedOwner } from \"../wallet/types.js\";\nimport { normalizeWalletAddress } from \"../wallet/addresses.js\";\n\nexport interface SessionWallet {\n walletAddress: string;\n needsKeySetup: boolean;\n}\n\nexport interface SessionWalletClaimDeps {\n createOwnerKey(): Promise<CreatedOwner>;\n loadOwner(): SealedOwner | null;\n saveOwner(sealed: SealedOwner): void;\n removeOwner(sealed: SealedOwner, ownerGuid: string): Promise<unknown>;\n}\n\nexport async function claimSessionWallet(\n api: { account: Pick<AccountApi, \"setupWalletKey\"> },\n walletAddress: string,\n deps: SessionWalletClaimDeps,\n): Promise<void> {\n const saved = deps.loadOwner();\n const resuming = saved !== null && normalizeWalletAddress(saved.address) === normalizeWalletAddress(walletAddress);\n const sealed = resuming ? saved : { ...(await deps.createOwnerKey()).sealed, address: walletAddress };\n if (!resuming) deps.saveOwner(sealed);\n\n const { removeOwnerGuid } = await api.account.setupWalletKey({ newOwnerPubkey: sealed.ownerPubKey });\n if (removeOwnerGuid) await deps.removeOwner(sealed, removeOwnerGuid);\n}\n","import type { AccountApi } from \"../api/domains/account.js\";\nimport type { CreatedOwner } from \"../wallet/passkey.js\";\nimport type { SealedOwner } from \"../wallet/types.js\";\nimport { normalizeWalletAddress } from \"../wallet/addresses.js\";\nimport { computeOwnerGuid } from \"../starknet/media-wallet/owners.js\";\nimport { UserFacingError } from \"../errors.js\";\n\ntype RecoveryApi = { account: Pick<AccountApi, \"walletRecovery\" | \"startWalletRecovery\" | \"completeWalletRecovery\"> };\n\nexport interface SessionRecoveryDeps {\n createOwnerKey(): Promise<CreatedOwner>;\n loadPending(): SealedOwner | null;\n savePending(sealed: SealedOwner): void;\n clearPending(): void;\n saveOwner(sealed: SealedOwner): void;\n}\n\nconst sameWallet = (a: string, b: string) => normalizeWalletAddress(a) === normalizeWalletAddress(b);\n\nexport async function startSessionRecovery(api: RecoveryApi, walletAddress: string, deps: SessionRecoveryDeps) {\n const saved = deps.loadPending();\n let pending = saved && sameWallet(saved.address, walletAddress) ? saved : null;\n if (!pending) {\n pending = { ...(await deps.createOwnerKey()).sealed, address: walletAddress };\n deps.savePending(pending);\n }\n const current = await api.account.walletRecovery();\n if (current.state !== \"none\" && current.newOwnerGuid !== null && BigInt(current.newOwnerGuid) === BigInt(computeOwnerGuid(pending.ownerPubKey))) {\n return current;\n }\n return api.account.startWalletRecovery({ newOwnerPubkey: pending.ownerPubKey });\n}\n\nexport async function finishSessionRecovery(api: RecoveryApi, walletAddress: string, deps: SessionRecoveryDeps): Promise<void> {\n const saved = deps.loadPending();\n if (!saved || !sameWallet(saved.address, walletAddress)) throw new UserFacingError(\"There is no recovery to finish on this browser\");\n await api.account.completeWalletRecovery({ newOwnerPubkey: saved.ownerPubKey });\n deps.saveOwner(saved);\n deps.clearPending();\n}\n\nexport async function turnOnRecovery(\n api: { account: Pick<AccountApi, \"walletRecovery\"> },\n wallet: { setFirstGuardian(sealed: SealedOwner, guardianPubkey: string): Promise<unknown> },\n sealed: SealedOwner,\n): Promise<void> {\n const status = await api.account.walletRecovery();\n if (status.enabled) return;\n if (!status.guardianPubkey) throw new UserFacingError(\"Recovery is not available right now\");\n await wallet.setFirstGuardian(sealed, status.guardianPubkey);\n}\n"]}
|
|
@@ -694,9 +694,18 @@ function sponsoredExecutor(deps) {
|
|
|
694
694
|
}
|
|
695
695
|
};
|
|
696
696
|
}
|
|
697
|
+
var SponsoredDeployError = class extends Error {
|
|
698
|
+
constructor(message, status, code) {
|
|
699
|
+
super(message);
|
|
700
|
+
this.status = status;
|
|
701
|
+
this.code = code;
|
|
702
|
+
this.name = "SponsoredDeployError";
|
|
703
|
+
}
|
|
704
|
+
};
|
|
705
|
+
var isAccountRefusal = (err) => err instanceof SponsoredDeployError && (err.status === 401 || err.status === 409);
|
|
697
706
|
async function describeFailure(res, fallback) {
|
|
698
707
|
const body = await res.json().catch(() => null);
|
|
699
|
-
throw new
|
|
708
|
+
throw new SponsoredDeployError(body?.error || fallback, res.status, body?.code);
|
|
700
709
|
}
|
|
701
710
|
async function deploySponsored(input) {
|
|
702
711
|
const doFetch = input.fetchImpl ?? fetch;
|
|
@@ -724,7 +733,7 @@ async function deploySponsored(input) {
|
|
|
724
733
|
const executeRes = await doFetch(`${base}/execute`, {
|
|
725
734
|
method: "POST",
|
|
726
735
|
headers: { "Content-Type": "application/json" },
|
|
727
|
-
body: JSON.stringify({ ownerAddress: input.ownerAddress, typedData, signature, deployment, calls })
|
|
736
|
+
body: JSON.stringify({ ownerAddress: input.ownerAddress, typedData, signature, deployment, calls, replace: input.replace === true })
|
|
728
737
|
});
|
|
729
738
|
if (!executeRes.ok) {
|
|
730
739
|
await describeFailure(executeRes, "We couldn't complete your wallet deployment. Please try again.");
|
|
@@ -763,7 +772,7 @@ async function waitUntilDeployed(provider, address, timeoutMs = 9e4, sleep = (ms
|
|
|
763
772
|
wait = Math.min(Math.round(wait * 1.5), 5e3);
|
|
764
773
|
}
|
|
765
774
|
}
|
|
766
|
-
async function deployWallet(deps, wallet) {
|
|
775
|
+
async function deployWallet(deps, wallet, replace) {
|
|
767
776
|
const sponsored = deps.deploySponsoredImpl ?? deploySponsored;
|
|
768
777
|
const selfFunded = deps.deploySelfFundedImpl ?? deploySelfFunded;
|
|
769
778
|
if (deps.deployProxyUrl) {
|
|
@@ -772,9 +781,11 @@ async function deployWallet(deps, wallet) {
|
|
|
772
781
|
proxyUrl: deps.deployProxyUrl,
|
|
773
782
|
provider: deps.provider(),
|
|
774
783
|
fetchImpl: deps.fetchImpl,
|
|
784
|
+
replace,
|
|
775
785
|
...wallet
|
|
776
786
|
});
|
|
777
787
|
} catch (sponsoredErr) {
|
|
788
|
+
if (replace || isAccountRefusal(sponsoredErr)) throw sponsoredErr;
|
|
778
789
|
try {
|
|
779
790
|
await selfFunded({ provider: deps.provider(), ...wallet });
|
|
780
791
|
} catch (selfFundedErr) {
|
|
@@ -788,9 +799,17 @@ async function deployWallet(deps, wallet) {
|
|
|
788
799
|
}
|
|
789
800
|
await (deps.waitUntilDeployedImpl ?? waitUntilDeployed)(deps.provider(), wallet.ownerAddress);
|
|
790
801
|
}
|
|
802
|
+
async function unfinishedReplacement(deps) {
|
|
803
|
+
const pending = deps.store.loadPending();
|
|
804
|
+
if (!pending) return null;
|
|
805
|
+
const deployed = await (deps.isDeployedImpl ?? isDeployed)(deps.provider(), pending.address).catch(() => true);
|
|
806
|
+
return deployed ? null : pending;
|
|
807
|
+
}
|
|
791
808
|
async function completeDeployment(deps, onStep, options = {}) {
|
|
792
|
-
|
|
793
|
-
|
|
809
|
+
const pending = await unfinishedReplacement(deps);
|
|
810
|
+
const replacing = options.replace === true || pending !== null;
|
|
811
|
+
let sealed = replacing ? pending : deps.store.load();
|
|
812
|
+
if (!replacing && sealed && await (deps.isDeployedImpl ?? isDeployed)(deps.provider(), sealed.address).catch(() => false)) {
|
|
794
813
|
sealed = null;
|
|
795
814
|
}
|
|
796
815
|
let privateKeyHex;
|
|
@@ -799,12 +818,17 @@ async function completeDeployment(deps, onStep, options = {}) {
|
|
|
799
818
|
const created = await deps.passkey.createOwnerKey();
|
|
800
819
|
sealed = created.sealed;
|
|
801
820
|
privateKeyHex = created.privateKeyHex;
|
|
802
|
-
deps.store.
|
|
821
|
+
if (replacing) deps.store.savePending(sealed);
|
|
822
|
+
else deps.store.save(sealed);
|
|
803
823
|
} else {
|
|
804
824
|
privateKeyHex = await deps.passkey.unlockOwnerKey(sealed);
|
|
805
825
|
}
|
|
806
826
|
onStep("deploying");
|
|
807
|
-
await deployWallet(deps, { ownerAddress: sealed.address, ownerPubKey: sealed.ownerPubKey, privateKeyHex });
|
|
827
|
+
await deployWallet(deps, { ownerAddress: sealed.address, ownerPubKey: sealed.ownerPubKey, privateKeyHex }, replacing);
|
|
828
|
+
if (replacing) {
|
|
829
|
+
deps.store.save(sealed);
|
|
830
|
+
deps.store.clearPending();
|
|
831
|
+
}
|
|
808
832
|
deps.store.notifyChange();
|
|
809
833
|
return { sealed };
|
|
810
834
|
}
|
|
@@ -815,7 +839,7 @@ function createDeploymentCoordinator(execute) {
|
|
|
815
839
|
return {
|
|
816
840
|
run(onStep, options = {}) {
|
|
817
841
|
if (inFlight) {
|
|
818
|
-
if (options.
|
|
842
|
+
if (options.replace) {
|
|
819
843
|
return Promise.reject(new Error("A wallet setup is already in progress."));
|
|
820
844
|
}
|
|
821
845
|
if (currentStep) onStep(currentStep);
|
|
@@ -982,6 +1006,6 @@ async function turnOnRecovery(api, wallet, sealed) {
|
|
|
982
1006
|
await wallet.setFirstGuardian(sealed, status.guardianPubkey);
|
|
983
1007
|
}
|
|
984
1008
|
|
|
985
|
-
export { GUARDIAN_WALLET_BUSY, InvalidPairingPayloadError, InvalidRecoveryKeyError, InvalidStarkPrivateKeyError, SponsoredCallRejectedError, accountFor, allowsFallbackFunding, buildAddOwnerCall, buildCancelEscapeCall, buildCompleteEscapeOwnerCall, buildDeployAccountParams, buildRemoveOwnerByGuidCall, buildRemoveOwnerCall, buildSetFirstGuardianCall, buildTriggerEscapeOwnerCall, canRemoveDevice, claimSessionWallet, completeDeployment, computeAccountAddress, computeOwnerGuid, createDeploymentCoordinator, createMediaWallet, createOwnerStore, createPasskeyOwner, createSelfFundConsent, decodeEscapeAndStatus, decodeGuardiansInfo, deploySelfFunded, deploySponsored, deriveAesKey, deriveOwnerKeyPair, describeDevices, describeGuardianStatus, describeRecoveryAction, encodePairingPayload, encodeRecoveryKey, erc20Balance, estimateSelfFundedFee, executeSponsored, finishSessionRecovery, generateStarkKeyPair, getEscape, getEscapeSecurityPeriod, getGuardians, getOwners, indexedDbDeviceKeys, isDeployed, isValidStarknetAddress, normalizeWalletAddress, ownerConstructorCalldata, parseAccountAddress, parsePairingPayload, parseRecoveryKey, sealPrivateKey, selfFundedExecutor, signWithPrivateKey, sponsoredExecutor, starkKeyPairFromPrivateKey, startSessionRecovery, turnOnRecovery, unsealPrivateKey, waitUntilDeployed };
|
|
986
|
-
//# sourceMappingURL=chunk-
|
|
987
|
-
//# sourceMappingURL=chunk-
|
|
1009
|
+
export { GUARDIAN_WALLET_BUSY, InvalidPairingPayloadError, InvalidRecoveryKeyError, InvalidStarkPrivateKeyError, SponsoredCallRejectedError, SponsoredDeployError, accountFor, allowsFallbackFunding, buildAddOwnerCall, buildCancelEscapeCall, buildCompleteEscapeOwnerCall, buildDeployAccountParams, buildRemoveOwnerByGuidCall, buildRemoveOwnerCall, buildSetFirstGuardianCall, buildTriggerEscapeOwnerCall, canRemoveDevice, claimSessionWallet, completeDeployment, computeAccountAddress, computeOwnerGuid, createDeploymentCoordinator, createMediaWallet, createOwnerStore, createPasskeyOwner, createSelfFundConsent, decodeEscapeAndStatus, decodeGuardiansInfo, deploySelfFunded, deploySponsored, deriveAesKey, deriveOwnerKeyPair, describeDevices, describeGuardianStatus, describeRecoveryAction, encodePairingPayload, encodeRecoveryKey, erc20Balance, estimateSelfFundedFee, executeSponsored, finishSessionRecovery, generateStarkKeyPair, getEscape, getEscapeSecurityPeriod, getGuardians, getOwners, indexedDbDeviceKeys, isAccountRefusal, isDeployed, isValidStarknetAddress, normalizeWalletAddress, ownerConstructorCalldata, parseAccountAddress, parsePairingPayload, parseRecoveryKey, sealPrivateKey, selfFundedExecutor, signWithPrivateKey, sponsoredExecutor, starkKeyPairFromPrivateKey, startSessionRecovery, turnOnRecovery, unsealPrivateKey, waitUntilDeployed };
|
|
1010
|
+
//# sourceMappingURL=chunk-PVU5AYOO.js.map
|
|
1011
|
+
//# sourceMappingURL=chunk-PVU5AYOO.js.map
|