@arkade-os/sdk 0.5.13 → 0.5.14

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.
Files changed (74) hide show
  1. package/README.md +6 -0
  2. package/dist/adapters/expo.cjs +6 -6
  3. package/dist/adapters/expo.d.cts +2 -2
  4. package/dist/adapters/expo.d.ts +2 -2
  5. package/dist/adapters/expo.js +3 -3
  6. package/dist/{asyncStorageTaskQueue-Y4BlVm41.d.cts → asyncStorageTaskQueue-DzO5SBcm.d.cts} +2 -2
  7. package/dist/{asyncStorageTaskQueue-Dhbe00Ya.d.ts → asyncStorageTaskQueue-p7zeFhA3.d.ts} +2 -2
  8. package/dist/{chunk-QSERJPTT.js → chunk-4HZQSKWG.js} +3 -3
  9. package/dist/{chunk-QSERJPTT.js.map → chunk-4HZQSKWG.js.map} +1 -1
  10. package/dist/{chunk-HS7TKVOZ.cjs → chunk-6J4GABF7.cjs} +8 -4
  11. package/dist/chunk-6J4GABF7.cjs.map +1 -0
  12. package/dist/{chunk-BA36SQY2.js → chunk-72EC3ASW.js} +3 -3
  13. package/dist/{chunk-BA36SQY2.js.map → chunk-72EC3ASW.js.map} +1 -1
  14. package/dist/{chunk-WFJPLXOE.cjs → chunk-7LPT6AYH.cjs} +18 -18
  15. package/dist/{chunk-WFJPLXOE.cjs.map → chunk-7LPT6AYH.cjs.map} +1 -1
  16. package/dist/{chunk-BP4NA7HK.js → chunk-AZHBGWVC.js} +4 -4
  17. package/dist/{chunk-BP4NA7HK.js.map → chunk-AZHBGWVC.js.map} +1 -1
  18. package/dist/{chunk-6XVTGWQK.cjs → chunk-EVVLVFY7.cjs} +17 -17
  19. package/dist/{chunk-6XVTGWQK.cjs.map → chunk-EVVLVFY7.cjs.map} +1 -1
  20. package/dist/{chunk-Y3AWLHQP.js → chunk-HWWSLCQN.js} +394 -58
  21. package/dist/chunk-HWWSLCQN.js.map +1 -0
  22. package/dist/{chunk-LHLRG2BE.js → chunk-J2JZZTOE.js} +8 -5
  23. package/dist/chunk-J2JZZTOE.js.map +1 -0
  24. package/dist/{chunk-D4QH6L54.js → chunk-LCGRZ24T.js} +4 -4
  25. package/dist/{chunk-D4QH6L54.js.map → chunk-LCGRZ24T.js.map} +1 -1
  26. package/dist/{chunk-6WPP4UGN.cjs → chunk-LQH7DACV.cjs} +871 -535
  27. package/dist/chunk-LQH7DACV.cjs.map +1 -0
  28. package/dist/{chunk-TYSUFG2K.cjs → chunk-MEIE2AEU.cjs} +11 -11
  29. package/dist/{chunk-TYSUFG2K.cjs.map → chunk-MEIE2AEU.cjs.map} +1 -1
  30. package/dist/{chunk-TD4PKK2I.cjs → chunk-XZHTYYW5.cjs} +8 -8
  31. package/dist/{chunk-TD4PKK2I.cjs.map → chunk-XZHTYYW5.cjs.map} +1 -1
  32. package/dist/compiler.d.cts +1 -1
  33. package/dist/compiler.d.ts +1 -1
  34. package/dist/contracts/handlers/index.cjs +10 -10
  35. package/dist/contracts/handlers/index.d.cts +3 -3
  36. package/dist/contracts/handlers/index.d.ts +3 -3
  37. package/dist/contracts/handlers/index.js +2 -2
  38. package/dist/{index-BapVvuoI.d.ts → index-CaOBA9Ev.d.ts} +2 -2
  39. package/dist/{index-BQwrHcOh.d.cts → index-Cy57QdcL.d.cts} +67 -2
  40. package/dist/{index-DuXylQrN.d.ts → index-Db5qzYRi.d.ts} +67 -2
  41. package/dist/{index-BaTItxPx.d.cts → index-Lq_u0hqj.d.cts} +2 -2
  42. package/dist/index.cjs +325 -325
  43. package/dist/index.d.cts +126 -57
  44. package/dist/index.d.ts +126 -57
  45. package/dist/index.js +4 -4
  46. package/dist/{program-DPzf5qsk.d.cts → program-ZWUAWy_9.d.cts} +1 -1
  47. package/dist/{program-38A2Twvj.d.ts → program-zdDO4cMt.d.ts} +1 -1
  48. package/dist/repositories/realm/index.cjs +37 -37
  49. package/dist/repositories/realm/index.d.cts +2 -2
  50. package/dist/repositories/realm/index.d.ts +2 -2
  51. package/dist/repositories/realm/index.js +5 -5
  52. package/dist/repositories/sqlite/index.cjs +35 -35
  53. package/dist/repositories/sqlite/index.d.cts +2 -2
  54. package/dist/repositories/sqlite/index.d.ts +2 -2
  55. package/dist/repositories/sqlite/index.js +5 -5
  56. package/dist/{taskRunner-D2itCXf6.d.cts → taskRunner-DhZ-KQBW.d.cts} +2 -2
  57. package/dist/{taskRunner-BxOmg-O6.d.ts → taskRunner-amPuilMW.d.ts} +2 -2
  58. package/dist/wallet/expo/background.cjs +14 -14
  59. package/dist/wallet/expo/background.d.cts +3 -3
  60. package/dist/wallet/expo/background.d.ts +3 -3
  61. package/dist/wallet/expo/background.js +6 -6
  62. package/dist/wallet/expo/index.cjs +15 -15
  63. package/dist/wallet/expo/index.d.cts +2 -2
  64. package/dist/wallet/expo/index.d.ts +2 -2
  65. package/dist/wallet/expo/index.js +5 -5
  66. package/dist/worker/expo/index.cjs +9 -9
  67. package/dist/worker/expo/index.d.cts +4 -4
  68. package/dist/worker/expo/index.d.ts +4 -4
  69. package/dist/worker/expo/index.js +5 -5
  70. package/package.json +1 -1
  71. package/dist/chunk-6WPP4UGN.cjs.map +0 -1
  72. package/dist/chunk-HS7TKVOZ.cjs.map +0 -1
  73. package/dist/chunk-LHLRG2BE.js.map +0 -1
  74. package/dist/chunk-Y3AWLHQP.js.map +0 -1
@@ -1,7 +1,7 @@
1
- import { Packet, AssetId, AssetGroup, AssetInput, AssetOutput, Metadata, RestIndexerProvider, BufferReader, BufferWriter, IndexerUtxosUnsupportedError, AssetRef } from './chunk-BA36SQY2.js';
2
- import { contractHandlers, speculativeReceiveMetadata, ExecutorContractHandler, isMainnetDescriptor, descriptorIsOurs, deriveDescriptorLeafPubKey, deriveDescriptorLeafCompressedPubKey, normalizeToDescriptor, extractPubKey, parseHDDescriptor, identityDescriptor, DelegateVtxo, WALLET_RECEIVE_SOURCE, DefaultVtxo, executorContractParams, evenOwnerKey, DEFAULT_TEMPLATE_IDS, executorKeysOf, defaultVariables, BoardingContractHandler, DefaultContractHandler, delegateDiscoveryKeys, exitSequence } from './chunk-QSERJPTT.js';
1
+ import { Packet, AssetId, AssetGroup, AssetInput, AssetOutput, Metadata, RestIndexerProvider, BufferReader, BufferWriter, IndexerUtxosUnsupportedError, AssetRef } from './chunk-72EC3ASW.js';
2
+ import { contractHandlers, speculativeReceiveMetadata, ExecutorContractHandler, isMainnetDescriptor, descriptorIsOurs, deriveDescriptorLeafPubKey, deriveDescriptorLeafCompressedPubKey, normalizeToDescriptor, extractPubKey, parseHDDescriptor, identityDescriptor, DelegateVtxo, WALLET_RECEIVE_SOURCE, DefaultVtxo, executorContractParams, evenOwnerKey, DEFAULT_TEMPLATE_IDS, executorKeysOf, defaultVariables, BoardingContractHandler, DefaultContractHandler, delegateDiscoveryKeys, exitSequence } from './chunk-4HZQSKWG.js';
3
3
  import { witnessRefToBytes, validateProgram, toASM, stringifyArtifact, serializeArkadeContractParams, resolveAsm, programFromArtifact, parseArtifact, isContractArtifact, getOpcodeValue, getOpcodeName, fromASM, deserializeArkadeContractParams, computeArkadeScriptPublicKey, bytesToASM, asmToBytes, arkadeWitnessHash, arkadeScriptHash, UnsupportedProgramVersionError, SUPPORTED_PROGRAM_VERSION, OPCODE_VALUES, OPCODE_NAMES, bignum_exports, ArkadeScript, ArkadeProgramScript, ARKADE_OPS, ARKADE_OPCODE_VALUES, ARKADE_OPCODE_NAMES, ARKADE_OPCODES, ARKADE_OP, staticWitness, validateParamValue } from './chunk-X57WKONW.js';
4
- import { Transaction, requiresForfeit, setArkPsbtField, ConditionWitness, toOffchainInputFeeParams, normalizeVtxo, Proof, isVtxoSpent, getNormalizedVtxos, PrevArkTxField, craftToSpendTx, RestOperatorProvider, isVirtualCoin, ServerResponseMismatchError, getArkPsbtFields, CosignerPublicKey, isArkError, ArkErrorName, assertNonNegativeMs, isRetryableProviderError, OUTPOINT_QUERY_CHUNK_SIZE, getAllNormalizedVtxos, DEFAULT_PAGE_SIZE, VtxoTaprootTree, PrevoutTxField, OnchainCosignUnsupportedError, assertAllowedSighashTypes, OP_RETURN_EMPTY_PKSCRIPT, canSweepOnchain, baseFetch, HttpResponseError, assertTimerMs, isEventSourceError, isEventSourceUnavailableError, retryAfterMsFromError, MAX_COOLDOWN_MS, isPastExpiry, formatSighash, rateGate, OnchainCosignRejectedError, timeoutSignal, canRecoverOnchain, maybeArkError, READ_TIMEOUT_MS, OnchainCosignAmbiguousError, ArkError, indexerPages, resolveTimeHeight, canSpendOffchain, INFO_FETCH_TIMEOUT_MS, fetchVtxoCreatedAtByTxid, EXPIRY_MIN_PLAUSIBLE_MS, ProviderUnavailableError, ONCHAIN_COSIGN_REJECTED_PREFIX, ONCHAIN_COSIGN_AMBIGUOUS_PREFIX, ONCHAIN_COSIGN_UNSUPPORTED_PREFIX } from './chunk-LHLRG2BE.js';
4
+ import { Transaction, requiresForfeit, setArkPsbtField, ConditionWitness, toOffchainInputFeeParams, normalizeVtxo, Proof, isVtxoSpent, getNormalizedVtxos, PrevArkTxField, craftToSpendTx, RestOperatorProvider, isVirtualCoin, ServerResponseMismatchError, getArkPsbtFields, CosignerPublicKey, isArkError, ArkErrorName, assertNonNegativeMs, isRetryableProviderError, OUTPOINT_QUERY_CHUNK_SIZE, getAllNormalizedVtxos, DEFAULT_PAGE_SIZE, VtxoTaprootTree, PrevoutTxField, OnchainCosignUnsupportedError, assertAllowedSighashTypes, OP_RETURN_EMPTY_PKSCRIPT, canSweepOnchain, baseFetch, HttpResponseError, assertTimerMs, isEventSourceError, isEventSourceUnavailableError, retryAfterMsFromError, MAX_COOLDOWN_MS, isPastExpiry, formatSighash, rateGate, OnchainCosignRejectedError, timeoutSignal, canRecoverOnchain, maybeArkError, READ_TIMEOUT_MS, OnchainCosignAmbiguousError, ArkError, isTransientOperatorError, indexerPages, resolveTimeHeight, canSpendOffchain, INFO_FETCH_TIMEOUT_MS, fetchVtxoCreatedAtByTxid, EXPIRY_MIN_PLAUSIBLE_MS, ProviderUnavailableError, ONCHAIN_COSIGN_REJECTED_PREFIX, ONCHAIN_COSIGN_AMBIGUOUS_PREFIX, ONCHAIN_COSIGN_UNSUPPORTED_PREFIX } from './chunk-J2JZZTOE.js';
5
5
  import { VtxoScript, __export, toXOnly, CSVMultisigTapscript, networks, getNetwork, DEFAULT_NETWORK, resolveEmulatorPubkey, timelockToSequence, decodeTapscript, CLTVMultisigTapscript, ConditionCSVMultisigTapscript, ArkAddress, sequenceToTimelock, DEFAULT_ARKADE_SERVER_URL, DEFAULT_NETWORK_NAME, scriptFromTapLeafScript, proofTapLeafScriptOf, classifyAgainstSignerSet, networkFromOperatorInfo, toXOnlySignerHex, getSequence, signerSetFromInfo, isCooperativelyMigratable, MultisigTapscript, DEFAULT_ARKADE_EMULATOR_URL, retiredDelegatePubKeys, toBIP371TapTree } from './chunk-GB67AGXG.js';
6
6
  import { entropyToMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39';
7
7
  import { wordlist } from '@scure/bip39/wordlists/english.js';
@@ -1889,29 +1889,22 @@ var RestExecutorProvider = class {
1889
1889
  body: JSON.stringify(body),
1890
1890
  signal: options.signal
1891
1891
  });
1892
- if (response.status === 429) {
1893
- rateGate.reportRateLimited(url, response.headers?.get("retry-after"));
1894
- }
1895
1892
  if (!response.ok) {
1896
- throw await failure(response, "register delegation");
1893
+ throw await failure(
1894
+ response,
1895
+ "register delegation",
1896
+ await postErrorBody(url, response)
1897
+ );
1897
1898
  }
1898
1899
  const data = await response.json();
1899
1900
  return parseDelegation(isObject(data) ? data.delegation : void 0);
1900
1901
  }
1901
1902
  async getDelegation(address, options = {}) {
1902
- const url = this.endpoint(`/v1/delegation?address=${encodeURIComponent(address)}`);
1903
- const response = await rateGate.runHttp(
1904
- url,
1905
- () => baseFetch(url, { signal: options.signal })
1903
+ const data = await this.getJson(
1904
+ `/v1/delegation?address=${encodeURIComponent(address)}`,
1905
+ "get Executor delegation",
1906
+ options.signal
1906
1907
  );
1907
- if (!response.ok) {
1908
- const body = await response.text();
1909
- throw new ExecutorRequestError(
1910
- `Failed to get Executor delegation (${response.status}): ${body}`,
1911
- response.status === 404 && !isGrpcNotFound(body) ? void 0 : response.status
1912
- );
1913
- }
1914
- const data = await response.json();
1915
1908
  if (!isObject(data)) {
1916
1909
  throw new Error("Invalid Executor delegation response");
1917
1910
  }
@@ -1920,28 +1913,104 @@ var RestExecutorProvider = class {
1920
1913
  coins: optionalArray(data.coins, "coins").map(parseCoin)
1921
1914
  };
1922
1915
  }
1916
+ async registerArtifact(document, options = {}) {
1917
+ const data = await this.postJson(
1918
+ "/v1/artifact",
1919
+ { document: documentText(document) },
1920
+ "register Executor artifact",
1921
+ options.signal
1922
+ );
1923
+ return parseArtifact2(isObject(data) ? data.artifact : void 0);
1924
+ }
1925
+ async getArtifact(id, options = {}) {
1926
+ const data = await this.getJson(
1927
+ `/v1/artifact/${encodeURIComponent(id)}`,
1928
+ "get Executor artifact",
1929
+ options.signal
1930
+ );
1931
+ return parseArtifact2(isObject(data) ? data.artifact : void 0);
1932
+ }
1933
+ async registerTemplate(document, options = {}) {
1934
+ const data = await this.postJson(
1935
+ "/v1/template",
1936
+ { document: documentText(document) },
1937
+ "register Executor template",
1938
+ options.signal
1939
+ );
1940
+ return parseTemplateDetails(isObject(data) ? data.template : void 0);
1941
+ }
1942
+ async getTemplate(id, options = {}) {
1943
+ const data = await this.getJson(
1944
+ `/v1/template/${encodeURIComponent(id)}`,
1945
+ "get Executor template",
1946
+ options.signal
1947
+ );
1948
+ return parseTemplateDetails(isObject(data) ? data.template : void 0);
1949
+ }
1950
+ async postJson(path, body, what, signal) {
1951
+ const url = this.endpoint(path);
1952
+ const response = await baseFetch(url, {
1953
+ method: "POST",
1954
+ headers: { "Content-Type": "application/json" },
1955
+ body: JSON.stringify(body),
1956
+ signal
1957
+ });
1958
+ if (!response.ok) {
1959
+ throw await notFoundFailure(response, what, await postErrorBody(url, response));
1960
+ }
1961
+ return response.json();
1962
+ }
1963
+ async getJson(path, what, signal) {
1964
+ const url = this.endpoint(path);
1965
+ const response = await rateGate.runHttp(url, () => baseFetch(url, { signal }));
1966
+ if (!response.ok) {
1967
+ throw await notFoundFailure(response, what);
1968
+ }
1969
+ return response.json();
1970
+ }
1923
1971
  };
1924
- async function failure(response, what) {
1972
+ async function notFoundFailure(response, what, text) {
1973
+ const body = text ?? await response.text();
1974
+ return new ExecutorRequestError(
1975
+ `Failed to ${what} (${response.status}): ${body}`,
1976
+ response.status === 404 && grpcCode(body) !== 5 ? void 0 : response.status
1977
+ );
1978
+ }
1979
+ async function failure(response, what, text) {
1925
1980
  return new ExecutorRequestError(
1926
- `Failed to ${what} (${response.status}): ${await response.text()}`,
1981
+ `Failed to ${what} (${response.status}): ${text ?? await response.text()}`,
1927
1982
  response.status
1928
1983
  );
1929
1984
  }
1930
- function isGrpcNotFound(body) {
1985
+ async function postErrorBody(url, response) {
1986
+ let body;
1987
+ try {
1988
+ body = await response.text();
1989
+ return body;
1990
+ } finally {
1991
+ if (response.status === 429 && (body === void 0 || grpcCode(body) !== 8)) {
1992
+ rateGate.reportRateLimited(url, response.headers?.get("retry-after"));
1993
+ }
1994
+ }
1995
+ }
1996
+ function documentText(document) {
1997
+ return typeof document === "string" ? document : JSON.stringify(document);
1998
+ }
1999
+ function grpcCode(body) {
1931
2000
  try {
1932
2001
  const parsed = JSON.parse(body);
1933
- return isObject(parsed) && parsed.code === 5;
2002
+ return isObject(parsed) ? parsed.code : void 0;
1934
2003
  } catch {
1935
- return false;
2004
+ return void 0;
1936
2005
  }
1937
2006
  }
1938
2007
  function isObject(value) {
1939
2008
  return typeof value === "object" && value !== null;
1940
2009
  }
1941
- function requiredString(object, key) {
2010
+ function requiredString(object, key, what = "info") {
1942
2011
  const value = object[key];
1943
2012
  if (typeof value !== "string" || value.length === 0) {
1944
- throw new Error(`Invalid Executor info: missing ${key}`);
2013
+ throw new Error(`Invalid Executor ${what}: missing ${key}`);
1945
2014
  }
1946
2015
  return value;
1947
2016
  }
@@ -2039,6 +2108,36 @@ function parseTemplate(value) {
2039
2108
  }
2040
2109
  return { id: value.id, status: typeof value.status === "string" ? value.status : "" };
2041
2110
  }
2111
+ function parseTemplateDetails(value) {
2112
+ if (!isObject(value)) throw new Error("Invalid Executor template");
2113
+ const artifactIds = optionalArray(value.artifactIds, "artifactIds");
2114
+ if (artifactIds.some((id) => typeof id !== "string" || id.length === 0)) {
2115
+ throw new Error("Invalid Executor template: artifactIds are not strings");
2116
+ }
2117
+ return {
2118
+ id: requiredString(value, "id", "template"),
2119
+ status: requiredString(value, "status", "template"),
2120
+ document: requiredString(value, "document", "template"),
2121
+ artifactIds,
2122
+ params: optionalArray(value.params, "params").map((param) => {
2123
+ if (!isObject(param)) throw new Error("Invalid Executor template param");
2124
+ return {
2125
+ name: requiredString(param, "name", "template param"),
2126
+ type: requiredString(param, "type", "template param")
2127
+ };
2128
+ }),
2129
+ type: requiredString(value, "type", "template"),
2130
+ createdAt: parseOptionalInt64(value.createdAt, "createdAt")
2131
+ };
2132
+ }
2133
+ function parseArtifact2(value) {
2134
+ if (!isObject(value)) throw new Error("Invalid Executor artifact");
2135
+ return {
2136
+ id: requiredString(value, "id", "artifact"),
2137
+ document: requiredString(value, "document", "artifact"),
2138
+ createdAt: parseOptionalInt64(value.createdAt, "createdAt")
2139
+ };
2140
+ }
2042
2141
  function parseExecutorInfo(value) {
2043
2142
  if (!isObject(value)) throw new Error("Invalid Executor info");
2044
2143
  const info = {
@@ -2051,6 +2150,10 @@ function parseExecutorInfo(value) {
2051
2150
  decodeCompressed(info.cosignerPubkey, "cosignerPubkey");
2052
2151
  decodeCompressed(info.serverPubkey, "serverPubkey");
2053
2152
  decodeCompressed(info.emulatorPubkey, "emulatorPubkey");
2153
+ if (value.encryptionPubkey !== void 0 && value.encryptionPubkey !== "") {
2154
+ info.encryptionPubkey = requiredString(value, "encryptionPubkey");
2155
+ decodeCompressed(info.encryptionPubkey, "encryptionPubkey");
2156
+ }
2054
2157
  return info;
2055
2158
  }
2056
2159
  function decodeCompressed(value, label) {
@@ -3940,6 +4043,9 @@ function validateRecipients(recipients, dustAmount, context) {
3940
4043
  if (amount <= 0) {
3941
4044
  throw new Error("Amount must be positive");
3942
4045
  }
4046
+ if ((recipient.assets?.length ?? 0) > 0 && amount < dustAmount) {
4047
+ throw new Error(`Asset recipient amount ${amount} is below dust ${dustAmount}`);
4048
+ }
3943
4049
  if (recipient.tapTree) {
3944
4050
  assertTapTreeDerivesAddress(recipient.address, recipient.tapTree, address);
3945
4051
  }
@@ -8822,6 +8928,11 @@ async function arkadeCashActivity(records, txs) {
8822
8928
  return activities.filter((activity) => activity.intent?.kind === "arkade-cash");
8823
8929
  }
8824
8930
 
8931
+ // src/repositories/vtxoReservationRepository.ts
8932
+ function reservationOutpointSetKey(outpoints) {
8933
+ return outpoints.map(({ txid, vout }) => `${txid}:${vout}`).sort().join("|");
8934
+ }
8935
+
8825
8936
  // src/wallet/intentReconciliation.ts
8826
8937
  var NON_TERMINAL_INTENT_STATES = ALL_BATCH_REGISTRATION_STATES.filter((s) => !isTerminalBatchRegistrationState(s));
8827
8938
  function isConsumed(vtxo) {
@@ -10871,7 +10982,7 @@ function createManagedConnection(dbName, version, initDatabase2) {
10871
10982
  // src/repositories/indexedDB/vtxoReservationRepository.ts
10872
10983
  var STORE = "reservations";
10873
10984
  var IndexedDBVtxoReservationRepository = class {
10874
- version = 1;
10985
+ version = 2;
10875
10986
  connection;
10876
10987
  constructor(dbName) {
10877
10988
  this.connection = createManagedConnection(dbName, 1, (db) => {
@@ -10894,6 +11005,22 @@ var IndexedDBVtxoReservationRepository = class {
10894
11005
  transaction.objectStore(STORE).delete(id);
10895
11006
  await awaitTransaction(transaction);
10896
11007
  }
11008
+ async deleteReservationIfMatches(id, expected) {
11009
+ const expectedKey = reservationOutpointSetKey(expected);
11010
+ const db = await this.connection.get();
11011
+ const transaction = db.transaction(STORE, "readwrite");
11012
+ const store = transaction.objectStore(STORE);
11013
+ let deleted = false;
11014
+ const request = store.get(id);
11015
+ request.onsuccess = () => {
11016
+ const current = request.result;
11017
+ if (!current || reservationOutpointSetKey(current.outpoints) !== expectedKey) return;
11018
+ store.delete(id);
11019
+ deleted = true;
11020
+ };
11021
+ await awaitTransaction(transaction);
11022
+ return deleted;
11023
+ }
10897
11024
  async [Symbol.asyncDispose]() {
10898
11025
  await this.connection[Symbol.asyncDispose]();
10899
11026
  }
@@ -15625,9 +15752,6 @@ function omittedOutpoints(before, after) {
15625
15752
  function coinKeys(inputs) {
15626
15753
  return inputs.filter((input) => typeof input === "object" && input !== null).map((input) => `${input.txid}:${input.vout}`);
15627
15754
  }
15628
- function outpointSetKey(outpoints) {
15629
- return outpoints.map(({ txid, vout }) => `${txid}:${vout}`).sort().join("|");
15630
- }
15631
15755
  function assertNoPersistentReservation(inputs, reservations) {
15632
15756
  const held = coinKeys(inputs).filter((key) => reservations?.has(key));
15633
15757
  if (held.length > 0) throw new VtxoReservedError(held, "held");
@@ -18035,6 +18159,16 @@ var Wallet2 = class extends ReadonlyWallet {
18035
18159
  // Own queue, not the tx lock: a settle holds that for a whole batch round. The pending and
18036
18160
  // held sets already order a hold against a spend.
18037
18161
  reservationQueue = Promise.resolve();
18162
+ requireReservationRepository() {
18163
+ const repository = this.reservationRepository;
18164
+ if (!repository) throw new Error("VTXO reservation repository is required");
18165
+ if (repository.version !== 2 || typeof repository.deleteReservationIfMatches !== "function") {
18166
+ throw new Error(
18167
+ "VTXO reservation repository version 2 with atomic release is required"
18168
+ );
18169
+ }
18170
+ return repository;
18171
+ }
18038
18172
  withReservationWrite(fn) {
18039
18173
  const run = this.reservationQueue.then(fn);
18040
18174
  this.reservationQueue = run.catch(() => void 0);
@@ -18047,13 +18181,13 @@ var Wallet2 = class extends ReadonlyWallet {
18047
18181
  }
18048
18182
  /** Restored before automatic spending. Reusing an owner id must name the same inputs. */
18049
18183
  async reserveVtxosPersistently(outpoints, id) {
18050
- if (!this.reservationRepository) throw new Error("VTXO reservation repository is required");
18184
+ const repository = this.requireReservationRepository();
18051
18185
  if (typeof id !== "string" || !id) throw new Error("Reservation id is required");
18052
18186
  const snapshot = outpoints.map(({ txid, vout }) => ({ txid, vout }));
18053
18187
  await this.withReservationWrite(async () => {
18054
18188
  const existing = this.persistentReservations.get(id);
18055
18189
  if (existing) {
18056
- if (outpointSetKey(existing) !== outpointSetKey(snapshot)) {
18190
+ if (reservationOutpointSetKey(existing) !== reservationOutpointSetKey(snapshot)) {
18057
18191
  throw new Error("Reservation id already holds different inputs");
18058
18192
  }
18059
18193
  return;
@@ -18063,7 +18197,7 @@ var Wallet2 = class extends ReadonlyWallet {
18063
18197
  this.persistentReservedOutpoints.add(`${txid}:${vout}`);
18064
18198
  try {
18065
18199
  await assertNoIntentLockedInputs(snapshot, this.intentRepository);
18066
- await this.reservationRepository.saveReservation({ id, outpoints: snapshot });
18200
+ await repository.saveReservation({ id, outpoints: snapshot });
18067
18201
  this.persistentReservations.set(id, snapshot);
18068
18202
  } catch (error) {
18069
18203
  hold.release();
@@ -18079,11 +18213,12 @@ var Wallet2 = class extends ReadonlyWallet {
18079
18213
  * newer hold under its id alone.
18080
18214
  */
18081
18215
  async releaseVtxoReservation(id, expected) {
18082
- if (!this.reservationRepository) throw new Error("VTXO reservation repository is required");
18216
+ const repository = this.requireReservationRepository();
18083
18217
  await this.withReservationWrite(async () => {
18084
18218
  const outpoints = this.persistentReservations.get(id) ?? [];
18085
- if (expected && outpointSetKey(outpoints) !== outpointSetKey(expected)) return;
18086
- await this.reservationRepository.deleteReservation(id);
18219
+ if (expected && reservationOutpointSetKey(outpoints) !== reservationOutpointSetKey(expected))
18220
+ return;
18221
+ if (!await repository.deleteReservationIfMatches(id, expected ?? outpoints)) return;
18087
18222
  this.persistentReservations.delete(id);
18088
18223
  const stillNamed = new Set(
18089
18224
  [...this.persistentReservations.values()].flat().map(({ txid, vout }) => `${txid}:${vout}`)
@@ -18270,6 +18405,11 @@ var Wallet2 = class extends ReadonlyWallet {
18270
18405
  settlementConfig;
18271
18406
  _concurrentSpending = false;
18272
18407
  _submitsAwaitingFinalize = 0;
18408
+ pendingTxRecoveryDeferred = false;
18409
+ /** @internal */
18410
+ get hasDeferredPendingTxRecovery() {
18411
+ return this.pendingTxRecoveryDeferred;
18412
+ }
18273
18413
  /** @see WalletConfig.concurrentSpending */
18274
18414
  get concurrentSpending() {
18275
18415
  return this._concurrentSpending;
@@ -18281,10 +18421,18 @@ var Wallet2 = class extends ReadonlyWallet {
18281
18421
  async getArkadeBroadcaster() {
18282
18422
  const ark = this.arkProvider;
18283
18423
  return {
18284
- submitTx: (signedArkTx, checkpointTxs) => ark.submitTx(signedArkTx, checkpointTxs),
18424
+ submitTx: async (signedArkTx, checkpointTxs) => {
18425
+ this.assertNoDeferredPendingTxRecovery();
18426
+ return ark.submitTx(signedArkTx, checkpointTxs);
18427
+ },
18285
18428
  finalizeTx: (arkTxid, finalCheckpointTxs) => ark.finalizeTx(arkTxid, finalCheckpointTxs)
18286
18429
  };
18287
18430
  }
18431
+ assertNoDeferredPendingTxRecovery() {
18432
+ if (this.pendingTxRecoveryDeferred) {
18433
+ throw new Error("Pending Arkade transaction recovery is required before sending");
18434
+ }
18435
+ }
18288
18436
  get assetManager() {
18289
18437
  this._walletAssetManager ??= new AssetManager(this);
18290
18438
  return this._walletAssetManager;
@@ -19482,12 +19630,42 @@ var Wallet2 = class extends ReadonlyWallet {
19482
19630
  * @returns Array of transaction IDs that were finalized
19483
19631
  */
19484
19632
  async finalizePendingTxs(vtxos) {
19633
+ return this.finalizePendingTxsImpl(vtxos);
19634
+ }
19635
+ /** @internal */
19636
+ async deferPendingTxRecovery() {
19637
+ this.pendingTxRecoveryDeferred = await this.hasPendingTxFlag();
19638
+ return this.pendingTxRecoveryDeferred;
19639
+ }
19640
+ /** @internal */
19641
+ async resumeDeferredPendingTxs(isCurrent) {
19642
+ const info = await this.getOperatorInfo({ requireLive: true });
19643
+ if (info.network !== this.network.name) {
19644
+ throw new Error("Operator network changed while recovering pending transactions");
19645
+ }
19646
+ await this._withTxLock(async () => {
19647
+ if (!isCurrent()) return;
19648
+ try {
19649
+ await this.finalizePendingTxsImpl(void 0, { info, isCurrent });
19650
+ } catch (error) {
19651
+ if (!isTransientOperatorError(error) && isCurrent()) {
19652
+ this.pendingTxRecoveryDeferred = false;
19653
+ }
19654
+ throw error;
19655
+ }
19656
+ if (isCurrent()) this.pendingTxRecoveryDeferred = false;
19657
+ });
19658
+ }
19659
+ async finalizePendingTxsImpl(vtxos, recovery) {
19660
+ const isCurrent = recovery?.isCurrent ?? (() => true);
19485
19661
  const hasPending = await this.hasPendingTxFlag();
19486
- if (!hasPending) {
19662
+ if (!hasPending || !isCurrent()) {
19663
+ if (!hasPending && isCurrent()) this.pendingTxRecoveryDeferred = false;
19487
19664
  return { finalized: [], pending: [] };
19488
19665
  }
19489
19666
  if (!vtxos || vtxos.length === 0) {
19490
19667
  const scriptMap = await this.getScriptMap();
19668
+ if (!isCurrent()) return { finalized: [], pending: [] };
19491
19669
  const allExtended = [];
19492
19670
  const fetchedVtxos = await getAllNormalizedVtxos(this.indexerProvider, [
19493
19671
  ...scriptMap.keys()
@@ -19495,7 +19673,9 @@ var Wallet2 = class extends ReadonlyWallet {
19495
19673
  for (const vtxo of fetchedVtxos) {
19496
19674
  const vtxoScript = scriptMap.get(vtxo.script);
19497
19675
  if (!vtxoScript) continue;
19498
- if (!vtxo.isSpent && !(vtxo.isPreconfirmed && !vtxo.isSwept)) {
19676
+ if (recovery) {
19677
+ if (isSubdust(vtxo, this.dustAmount) || vtxo.isUnrolled) continue;
19678
+ } else if (!vtxo.isSpent && !(vtxo.isPreconfirmed && !vtxo.isSwept)) {
19499
19679
  continue;
19500
19680
  }
19501
19681
  allExtended.push({
@@ -19514,19 +19694,24 @@ var Wallet2 = class extends ReadonlyWallet {
19514
19694
  for (let i = 0; i < vtxos.length; i += MAX_INPUTS_PER_PROOF) {
19515
19695
  batches.push(vtxos.slice(i, i + MAX_INPUTS_PER_PROOF));
19516
19696
  }
19517
- const unrollCandidates = this.checkpointUnrollCandidates(await this.arkProvider.getInfo());
19697
+ const unrollCandidates = this.checkpointUnrollCandidates(
19698
+ recovery?.info ?? await this.arkProvider.getInfo()
19699
+ );
19700
+ if (!isCurrent()) return { finalized: [], pending: [] };
19518
19701
  const checkpointInputs = vtxos.map((vtxo) => ({
19519
19702
  ...vtxo,
19520
19703
  tapLeafScript: vtxo.forfeitTapLeafScript
19521
19704
  }));
19522
19705
  const seen = /* @__PURE__ */ new Set();
19523
- const results = await Promise.all(
19706
+ const results = await Promise.allSettled(
19524
19707
  batches.map(async (batch) => {
19525
19708
  const batchFinalized = [];
19526
19709
  const batchPending = [];
19527
19710
  const intent = await this.makeGetPendingTxIntentSignature(batch);
19711
+ if (!isCurrent()) return { finalized: batchFinalized, pending: batchPending };
19528
19712
  const pendingTxs = await this.arkProvider.getPendingTxs(intent);
19529
19713
  for (const pendingTx of pendingTxs) {
19714
+ if (!isCurrent()) break;
19530
19715
  if (seen.has(pendingTx.arkTxid)) continue;
19531
19716
  seen.add(pendingTx.arkTxid);
19532
19717
  batchPending.push(pendingTx.arkTxid);
@@ -19562,6 +19747,7 @@ var Wallet2 = class extends ReadonlyWallet {
19562
19747
  );
19563
19748
  const identity = this.identity;
19564
19749
  const batchEligible = isBatchSignable(identity) && await this._signerRouter.canBatch(...checkpointJobs);
19750
+ if (!isCurrent()) break;
19565
19751
  let finalCheckpoints;
19566
19752
  if (batchEligible) {
19567
19753
  const requests = checkpointTxs.map((tx, i) => ({
@@ -19586,9 +19772,11 @@ var Wallet2 = class extends ReadonlyWallet {
19586
19772
  })
19587
19773
  );
19588
19774
  }
19775
+ if (!isCurrent()) break;
19589
19776
  await this.arkProvider.finalizeTx(pendingTx.arkTxid, finalCheckpoints);
19590
19777
  batchFinalized.push(pendingTx.arkTxid);
19591
19778
  } catch (error) {
19779
+ if (recovery && isTransientOperatorError(error)) throw error;
19592
19780
  console.error(
19593
19781
  `Failed to finalize transaction ${pendingTx.arkTxid}:`,
19594
19782
  error
@@ -19604,11 +19792,13 @@ var Wallet2 = class extends ReadonlyWallet {
19604
19792
  const finalized = [];
19605
19793
  const pending = [];
19606
19794
  for (const result of results) {
19607
- finalized.push(...result.finalized);
19608
- pending.push(...result.pending);
19795
+ if (result.status === "rejected") throw result.reason;
19796
+ finalized.push(...result.value.finalized);
19797
+ pending.push(...result.value.pending);
19609
19798
  }
19610
- if (finalized.length === pending.length) {
19611
- await this.setPendingTxFlag(false);
19799
+ if (finalized.length === pending.length && isCurrent()) {
19800
+ await this.setPendingTxFlag(false, isCurrent);
19801
+ if (isCurrent()) this.pendingTxRecoveryDeferred = false;
19612
19802
  }
19613
19803
  return { finalized, pending };
19614
19804
  }
@@ -19643,11 +19833,11 @@ var Wallet2 = class extends ReadonlyWallet {
19643
19833
  const state = await this.walletRepository.getWalletState();
19644
19834
  return state?.settings?.hasPendingTx === true;
19645
19835
  }
19646
- async setPendingTxFlag(value) {
19647
- await updateWalletState(this.walletRepository, (state) => ({
19648
- ...state,
19649
- settings: { ...state.settings, hasPendingTx: value }
19650
- }));
19836
+ async setPendingTxFlag(value, isCurrent = () => true) {
19837
+ await updateWalletState(
19838
+ this.walletRepository,
19839
+ (state) => isCurrent() ? { ...state, settings: { ...state.settings, hasPendingTx: value } } : state
19840
+ );
19651
19841
  }
19652
19842
  /**
19653
19843
  * Create an ArkadeCash bearer instrument: sends `amount` to a DefaultVtxo controlled by a fresh
@@ -20630,6 +20820,7 @@ var Wallet2 = class extends ReadonlyWallet {
20630
20820
  });
20631
20821
  }
20632
20822
  async _buildAndSubmitOffchainTx(inputs, outputs, serverUnrollScript, options) {
20823
+ this.assertNoDeferredPendingTxRecovery();
20633
20824
  await assertNoIntentLockedInputs(inputs, this.intentRepository);
20634
20825
  assertNoPersistentReservation(inputs, this.persistentReservedOutpoints);
20635
20826
  const validUntil = captureSendDeadline(options?.validUntil);
@@ -21467,8 +21658,8 @@ var MessageBus = class {
21467
21658
  */
21468
21659
  initChain = Promise.resolve();
21469
21660
  /**
21470
- * Number of inits accepted but not yet settled (queued or running). The
21471
- * bus refuses ordinary wallet messages while this is > 0.
21661
+ * Number of inits and releases accepted but not yet settled (queued or
21662
+ * running). The bus refuses ordinary wallet messages while this is > 0.
21472
21663
  */
21473
21664
  pendingInitCount = 0;
21474
21665
  buildServicesFn;
@@ -21645,6 +21836,30 @@ var MessageBus = class {
21645
21836
  this.initChain = run.catch(() => void 0);
21646
21837
  return run;
21647
21838
  }
21839
+ /**
21840
+ * Back to a fresh worker's state. On the init chain, so a later init
21841
+ * builds only after these handlers stop.
21842
+ */
21843
+ release(epoch) {
21844
+ this.pendingInitCount += 1;
21845
+ const run = this.initChain.then(async () => {
21846
+ if (epoch !== this.broadcastEpoch || !this.initialized) return;
21847
+ this.initialized = false;
21848
+ this.invalidateBroadcasts();
21849
+ if (this.tickTimeout !== null) {
21850
+ self.clearTimeout(this.tickTimeout);
21851
+ this.tickTimeout = null;
21852
+ }
21853
+ await Promise.all(
21854
+ Array.from(this.handlers.values()).map((h) => h.stop().catch(() => {
21855
+ }))
21856
+ );
21857
+ }).finally(() => {
21858
+ this.pendingInitCount -= 1;
21859
+ });
21860
+ this.initChain = run.catch(() => void 0);
21861
+ return run;
21862
+ }
21648
21863
  /**
21649
21864
  * The bus serves ordinary wallet messages only when it is initialized AND
21650
21865
  * no init is in flight.
@@ -21664,7 +21879,8 @@ var MessageBus = class {
21664
21879
  broadcast: (response) => {
21665
21880
  if (epoch !== this.broadcastEpoch) return;
21666
21881
  this.broadcastToClients([response]);
21667
- }
21882
+ },
21883
+ release: () => this.release(epoch)
21668
21884
  };
21669
21885
  if (this.initialized) {
21670
21886
  this.initialized = false;
@@ -22316,6 +22532,12 @@ var Ramps = class {
22316
22532
  *
22317
22533
  * Returns the onchain txid instead when onchain coins alone cover `amount`
22318
22534
  * and were spent via arkd cosigning.
22535
+ *
22536
+ * Rethrows a cosign that failed after the client signed (`OnchainCosignRejectedError`,
22537
+ * `OnchainCosignAmbiguousError`): the operator may still hold that signed tx and complete it,
22538
+ * so paying from other coins can pay twice. No batch here can conflict with it, as arkd
22539
+ * refuses an intent mixing onchain inputs and outputs. See "Onchain cosigning" in the README for
22540
+ * the caller's options.
22319
22541
  */
22320
22542
  async offboardExact(params) {
22321
22543
  const { destinationAddress, feeInfo, amount, eventCallback, vtxos } = params;
@@ -22667,6 +22889,7 @@ var WalletMessageHandler = class {
22667
22889
  incomingFundsSubscription;
22668
22890
  incomingFundsRegistrations = /* @__PURE__ */ new WeakMap();
22669
22891
  contractEventsSubscription;
22892
+ retryPendingTxs;
22670
22893
  onNextTick = [];
22671
22894
  channel;
22672
22895
  // One counter per subscription field, bumped exactly where that field is
@@ -22697,6 +22920,9 @@ var WalletMessageHandler = class {
22697
22920
  // lifecycle methods
22698
22921
  async start(...params) {
22699
22922
  const [services, repositories, channel] = params;
22923
+ if (services.wallet?.serverInfoSource === "cache") {
22924
+ await services.wallet.deferPendingTxRecovery();
22925
+ }
22700
22926
  this.readonlyWallet = services.readonlyWallet;
22701
22927
  this.wallet = services.wallet;
22702
22928
  this.walletRequestBinding = services.walletRequestBinding ? Object.freeze({ ...services.walletRequestBinding }) : void 0;
@@ -22705,6 +22931,7 @@ var WalletMessageHandler = class {
22705
22931
  this.walletRepository = repositories.walletRepository;
22706
22932
  this.channel = channel;
22707
22933
  this.onNextTick = [];
22934
+ this.retryPendingTxs = void 0;
22708
22935
  }
22709
22936
  async stop() {
22710
22937
  const wallet = this.wallet ?? this.readonlyWallet;
@@ -22716,6 +22943,7 @@ var WalletMessageHandler = class {
22716
22943
  this.channel = void 0;
22717
22944
  this.walletRequestBinding = void 0;
22718
22945
  this.onNextTick = [];
22946
+ this.retryPendingTxs = void 0;
22719
22947
  if (this.incomingFundsSubscription) {
22720
22948
  this.incomingFundsSubscription();
22721
22949
  this.incomingFundsSubscription = void 0;
@@ -22737,6 +22965,9 @@ var WalletMessageHandler = class {
22737
22965
  }
22738
22966
  }
22739
22967
  async tick(_now) {
22968
+ const retryPendingTxs = this.retryPendingTxs;
22969
+ this.retryPendingTxs = void 0;
22970
+ void retryPendingTxs?.();
22740
22971
  const pending = this.onNextTick.splice(0);
22741
22972
  const results = await Promise.allSettled(pending.map((fn) => fn()));
22742
22973
  return results.map((result) => {
@@ -22873,6 +23104,11 @@ var WalletMessageHandler = class {
22873
23104
  throw new Error("Invalid scoped wallet request");
22874
23105
  }
22875
23106
  const context = this.captureRequestContext(message.payload.binding);
23107
+ if (request.type === "DISPOSE") {
23108
+ const release = this.channel?.release;
23109
+ await (release ? release() : this.stop());
23110
+ return this.tagged({ id: request.id, type: "DISPOSE_SUCCESS" });
23111
+ }
22876
23112
  if (request.type === "CLEAR" && this.longRunningOperations.size > 0) {
22877
23113
  throw new Error(
22878
23114
  "Cannot clear the wallet while a long-running operation such as a settlement is in progress"
@@ -22887,6 +23123,7 @@ var WalletMessageHandler = class {
22887
23123
  this.contractEventsEpoch++;
22888
23124
  this.boardingEpoch++;
22889
23125
  this.onNextTick = [];
23126
+ this.retryPendingTxs = void 0;
22890
23127
  }
22891
23128
  const execution = pending ? settledWithin(pending, this.drainBudgetMs).then((drained) => {
22892
23129
  if (!drained) {
@@ -23746,12 +23983,21 @@ var WalletMessageHandler = class {
23746
23983
  return;
23747
23984
  }
23748
23985
  this.initEpoch++;
23986
+ this.retryPendingTxs = void 0;
23749
23987
  const init = this.newGeneration("init");
23988
+ if (signingWallet?.serverInfoSource === "cache" && !signingWallet.hasDeferredPendingTxRecovery) {
23989
+ await signingWallet.deferPendingTxRecovery();
23990
+ if (init.stale) return;
23991
+ }
23992
+ const deferred = signingWallet?.hasDeferredPendingTxRecovery === true;
23993
+ if (signingWallet && deferred) {
23994
+ this.schedulePendingTxRecovery(signingWallet, context, init);
23995
+ }
23750
23996
  await this.ensureContractEventBroadcasting(context);
23751
23997
  if (init.stale) return;
23752
23998
  await this.refreshCachedData({ lazyBoarding }, context, init);
23753
23999
  if (init.stale) return;
23754
- if (signingWallet) {
24000
+ if (signingWallet && !deferred) {
23755
24001
  try {
23756
24002
  const vtxos = await this.getVtxosFromRepo(void 0, context);
23757
24003
  if (init.stale) return;
@@ -23767,7 +24013,13 @@ var WalletMessageHandler = class {
23767
24013
  `Recovered ${finalized.length}/${pending.length} pending transactions: ${finalized.join(", ")}`
23768
24014
  );
23769
24015
  } catch (error) {
23770
- console.error("Error recovering pending transactions:", error);
24016
+ if (init.stale) return;
24017
+ if (isTransientOperatorError(error) && await signingWallet.deferPendingTxRecovery()) {
24018
+ if (init.stale) return;
24019
+ this.schedulePendingTxRecovery(signingWallet, context, init);
24020
+ } else {
24021
+ console.error("Error recovering pending transactions:", error);
24022
+ }
23771
24023
  }
23772
24024
  if (init.stale) return;
23773
24025
  }
@@ -23793,6 +24045,33 @@ var WalletMessageHandler = class {
23793
24045
  }
23794
24046
  }
23795
24047
  }
24048
+ schedulePendingTxRecovery(wallet, context, init) {
24049
+ const reported = /* @__PURE__ */ new Set();
24050
+ const retry = async () => {
24051
+ if (init.stale) return;
24052
+ try {
24053
+ await this.runOwnedOperation(
24054
+ context,
24055
+ () => wallet.resumeDeferredPendingTxs(() => !init.stale)
24056
+ );
24057
+ } catch (error) {
24058
+ if (init.stale) return;
24059
+ if (!wallet.hasDeferredPendingTxRecovery) {
24060
+ console.error("Error recovering pending transactions:", error);
24061
+ return;
24062
+ }
24063
+ if (!isTransientOperatorError(error)) {
24064
+ const reason = String(error);
24065
+ if (!reported.has(reason)) {
24066
+ reported.add(reason);
24067
+ console.error("Retrying pending transaction recovery:", error);
24068
+ }
24069
+ }
24070
+ this.retryPendingTxs = retry;
24071
+ }
24072
+ };
24073
+ this.retryPendingTxs = retry;
24074
+ }
23796
24075
  async registerIncomingFunds(wallet, emitter, context) {
23797
24076
  const repository = context.walletRepository;
23798
24077
  if (emitter.stale) return;
@@ -24302,6 +24581,7 @@ var DEFAULT_MESSAGE_TIMEOUTS = {
24302
24581
  INIT_WALLET: 3e4,
24303
24582
  SCOPED_WALLET_REQUEST_V1: 3e4,
24304
24583
  CLEAR: 1e4,
24584
+ DISPOSE: 3e4,
24305
24585
  SIGN_TRANSACTION: 3e4,
24306
24586
  CREATE_CONTRACT: 3e4,
24307
24587
  UPDATE_CONTRACT: 3e4,
@@ -24484,6 +24764,8 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
24484
24764
  messageBusTimeoutMs;
24485
24765
  messageTimeouts = DEFAULT_MESSAGE_TIMEOUTS;
24486
24766
  reinitPromise = null;
24767
+ disposed = false;
24768
+ disposePromise;
24487
24769
  pingPromise = null;
24488
24770
  inflightRequests = /* @__PURE__ */ new Map();
24489
24771
  get assetManager() {
@@ -24666,6 +24948,7 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
24666
24948
  });
24667
24949
  }
24668
24950
  async sendMessage(request) {
24951
+ this.assertNotDisposed();
24669
24952
  if (!DEDUPABLE_REQUEST_TYPES.has(request.type)) {
24670
24953
  return this.sendMessageWithRetry(request);
24671
24954
  }
@@ -24709,17 +24992,20 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
24709
24992
  // send a message, retrying up to 2 times if the service worker was
24710
24993
  // killed and restarted by the OS (mobile browsers do this aggressively)
24711
24994
  async sendMessageWithRetry(request, withEvents) {
24995
+ this.assertNotDisposed();
24712
24996
  request = this.scopeRequest(request);
24713
24997
  if (this.initConfig) {
24714
24998
  try {
24715
24999
  await this.pingServiceWorker();
24716
25000
  } catch {
25001
+ this.assertNotDisposed();
24717
25002
  await this.reinitialize();
24718
25003
  }
24719
25004
  }
24720
25005
  const timeoutMs = this.getTimeoutForRequest(request);
24721
25006
  const maxRetries = 2;
24722
25007
  for (let attempt = 0, initWaits = 0; ; attempt++) {
25008
+ this.assertNotDisposed();
24723
25009
  try {
24724
25010
  if (withEvents) {
24725
25011
  return await this.sendMessageStreaming(
@@ -24731,6 +25017,7 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
24731
25017
  return await this.sendMessageDirect(request, timeoutMs);
24732
25018
  } catch (error) {
24733
25019
  if (isMessageBusInitializingError(error)) {
25020
+ this.assertNotDisposed();
24734
25021
  if (initWaits >= MAX_INIT_WAITS) throw error;
24735
25022
  await sleep(initWaitBackoffMs(initWaits++));
24736
25023
  attempt--;
@@ -24739,6 +25026,7 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
24739
25026
  if (!isMessageBusNotInitializedError(error) || attempt >= maxRetries) {
24740
25027
  throw error;
24741
25028
  }
25029
+ this.assertNotDisposed();
24742
25030
  await this.reinitialize();
24743
25031
  }
24744
25032
  }
@@ -24771,11 +25059,14 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
24771
25059
  return this.initWalletPayload;
24772
25060
  }
24773
25061
  async reinitialize() {
25062
+ this.assertNotDisposed();
24774
25063
  if (this.reinitPromise) return this.reinitPromise;
24775
25064
  this.reinitPromise = (async () => {
24776
25065
  const config = await this.buildInitConfig();
25066
+ this.assertNotDisposed();
24777
25067
  const payload = this.buildInitWalletPayload();
24778
25068
  await initializeMessageBus(this.serviceWorker, config, this.messageBusTimeoutMs);
25069
+ this.assertNotDisposed();
24779
25070
  const initMessage = {
24780
25071
  tag: this.messageTag,
24781
25072
  type: "INIT_WALLET",
@@ -24783,6 +25074,7 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
24783
25074
  payload
24784
25075
  };
24785
25076
  await this.assertWorkerIdentityMatches();
25077
+ this.assertNotDisposed();
24786
25078
  await this.sendMessageDirect(
24787
25079
  this.scopeRequest(initMessage),
24788
25080
  this.getTimeoutForRequest(initMessage)
@@ -24836,6 +25128,49 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
24836
25128
  }
24837
25129
  this.walletRequestBinding ??= Object.freeze({ ...binding });
24838
25130
  }
25131
+ assertNotDisposed() {
25132
+ if (this.disposed) throw new Error("Service worker wallet is disposed");
25133
+ }
25134
+ /**
25135
+ * Revoke this worker wallet and proxy without deleting persisted data or
25136
+ * holds; call again after a failure to retry.
25137
+ */
25138
+ dispose() {
25139
+ this.disposed = true;
25140
+ this.disposePromise ??= this.disposeWorker().catch((error) => {
25141
+ this.disposePromise = void 0;
25142
+ throw error;
25143
+ });
25144
+ return this.disposePromise;
25145
+ }
25146
+ async disposeWorker() {
25147
+ await this.reinitPromise?.catch(() => void 0);
25148
+ const message = {
25149
+ id: getRandomId(),
25150
+ tag: this.messageTag,
25151
+ type: "DISPOSE"
25152
+ };
25153
+ for (let initWaits = 0; ; ) {
25154
+ try {
25155
+ const response = await this.sendMessageDirect(
25156
+ this.scopeRequest(message),
25157
+ this.getTimeoutForRequest(message)
25158
+ );
25159
+ if (response.type !== "DISPOSE_SUCCESS") {
25160
+ throw new Error("Worker did not confirm wallet disposal");
25161
+ }
25162
+ return;
25163
+ } catch (error) {
25164
+ if (isMessageBusInitializingError(error)) {
25165
+ if (initWaits >= MAX_INIT_WAITS) throw error;
25166
+ await sleep(initWaitBackoffMs(initWaits++));
25167
+ continue;
25168
+ }
25169
+ if (isMessageBusNotInitializedError(error)) return;
25170
+ throw error;
25171
+ }
25172
+ }
25173
+ }
24839
25174
  /** This tells the service worker to wipe all locally persisted wallet data. */
24840
25175
  async clear() {
24841
25176
  const message = {
@@ -25079,11 +25414,12 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
25079
25414
  }
25080
25415
  /** Subscribe to contract and coin updates bound to this proxy's wallet. */
25081
25416
  onWalletUpdate(callback) {
25417
+ this.assertNotDisposed();
25082
25418
  const binding = this.walletRequestBinding;
25083
25419
  const tag = this.messageTag;
25084
25420
  const messageHandler = (event) => {
25085
25421
  const response = event.data;
25086
- if (!binding || !response || response.tag !== tag || response.broadcast !== true || !["CONTRACT_EVENT", "VTXO_UPDATE", "UTXO_UPDATE"].includes(response.type) || response.walletRequestBinding?.scope !== binding.scope || response.walletRequestBinding?.network !== binding.network) {
25422
+ if (this.disposed || !binding || !response || response.tag !== tag || response.broadcast !== true || !["CONTRACT_EVENT", "VTXO_UPDATE", "UTXO_UPDATE"].includes(response.type) || response.walletRequestBinding?.scope !== binding.scope || response.walletRequestBinding?.network !== binding.network) {
25087
25423
  return;
25088
25424
  }
25089
25425
  callback(response);
@@ -30150,5 +30486,5 @@ function createDefaultPaymentRouter(wallet) {
30150
30486
  */
30151
30487
 
30152
30488
  export { ARKADE_MAGIC, ARKADE_SALTED_PREIMAGE_TAG, ARKADE_SWAP_PREIMAGE_TAG, ASSET_CARRIER_SATS, AbortError, ActivityRegistry, AmbiguousRouteError, ArkNote, Arkade, ArkadeCash, ArkadeCashCreateError, ArkadeCashOperatorMismatchError, AssetManager, BATCH_REGISTRATION_TERMINAL_STATES, BIP21, BIP21Error, BIP322, BLOCKED_UPGRADE_TIMEOUT_MS, Batch, CachingArkProvider, CachingOperatorProvider, ChainedTxType, ConnectionDisposedError, ContractManager, ContractWatcher, DEFAULT_MESSAGE_TIMEOUTS, DEFAULT_MIN_BATCH_EXPIRY_SECONDS, DEFAULT_PASSKEY_LABEL, DELEGATION_EXPIRES_KEY, DELEGATION_LOCAL_STATUS, DELEGATION_REGISTERED_KEY, DELEGATION_STATUS_KEY, DatabaseUpgradeBlockedError, DelegateManagerImpl, DelegateNotConfiguredError, DescriptorIdentity, DescriptorSigningProviderMissingError, DustChangeError, ELECTRUM_TCP_HOST, ELECTRUM_WS_URL, ESPLORA_URL, ElectrumOnchainProvider, EmulatorPacket, EsploraProvider, Estimator, ExecutorManagerImpl, ExecutorRequestError, Extension, ExtensionNotFoundError, ForeignDescriptorError, HDDescriptorProvider, INTENT_TERMINAL_STATES, InMemoryBatchRegistrationRepository, InMemoryContractRepository, InMemoryIntentRepository, InMemoryVirtualTxRepository, InMemoryWalletRepository, IndexedDBBatchRegistrationRepository, IndexedDBContractRepository, IndexedDBIntentRepository, IndexedDBVirtualTxRepository, IndexedDBVtxoReservationRepository, IndexedDBWalletRepository, KeyringDescriptorProvider, MAX_PAGE_SIZE, MAX_USED_SIGNING_DESCRIPTORS_LOOK_AHEAD, MESSAGE_BUS_INITIALIZING, MESSAGE_BUS_NOT_INITIALIZED, MessageBus, MessageBusInitializingError, MessageBusNotInitializedError, MissingSigningDescriptorError, MnemonicIdentity, OnchainCosignPreflightError, OnchainWallet, OversizedChangeError, P2A, PasskeyCancelled, PasskeyUnconfirmed, PaymentRouter, PrevTxUnavailableError, PrfUnavailable, REGTEST_MIN_BATCH_EXPIRY_SECONDS, Ramps, ReadonlyAssetManager, ReadonlyDescriptorIdentity, ReadonlySingleKey, ReadonlyWallet, ReadonlyWalletError, RestDelegateProvider, RestEmulatorProvider, RestExecutorProvider, SeedIdentity, SendDeadlineExceededError, ServiceWorkerReadonlyWallet, ServiceWorkerTimeoutError, ServiceWorkerWallet, SingleKey, StaticDescriptorProvider, TreeSignerSession, TxTree, TxType, TxWeightEstimator, UnannotatableInputError, UnilateralExit, UnknownPacket, Unroll, VtxoManager, VtxoReservedError, Wallet2 as Wallet, WalletCannotAllocateAddressError, WalletCannotSignError, WalletMessageHandler, WalletNotInitializedError, WsElectrumChainSource, addArkadeCashRecord, adoptContractDescriptor, applyWalletStateUpdate, arkAssetRail, arkRail, arkTarget, arkadeCashId, arkadeCashResolver, arkade_exports, assertFinalCommitmentMatchesValidated, assertHistoryPageFilter, assertIntentIdUnique, assertNoAssets, assertNoSelection, assertPageRequest, assertRecipientArkadeAddress, assertSendDeadline, assertSendableAmount, assertSubmittedArkTxid, assertValidBatchExpiry, assertValidServerUnrollScript, assetMintResolver, assetsOf, attachPrevArkTxs, attachPrevoutTxs, awaitTransaction, boardingResolver, btcTarget, buildForfeitTx, buildOffchainTx, buildPreimageMessage, buildSaltedPreimageMessage, captureSendDeadline, checkSaveVtxosForScript, claimWithPreimageIdentity, classifyBoardingExpiry, closeDatabase, collabExitResolver, collectBatchRegistrations, collectContracts, collectIntents, collectPages, collectScriptVtxos, collectTransactionHistory, collectUtxos, collectVtxos, combineTapscriptSigs, compareHistoryCursors, contractFilterMatchesNothing, contractFromArkContract, contractFromArkContractWithAddress, contractPreimage, contractSigner, createArkadeCashTracker, createAssetPacket, createDefaultActivityRegistry, createDefaultPaymentRouter, createExitChainResolver, createManagedConnection, createPrfPasskey, createdAtToIso, decodeArkContract, decodeBoardingExit, defaultBatchExpiryPolicy, deleteByIndex, deserializeAssets, deserializeExitPackage, deserializeUtxo, deserializeVtxo, encodeArkContract, evaluatePrf, exitObserverFor, extendVirtualCoinForContract, extractOperatorProviderUrl, gateExclusion, gatedContracts, getAllByIndexValues, getRandomId, hasBoardingTxExpired, hasCandidates, intentMatchesFilter, invoiceTarget, isAddressAllocationCapable, isArkContract, isBatchSignable, isBtcAddress, isContractGenericallySpendable, isContractVtxoEvent, isCosignFallback, isDeterministicSigner, isDiscoverable, isHDAllocationCapable, isHDDeterministicSignCapable, isHDWalletCapable, isLightningInvoice, isLnurl, isMessageBusInitializingError, isMessageBusNotInitializedError, isPerArtifactDescriptor, isSigningIdentity, isSubdust, isTerminalBatchRegistrationState, isTerminalIntentState, isValidArkAddress, isVtxoExpiringSoon, iteratePages, legacyVtxoFacts, logExcludedVtxos, makeHandle, matchServerCheckpoints, mergeArkadeCashRecord, mergeChainedTxType, mnemonicFromPrf, notifyExitObserved, onchainRail, openDatabase, outpointExclusion, outpointReasons, pageResult, prfSupport, promisifyRequest, provisionClaimSecret, provisionRefundKey, readArkadeCash, registerWalletRestoreHook, resolveAssetAmount, resolveBatchExpiryPolicy, resolveDescriptorSigner, resolvePrevTxs, resolveSendAmount, saveVtxosForContract, scopeOf, scriptFromArkAddress, selectCoinsWithAsset, selectVirtualCoins, selectionOf, serializeAssets, serializeExitPackage, serializeUtxo, serializeVtxo, setupServiceWorker, signAndSubmitOffchainTx, signingDescriptorIndex, strictSigningDescriptorIndex, submitViaEmulator, tryResolveSendAmount, utxoEntries, validateBatchRecipients, validateConnectorsTxGraph, validateVtxoTxGraph, verifyTapscriptSignatures, waitForIncomingFunds, walletFeeSource, warnAndFilterVtxosForScript, watchExecutorContracts, withPrevTxs };
30153
- //# sourceMappingURL=chunk-Y3AWLHQP.js.map
30154
- //# sourceMappingURL=chunk-Y3AWLHQP.js.map
30489
+ //# sourceMappingURL=chunk-HWWSLCQN.js.map
30490
+ //# sourceMappingURL=chunk-HWWSLCQN.js.map