@arkade-os/sdk 0.5.14 → 0.5.15

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 (88) hide show
  1. package/README.md +49 -1
  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/artifact-DA5YHM2k.d.cts +87 -0
  7. package/dist/artifact-DacurepK.d.ts +87 -0
  8. package/dist/{asyncStorageTaskQueue-p7zeFhA3.d.ts → asyncStorageTaskQueue-B3umqlkb.d.ts} +2 -2
  9. package/dist/{asyncStorageTaskQueue-DzO5SBcm.d.cts → asyncStorageTaskQueue-Dq6AJHNv.d.cts} +2 -2
  10. package/dist/{chunk-MEIE2AEU.cjs → chunk-35GRSVCZ.cjs} +11 -11
  11. package/dist/{chunk-MEIE2AEU.cjs.map → chunk-35GRSVCZ.cjs.map} +1 -1
  12. package/dist/{chunk-X57WKONW.js → chunk-43APGKWL.js} +130 -22
  13. package/dist/chunk-43APGKWL.js.map +1 -0
  14. package/dist/{chunk-LQH7DACV.cjs → chunk-CMFRCBZW.cjs} +866 -615
  15. package/dist/chunk-CMFRCBZW.cjs.map +1 -0
  16. package/dist/{chunk-6J4GABF7.cjs → chunk-FKHUXSYW.cjs} +3 -3
  17. package/dist/chunk-FKHUXSYW.cjs.map +1 -0
  18. package/dist/{chunk-AZHBGWVC.js → chunk-HVUZKXB2.js} +4 -4
  19. package/dist/{chunk-AZHBGWVC.js.map → chunk-HVUZKXB2.js.map} +1 -1
  20. package/dist/{chunk-EVVLVFY7.cjs → chunk-INQAIZUO.cjs} +17 -17
  21. package/dist/{chunk-EVVLVFY7.cjs.map → chunk-INQAIZUO.cjs.map} +1 -1
  22. package/dist/{chunk-7LPT6AYH.cjs → chunk-JSYS2KX3.cjs} +18 -18
  23. package/dist/{chunk-7LPT6AYH.cjs.map → chunk-JSYS2KX3.cjs.map} +1 -1
  24. package/dist/{chunk-4HZQSKWG.js → chunk-R37I633T.js} +22 -17
  25. package/dist/chunk-R37I633T.js.map +1 -0
  26. package/dist/{chunk-ACIQZLWL.cjs → chunk-UNLH3NNG.cjs} +129 -20
  27. package/dist/chunk-UNLH3NNG.cjs.map +1 -0
  28. package/dist/{chunk-XZHTYYW5.cjs → chunk-VIQF74QJ.cjs} +38 -33
  29. package/dist/chunk-VIQF74QJ.cjs.map +1 -0
  30. package/dist/{chunk-LCGRZ24T.js → chunk-XPZ7TMXH.js} +4 -4
  31. package/dist/{chunk-LCGRZ24T.js.map → chunk-XPZ7TMXH.js.map} +1 -1
  32. package/dist/{chunk-72EC3ASW.js → chunk-YYSHQPCG.js} +3 -3
  33. package/dist/{chunk-72EC3ASW.js.map → chunk-YYSHQPCG.js.map} +1 -1
  34. package/dist/{chunk-J2JZZTOE.js → chunk-Z4LG3CZ4.js} +3 -3
  35. package/dist/chunk-Z4LG3CZ4.js.map +1 -0
  36. package/dist/{chunk-HWWSLCQN.js → chunk-ZECZ2MKX.js} +344 -93
  37. package/dist/chunk-ZECZ2MKX.js.map +1 -0
  38. package/dist/compiler.cjs +5 -5
  39. package/dist/compiler.cjs.map +1 -1
  40. package/dist/compiler.d.cts +9 -9
  41. package/dist/compiler.d.ts +9 -9
  42. package/dist/compiler.js +5 -5
  43. package/dist/compiler.js.map +1 -1
  44. package/dist/contracts/handlers/index.cjs +11 -11
  45. package/dist/contracts/handlers/index.d.cts +2 -2
  46. package/dist/contracts/handlers/index.d.ts +2 -2
  47. package/dist/contracts/handlers/index.js +3 -3
  48. package/dist/{index-Cy57QdcL.d.cts → index-Bi22mLsh.d.cts} +147 -43
  49. package/dist/{index-CaOBA9Ev.d.ts → index-CiLMmCHX.d.ts} +1 -1
  50. package/dist/{index-Db5qzYRi.d.ts → index-DOdoDqvM.d.ts} +147 -43
  51. package/dist/{index-Lq_u0hqj.d.cts → index-DnKugm-h.d.cts} +1 -1
  52. package/dist/index.cjs +327 -327
  53. package/dist/index.d.cts +32 -66
  54. package/dist/index.d.ts +32 -66
  55. package/dist/index.js +5 -5
  56. package/dist/repositories/realm/index.cjs +38 -38
  57. package/dist/repositories/realm/index.d.cts +2 -2
  58. package/dist/repositories/realm/index.d.ts +2 -2
  59. package/dist/repositories/realm/index.js +6 -6
  60. package/dist/repositories/sqlite/index.cjs +36 -36
  61. package/dist/repositories/sqlite/index.d.cts +2 -2
  62. package/dist/repositories/sqlite/index.d.ts +2 -2
  63. package/dist/repositories/sqlite/index.js +6 -6
  64. package/dist/{taskRunner-amPuilMW.d.ts → taskRunner-CoE4Xx9K.d.ts} +2 -2
  65. package/dist/{taskRunner-DhZ-KQBW.d.cts → taskRunner-DFG0BN_R.d.cts} +2 -2
  66. package/dist/wallet/expo/background.cjs +15 -15
  67. package/dist/wallet/expo/background.d.cts +3 -3
  68. package/dist/wallet/expo/background.d.ts +3 -3
  69. package/dist/wallet/expo/background.js +7 -7
  70. package/dist/wallet/expo/index.cjs +19 -16
  71. package/dist/wallet/expo/index.cjs.map +1 -1
  72. package/dist/wallet/expo/index.d.cts +3 -2
  73. package/dist/wallet/expo/index.d.ts +3 -2
  74. package/dist/wallet/expo/index.js +9 -6
  75. package/dist/wallet/expo/index.js.map +1 -1
  76. package/dist/worker/expo/index.cjs +10 -10
  77. package/dist/worker/expo/index.d.cts +4 -4
  78. package/dist/worker/expo/index.d.ts +4 -4
  79. package/dist/worker/expo/index.js +6 -6
  80. package/package.json +3 -3
  81. package/dist/chunk-4HZQSKWG.js.map +0 -1
  82. package/dist/chunk-6J4GABF7.cjs.map +0 -1
  83. package/dist/chunk-ACIQZLWL.cjs.map +0 -1
  84. package/dist/chunk-HWWSLCQN.js.map +0 -1
  85. package/dist/chunk-J2JZZTOE.js.map +0 -1
  86. package/dist/chunk-LQH7DACV.cjs.map +0 -1
  87. package/dist/chunk-X57WKONW.js.map +0 -1
  88. package/dist/chunk-XZHTYYW5.cjs.map +0 -1
@@ -1,8 +1,8 @@
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
- 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, 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
- 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';
1
+ import { Packet, AssetId, AssetGroup, AssetInput, AssetOutput, Metadata, RestIndexerProvider, BufferReader, BufferWriter, IndexerUtxosUnsupportedError, AssetRef } from './chunk-YYSHQPCG.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-R37I633T.js';
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, instantiatedContracts, validateParamValue } from './chunk-43APGKWL.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-Z4LG3CZ4.js';
5
+ import { VtxoScript, __export, toXOnly, CSVMultisigTapscript, networks, getNetwork, DEFAULT_NETWORK, resolveEmulatorPubkey, decodeTapscript, CLTVMultisigTapscript, ConditionCSVMultisigTapscript, timelockToSequence, 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';
8
8
  import * as musig2 from '@scure/btc-signer/musig2.js';
@@ -2143,16 +2143,16 @@ function parseExecutorInfo(value) {
2143
2143
  const info = {
2144
2144
  version: requiredString(value, "version"),
2145
2145
  network: requiredString(value, "network"),
2146
- cosignerPubkey: requiredString(value, "cosignerPubkey"),
2147
- serverPubkey: requiredString(value, "serverPubkey"),
2146
+ batchCosignerPubkey: requiredString(value, "batchCosignerPubkey"),
2147
+ operatorPubkey: requiredString(value, "operatorPubkey"),
2148
2148
  emulatorPubkey: requiredString(value, "emulatorPubkey")
2149
2149
  };
2150
- decodeCompressed(info.cosignerPubkey, "cosignerPubkey");
2151
- decodeCompressed(info.serverPubkey, "serverPubkey");
2150
+ decodeCompressed(info.batchCosignerPubkey, "batchCosignerPubkey");
2151
+ decodeCompressed(info.operatorPubkey, "operatorPubkey");
2152
2152
  decodeCompressed(info.emulatorPubkey, "emulatorPubkey");
2153
- if (value.encryptionPubkey !== void 0 && value.encryptionPubkey !== "") {
2154
- info.encryptionPubkey = requiredString(value, "encryptionPubkey");
2155
- decodeCompressed(info.encryptionPubkey, "encryptionPubkey");
2153
+ if (value.sealingPubkey !== void 0 && value.sealingPubkey !== "") {
2154
+ info.sealingPubkey = requiredString(value, "sealingPubkey");
2155
+ decodeCompressed(info.sealingPubkey, "sealingPubkey");
2156
2156
  }
2157
2157
  return info;
2158
2158
  }
@@ -4657,6 +4657,11 @@ function verifyTapscriptSignatures(tx, inputIndex, requiredSigners, excludePubke
4657
4657
  );
4658
4658
  }
4659
4659
  }
4660
+ if (signature.length !== 64 && (signature.length !== 65 || signature[64] === SigHash.DEFAULT)) {
4661
+ throw new Error(
4662
+ `Input ${inputIndex}: signature from ${pubKeyHex} is not a BIP-341 signature encoding (${signature.length} bytes)`
4663
+ );
4664
+ }
4660
4665
  const sighashType = signature.length === 65 ? signature[64] : SigHash.DEFAULT;
4661
4666
  const sig = signature.subarray(0, 64);
4662
4667
  if (!allowedSighashTypes.includes(sighashType)) {
@@ -5913,6 +5918,13 @@ var NonRangeableDescriptorError = class extends Error {
5913
5918
  }
5914
5919
  };
5915
5920
  var ROTATION_MAX_BACKOFF_MS = 6e4;
5921
+ function isReceiptAtDisplayed(event, wallet) {
5922
+ if (event.type !== "vtxo_received") return false;
5923
+ if (event.contractScript === wallet.defaultContractScript) return true;
5924
+ if (!isContractVtxoEvent(event)) return false;
5925
+ const { type, params } = event.contract;
5926
+ return type === ExecutorContractHandler.type && params.template === "renewal" && params.owner?.slice(2).toLowerCase() === hex.encode(wallet.offchainTapscript.options.pubKey);
5927
+ }
5916
5928
  var WalletReceiveRotator = class _WalletReceiveRotator {
5917
5929
  constructor(provider, priorTaggedScript, logger) {
5918
5930
  this.provider = provider;
@@ -6006,8 +6018,7 @@ var WalletReceiveRotator = class _WalletReceiveRotator {
6006
6018
  async install(wallet) {
6007
6019
  const manager = await wallet.getContractManager();
6008
6020
  this.unsubscribe = manager.onContractEvent((event) => {
6009
- if (event.type !== "vtxo_received") return;
6010
- if (event.contractScript !== wallet.defaultContractScript) return;
6021
+ if (!isReceiptAtDisplayed(event, wallet)) return;
6011
6022
  this.chain = this.chain.catch(() => void 0).then(() => this.runRotateWithBackoff(wallet));
6012
6023
  });
6013
6024
  }
@@ -6090,6 +6101,7 @@ var WalletReceiveRotator = class _WalletReceiveRotator {
6090
6101
  const newScript = params.script;
6091
6102
  const manager = await managerPromise;
6092
6103
  await manager.createContract(params);
6104
+ await wallet.registerReceiveTwin?.(descriptor);
6093
6105
  wallet.setOffchainTapscriptForRotation(newTapscript);
6094
6106
  const previousTagged = this.currentTaggedScript;
6095
6107
  if (previousTagged !== void 0 && previousTagged !== newScript) {
@@ -6198,12 +6210,19 @@ var DELEGATION_STATUS_KEY = "delegationStatus";
6198
6210
  var DELEGATION_EXPIRES_KEY = "delegationExpiresAt";
6199
6211
  var DELEGATION_REGISTERED_KEY = "delegationRegisteredAt";
6200
6212
  var DELEGATION_LOCAL_STATUS = "local";
6213
+ async function ownAddress(wallet) {
6214
+ return ArkAddress.decode(await (wallet.getOwnAddress?.() ?? wallet.getAddress()));
6215
+ }
6216
+ var SCRIPT_CACHE_LIMIT = 512;
6201
6217
  var scriptCache = /* @__PURE__ */ new Map();
6202
6218
  function cachedScript(params) {
6203
6219
  const key = JSON.stringify(Object.entries(params).sort(([a], [b]) => a < b ? -1 : 1));
6204
6220
  let script = scriptCache.get(key);
6205
6221
  if (!script) {
6206
6222
  script = ExecutorContractHandler.createScript(params);
6223
+ if (scriptCache.size >= SCRIPT_CACHE_LIMIT) {
6224
+ scriptCache.delete(scriptCache.keys().next().value);
6225
+ }
6207
6226
  scriptCache.set(key, script);
6208
6227
  }
6209
6228
  return script;
@@ -6224,30 +6243,56 @@ async function delegatedContracts(identity, getContracts, template) {
6224
6243
  const descriptor = contract.metadata?.signingDescriptor;
6225
6244
  const held = owner === identityKey || typeof descriptor === "string" && hex.encode(deriveDescriptorLeafPubKey(descriptor)) === owner;
6226
6245
  if (!held || owner === void 0) continue;
6227
- const script = cachedScript(contract.params);
6228
- if (hex.encode(script.pkScript) !== contract.script) continue;
6229
- const expiresAt = contract.metadata?.[DELEGATION_EXPIRES_KEY];
6230
- watches.push({
6231
- contract,
6232
- owner,
6233
- script,
6234
- signer: toXOnlySignerHex(contract.params.serverPubKey),
6235
- live: contract.metadata?.[DELEGATION_STATUS_KEY] === "active" && !(typeof expiresAt === "number" && expiresAt > 0 && expiresAt <= now)
6236
- });
6246
+ const watch = watchOf(contract, owner, now);
6247
+ if (watch) watches.push(watch);
6237
6248
  } catch (e) {
6238
6249
  console.warn("Skipping malformed delegated contract", contract.script, e);
6239
6250
  }
6240
6251
  }
6241
6252
  return watches;
6242
6253
  }
6254
+ function watchOf(contract, owner, now) {
6255
+ const script = cachedScript(contract.params);
6256
+ if (hex.encode(script.pkScript) !== contract.script) return void 0;
6257
+ const expiresAt = contract.metadata?.[DELEGATION_EXPIRES_KEY];
6258
+ return {
6259
+ contract,
6260
+ owner,
6261
+ script,
6262
+ signer: toXOnlySignerHex(contract.params.serverPubKey),
6263
+ live: contract.metadata?.[DELEGATION_STATUS_KEY] === "active" && !(typeof expiresAt === "number" && expiresAt > 0 && expiresAt <= now)
6264
+ };
6265
+ }
6266
+ var warnedStatusless = /* @__PURE__ */ new Set();
6267
+ async function receiveTwin(getContracts, owner, signer) {
6268
+ const rows = (await getContracts({ type: ["executor"] })).filter(
6269
+ (c) => c.params.template === "renewal" && c.params.owner?.slice(2).toLowerCase() === owner && c.params.serverPubKey !== void 0 && toXOnlySignerHex(c.params.serverPubKey) === signer
6270
+ ).sort((a, b) => registeredAt(b) - registeredAt(a));
6271
+ const now = Math.floor(Date.now() / 1e3);
6272
+ for (const contract of rows) {
6273
+ const watch = watchOf(contract, owner, now);
6274
+ if (watch?.live) return watch;
6275
+ if (contract.metadata?.[DELEGATION_STATUS_KEY] === void 0) warnStatusless(contract);
6276
+ }
6277
+ return void 0;
6278
+ }
6279
+ function warnStatusless(contract) {
6280
+ if (warnedStatusless.has(contract.script)) return;
6281
+ if (warnedStatusless.size >= SCRIPT_CACHE_LIMIT) {
6282
+ warnedStatusless.delete(warnedStatusless.values().next().value);
6283
+ }
6284
+ warnedStatusless.add(contract.script);
6285
+ console.warn(
6286
+ `Executor renewal watch ${contract.address} has no delegation status, as after a restore: the wallet shows its own address until registerRenewal() confirms it`
6287
+ );
6288
+ }
6243
6289
  async function watchExecutorContracts(wallet, keys, params, registered, descriptor) {
6244
- const [owner, address, manager] = await Promise.all([
6290
+ const [owner, { hrp, serverPubKey }, manager] = await Promise.all([
6245
6291
  descriptor === void 0 ? wallet.identity.compressedPublicKey() : ownerKey(wallet.identity, descriptor),
6246
- wallet.getAddress(),
6292
+ ownAddress(wallet),
6247
6293
  wallet.getContractManager()
6248
6294
  ]);
6249
6295
  const signing = descriptor === void 0 || equalBytes(owner.subarray(1), await wallet.identity.xOnlyPublicKey()) ? void 0 : descriptor;
6250
- const { hrp, serverPubKey } = ArkAddress.decode(address);
6251
6296
  const templates = params.boardingExitDelay === void 0 ? ["renewal"] : ["renewal", "boarding"];
6252
6297
  const contracts = [];
6253
6298
  for (const template of templates) {
@@ -6318,6 +6363,11 @@ function reRegistrationOf(watch) {
6318
6363
  }
6319
6364
  };
6320
6365
  }
6366
+ function sameDelegation(a, b) {
6367
+ const p = ExecutorContractHandler.deserializeParams(a.contract.params);
6368
+ const q = ExecutorContractHandler.deserializeParams(b.contract.params);
6369
+ return p.renewalWindow === q.renewalWindow && p.maxFee === q.maxFee && p.exitDelay === q.exitDelay && p.boardingExitDelay === q.boardingExitDelay && equalBytes(p.emulatorPubKey, q.emulatorPubKey);
6370
+ }
6321
6371
  function renewalScript(owner, keys, params) {
6322
6372
  const script = ExecutorContractHandler.createScript(
6323
6373
  executorContractParams("renewal", owner, keys, params)
@@ -6419,6 +6469,11 @@ var ExecutorManagerImpl = class {
6419
6469
  }
6420
6470
  return first;
6421
6471
  }
6472
+ /** @internal The renewal watch of `descriptor`'s key alone, under the params of `options`. */
6473
+ async registerRenewalAt(descriptor, options, registration = {}) {
6474
+ const context = this.lazyContext();
6475
+ return await this.storedWatch(descriptor, options, registration, "renewal") ?? await this.registerAt(await context(), descriptor, options, registration, "renewal");
6476
+ }
6422
6477
  /** @internal {@link registerBoarding} for `descriptor`'s key; the displayed one by default. */
6423
6478
  async registerBoardingAt(descriptor, options, registration = {}) {
6424
6479
  const key = descriptor ?? await this.displayedDescriptor();
@@ -6439,10 +6494,11 @@ var ExecutorManagerImpl = class {
6439
6494
  * registration moves the boarding address. One that cannot be revived stops being live, and
6440
6495
  * the wallet boards its deposits itself. A failing watch leaves the others to be tried.
6441
6496
  *
6442
- * Only a key the wallet still uses is revived: the displayed one, and the most recently
6443
- * registered other key with a live watch, whose renewal contract the wallet's renewals pay
6444
- * into. A lapsed watch of any older key ends instead: it never held a coin, and reviving it
6445
- * would repeat for every rotation, forever.
6497
+ * Only a watch the wallet still needs is revived: the displayed boarding and receive keys', the
6498
+ * most recently registered other key's, and a renewal watch whose contract holds an unspent
6499
+ * coin, which the Executor must keep renewing while the wallet is offline. A lapsed watch of
6500
+ * any other key ends instead: it never held a coin, or none is left, and reviving it would
6501
+ * repeat for every rotation, forever.
6446
6502
  *
6447
6503
  * The status reads run as called; only the writes go through `write`, so a caller that orders
6448
6504
  * them with its rotations holds those back for one write, never for the whole refresh.
@@ -6501,7 +6557,7 @@ var ExecutorManagerImpl = class {
6501
6557
  (w) => w.contract.script === lapsed.contract.script
6502
6558
  );
6503
6559
  if (!watch?.live) return;
6504
- if (!await this.keyInUse(watch.owner, context.server)) {
6560
+ if (!await this.keyInUse(watch.owner, context.server) && !(template === "renewal" && await this.holdsCoin(watch.contract))) {
6505
6561
  await this.endWatch(watch, status);
6506
6562
  return;
6507
6563
  }
@@ -6532,19 +6588,28 @@ var ExecutorManagerImpl = class {
6532
6588
  )
6533
6589
  });
6534
6590
  }
6591
+ /** Whether `contract` holds an unspent, unswept coin, as stored. */
6592
+ async holdsCoin(contract) {
6593
+ const manager = await this.wallet.getContractManager();
6594
+ const [stored] = await manager.getStoredContractsWithVtxos({ script: contract.script });
6595
+ return (stored?.vtxos ?? []).some((v) => !isVtxoSpent(v) && !v.isSwept);
6596
+ }
6535
6597
  /**
6536
- * The displayed key, and the most recently registered other key with a live watch: the
6537
- * wallet's renewals pay into its renewal contract, and a rotation copies its params when the
6538
- * displayed key has no watch.
6598
+ * The displayed boarding key, the displayed receive key, and the most recently registered
6599
+ * other key with a live watch, whose params a rotation copies when the displayed key has no
6600
+ * watch.
6539
6601
  */
6540
6602
  async keyInUse(owner, server) {
6541
6603
  const displayed = await ownerKey(this.wallet.identity, await this.displayedDescriptor());
6542
6604
  const displayedOwner = hex.encode(displayed.subarray(1));
6543
- if (owner === displayedOwner) return true;
6605
+ const receiveOwner = this.wallet.offchainTapscript ? hex.encode(this.wallet.offchainTapscript.options.pubKey) : void 0;
6606
+ if (owner === displayedOwner || owner === receiveOwner) return true;
6544
6607
  const others = [
6545
6608
  ...await this.heldWatches("boarding"),
6546
6609
  ...await this.heldWatches("renewal")
6547
- ].filter((w) => w.live && w.signer === server && w.owner !== displayedOwner).sort((a, b) => registeredAt(b.contract) - registeredAt(a.contract));
6610
+ ].filter(
6611
+ (w) => w.live && w.signer === server && w.owner !== displayedOwner && w.owner !== receiveOwner
6612
+ ).sort((a, b) => registeredAt(b.contract) - registeredAt(a.contract));
6548
6613
  return others[0]?.owner === owner;
6549
6614
  }
6550
6615
  /**
@@ -6573,11 +6638,10 @@ var ExecutorManagerImpl = class {
6573
6638
  * params, or older ones registered again to move the boarding address back.
6574
6639
  */
6575
6640
  async storedWatch(descriptor, options, { emulatorPubkey }, template) {
6576
- const [address, owner] = await Promise.all([
6577
- this.wallet.getAddress(),
6641
+ const [{ hrp, serverPubKey }, owner] = await Promise.all([
6642
+ ownAddress(this.wallet),
6578
6643
  ownerKey(this.wallet.identity, descriptor)
6579
6644
  ]);
6580
- const { hrp, serverPubKey } = ArkAddress.decode(address);
6581
6645
  const server = hex.encode(serverPubKey);
6582
6646
  const xOnlyOwner = hex.encode(owner.subarray(1));
6583
6647
  const watch = (await this.heldWatches(template)).find(
@@ -6606,7 +6670,7 @@ var ExecutorManagerImpl = class {
6606
6670
  }
6607
6671
  /** The wallet's operator key, x-only hex: the signer a live watch is registered under. */
6608
6672
  async operatorSigner() {
6609
- return hex.encode(ArkAddress.decode(await this.wallet.getAddress()).serverPubKey);
6673
+ return hex.encode((await ownAddress(this.wallet)).serverPubKey);
6610
6674
  }
6611
6675
  /**
6612
6676
  * Both templates register the displayed boarding key: boarding moves its deposits in, renewal
@@ -6634,11 +6698,11 @@ var ExecutorManagerImpl = class {
6634
6698
  `Executor runs on ${info.network}, the wallet's operator on ${operator.network}`
6635
6699
  );
6636
6700
  }
6637
- const { hrp, serverPubKey } = ArkAddress.decode(await this.wallet.getAddress());
6701
+ const { hrp, serverPubKey } = await ownAddress(this.wallet);
6638
6702
  const server = hex.encode(serverPubKey);
6639
- if (info.serverPubkey.slice(2).toLowerCase() !== server) {
6703
+ if (info.operatorPubkey.slice(2).toLowerCase() !== server) {
6640
6704
  throw new Error(
6641
- `Executor's operator key ${info.serverPubkey} is not the wallet's operator ${server}`
6705
+ `Executor's operator key ${info.operatorPubkey} is not the wallet's operator ${server}`
6642
6706
  );
6643
6707
  }
6644
6708
  return {
@@ -6665,8 +6729,8 @@ var ExecutorManagerImpl = class {
6665
6729
  const owner = await ownerKey(this.wallet.identity, descriptor);
6666
6730
  const params = resolveParams(options, operator, template);
6667
6731
  const keys = {
6668
- cosignerPubkey: info.cosignerPubkey,
6669
- serverPubkey: info.serverPubkey,
6732
+ batchCosignerPubkey: info.batchCosignerPubkey,
6733
+ operatorPubkey: info.operatorPubkey,
6670
6734
  emulatorPubkey: info.emulatorPubkey
6671
6735
  };
6672
6736
  const variables = defaultVariables(template, owner, params);
@@ -15652,6 +15716,7 @@ var MAX_USED_SIGNING_DESCRIPTORS_LOOK_AHEAD = 1e3;
15652
15716
  var MAINNET_UNILATERAL_EXIT_DELAY = 605184n;
15653
15717
  var EXECUTOR_REFRESH_INTERVAL_MS = 24 * 60 * 60 * 1e3;
15654
15718
  var EXECUTOR_REFRESHED_KEY = "executorRefreshedAt";
15719
+ var EXECUTOR_RECEIVE_RETRY_MS = 10 * 60 * 1e3;
15655
15720
  function dedupeTimelocks(timelocks) {
15656
15721
  const seen = /* @__PURE__ */ new Set();
15657
15722
  const deduped = [];
@@ -16244,9 +16309,17 @@ var ReadonlyWallet = class _ReadonlyWallet {
16244
16309
  wallet.refreshDeprecatedSigners(setup.info);
16245
16310
  return wallet;
16246
16311
  }
16312
+ /**
16313
+ * The wallet's own address, under its own key: what its hrp and operator key are read from.
16314
+ * Not where to receive; that is {@link getAddress}, which answers the delegated twin once the
16315
+ * Executor watches this key.
16316
+ */
16247
16317
  get arkAddress() {
16248
16318
  return this.offchainTapscript.address(this.network.hrp, this.arkServerPublicKey);
16249
16319
  }
16320
+ async getOwnAddress() {
16321
+ return this.arkAddress.encode();
16322
+ }
16250
16323
  /**
16251
16324
  * Get the pkScript hex for the wallet's primary offchain address.
16252
16325
  * For the full wallet-owned script set registered in ContractManager, use getWalletScripts().
@@ -16255,11 +16328,42 @@ var ReadonlyWallet = class _ReadonlyWallet {
16255
16328
  return hex.encode(this.offchainTapscript.pkScript);
16256
16329
  }
16257
16330
  /**
16258
- * Returns the wallet's Arkade address. While an Executor renewal watch is live, the wallet's
16259
- * own renewals move coins received here into its renewal contract, which the Executor renews.
16331
+ * Returns the Arkade address to receive at: the delegated twin of the current receive key
16332
+ * while its Executor renewal watch is live, so the Executor renews what lands here while the
16333
+ * wallet is offline; the wallet's own address otherwise. See
16334
+ * {@link IExecutorManager.registerRenewal}.
16335
+ *
16336
+ * The answer changes without a receipt when a watch registers or ends, and when the operator
16337
+ * signer rotates: do not store it. Use {@link arkAddress} for the wallet's own address.
16260
16338
  */
16261
16339
  async getAddress() {
16262
- return this.arkAddress.encode();
16340
+ const serverPubKey = this.arkServerPublicKey;
16341
+ const tapscript = await this.destinationTapscript(serverPubKey);
16342
+ return tapscript.address(this.network.hrp, serverPubKey).encode();
16343
+ }
16344
+ /**
16345
+ * Where receives go under `serverPubKey`: the live Executor renewal watch of the receive key
16346
+ * (the delegated twin), else `own`. With `amount`, a twin the Executor cannot renew it at
16347
+ * (`maxFee + dust` or less) gives way to `own`. Fail-open: a lookup must not fail a receive.
16348
+ *
16349
+ * Callers read `own` and `serverPubKey` before their first await, then pass them here.
16350
+ */
16351
+ async destinationTapscript(serverPubKey, own = this.offchainTapscript, amount) {
16352
+ try {
16353
+ const twin = await receiveTwin(
16354
+ (filter) => collectContracts(this.contractRepository, filter),
16355
+ hex.encode(own.options.pubKey),
16356
+ toXOnlySignerHex(hex.encode(serverPubKey))
16357
+ );
16358
+ if (twin && (amount === void 0 || this.renews(twin, amount))) return twin.script;
16359
+ } catch (e) {
16360
+ console.warn("Unable to inspect Executor renewal watches", e);
16361
+ }
16362
+ return own;
16363
+ }
16364
+ /** Whether the Executor can renew `amount` at `watch`: not for `maxFee + dust` or less. */
16365
+ renews(watch, amount) {
16366
+ return amount > BigInt(watch.contract.params.maxFee) + this.dustAmount;
16263
16367
  }
16264
16368
  /**
16265
16369
  * Returns the onchain boarding address used to move funds into Arkade: with an Executor
@@ -17628,6 +17732,80 @@ var Wallet2 = class extends ReadonlyWallet {
17628
17732
  console.warn("Failed to register an Executor watch for the new boarding address", e);
17629
17733
  }
17630
17734
  }
17735
+ /**
17736
+ * @internal Register the Executor twin of the receive key at `descriptor`, under the params
17737
+ * of {@link delegationSource}: none means the app never opted in, and nothing is done.
17738
+ * Only the displayed key gets one: look-ahead addresses may have been issued to others and
17739
+ * are not delegated. Never throws: on failure the own address is shown until
17740
+ * {@link syncReceiveDelegation} registers the twin.
17741
+ */
17742
+ async registerReceiveTwin(descriptor) {
17743
+ const executor = this._executorManager;
17744
+ if (!executor) return;
17745
+ try {
17746
+ const watch = this.delegationSource(
17747
+ await this.liveRenewalWatches(
17748
+ toXOnlySignerHex(hex.encode(this.arkServerPublicKey))
17749
+ )
17750
+ );
17751
+ if (!watch) return;
17752
+ const { options, registration } = reRegistrationOf(watch);
17753
+ await executor.registerRenewalAt(descriptor, options, registration);
17754
+ } catch (e) {
17755
+ console.warn("Failed to register an Executor watch for the new receive address", e);
17756
+ }
17757
+ }
17758
+ /**
17759
+ * The live renewal watch whose params a twin copies: the displayed boarding key's, which
17760
+ * `registerRenewal` registers with the app's params, else the newest.
17761
+ */
17762
+ delegationSource(watches) {
17763
+ const boarding = hex.encode(this._boardingTapscript.options.pubKey);
17764
+ return watches.find((w) => w.owner === boarding) ?? watches[0];
17765
+ }
17766
+ _receiveSyncFailedAt = 0;
17767
+ /**
17768
+ * @internal The upkeep of receive delegation for an HD wallet that opted in, run from the poll
17769
+ * and at boot, and never throwing:
17770
+ * - the receive key never is the displayed boarding key, as a payment at the twin would
17771
+ * rotate boarding: it rotates boarding first, once, when they coincide;
17772
+ * - the displayed receive key gets its twin when a rotation could not register one, or a new
17773
+ * one when the app registered renewal with other params since.
17774
+ *
17775
+ * A failure is not tried again for a few minutes, as the Executor may be down.
17776
+ */
17777
+ syncReceiveDelegation() {
17778
+ const executor = this._executorManager;
17779
+ if (!executor || !this._descriptorProvider) return Promise.resolve();
17780
+ return this.onBoardChain(async () => {
17781
+ if (this._executorStopping || Date.now() - this._receiveSyncFailedAt < EXECUTOR_RECEIVE_RETRY_MS) {
17782
+ return;
17783
+ }
17784
+ const signer = toXOnlySignerHex(hex.encode(this.arkServerPublicKey));
17785
+ const watches = await this.liveRenewalWatches(signer);
17786
+ if (watches.length === 0) return;
17787
+ const key = hex.encode(this.offchainTapscript.options.pubKey);
17788
+ if (key === hex.encode(this._boardingTapscript.options.pubKey)) {
17789
+ await this.rotateBoarding();
17790
+ }
17791
+ const source = this.delegationSource(watches);
17792
+ const twin = watches.find((w) => w.owner === key);
17793
+ if (twin && sameDelegation(twin, source)) return;
17794
+ const [row] = await (await this.getContractManager()).getContracts({
17795
+ script: this.defaultContractScript
17796
+ });
17797
+ const descriptor = row?.metadata?.signingDescriptor;
17798
+ const { options, registration } = reRegistrationOf(source);
17799
+ await executor.registerRenewalAt(
17800
+ typeof descriptor === "string" ? descriptor : await identityDescriptor(this.identity),
17801
+ options,
17802
+ registration
17803
+ );
17804
+ }).catch((e) => {
17805
+ this._receiveSyncFailedAt = Date.now();
17806
+ console.warn("Failed to keep the receive address under Executor delegation", e);
17807
+ });
17808
+ }
17631
17809
  /**
17632
17810
  * Startup work for an Executor: refresh its watches (every wallet), then, with a descriptor
17633
17811
  * provider, rotate-on-board. The Executor boards a deposit into the renewal contract of its
@@ -17669,7 +17847,7 @@ var Wallet2 = class extends ReadonlyWallet {
17669
17847
  * Best-effort: never throws. Never call it from a board chain task: it would wait on itself.
17670
17848
  */
17671
17849
  refreshExecutorWatches() {
17672
- this._executorRefreshing ??= this.refreshExecutorWatchesNow().finally(() => {
17850
+ this._executorRefreshing ??= this.refreshExecutorWatchesNow().then(() => this.syncReceiveDelegation()).finally(() => {
17673
17851
  this._executorRefreshing = void 0;
17674
17852
  });
17675
17853
  return this._executorRefreshing;
@@ -18018,6 +18196,7 @@ var Wallet2 = class extends ReadonlyWallet {
18018
18196
  }
18019
18197
  async _doRotateServerSigner(xonly, newServerUnrollScript) {
18020
18198
  if (equalBytes(xonly, this.arkServerPublicKey)) return;
18199
+ const previousSigner = toXOnlySignerHex(hex.encode(this.arkServerPublicKey));
18021
18200
  const manager = await this.getContractManager();
18022
18201
  const currentBoardingScript = hex.encode(this._boardingTapscript.pkScript);
18023
18202
  const [offchainRows2, boardingRows] = await Promise.all([
@@ -18090,6 +18269,14 @@ var Wallet2 = class extends ReadonlyWallet {
18090
18269
  } catch (e) {
18091
18270
  console.warn("look-ahead refill after server-signer rotation failed", e);
18092
18271
  }
18272
+ if (this._executorManager) {
18273
+ const held = await this.liveRenewalWatches(previousSigner).catch(() => []);
18274
+ if (held.length > 0) {
18275
+ console.warn(
18276
+ "Executor delegations stay under the previous operator key, and getAddress() shows the own address: call registerRenewal() again to delegate under the new one"
18277
+ );
18278
+ }
18279
+ }
18093
18280
  }
18094
18281
  /**
18095
18282
  * Serializes `settle`/`send` so VtxoManager's background renewal can't race user
@@ -20635,8 +20822,8 @@ var Wallet2 = class extends ReadonlyWallet {
20635
20822
  }
20636
20823
  /**
20637
20824
  * Change follows its inputs: a send spending a coin at a live renewal watch returns the change
20638
- * to that contract, so the Executor keeps renewing it. The own script otherwise. Fail-open: a
20639
- * send must not fail over a delegation lookup.
20825
+ * to that contract, so the Executor keeps renewing it. Otherwise it goes where receives go.
20826
+ * Fail-open: a send must not fail over a delegation lookup.
20640
20827
  */
20641
20828
  async changeTapscriptFor(inputs, changeAmount, serverPubKey, own) {
20642
20829
  try {
@@ -20648,8 +20835,9 @@ var Wallet2 = class extends ReadonlyWallet {
20648
20835
  }
20649
20836
  } catch (e) {
20650
20837
  console.warn("Unable to inspect Executor renewal watches", e);
20838
+ return own;
20651
20839
  }
20652
- return own;
20840
+ return this.destinationTapscript(serverPubKey, own, BigInt(changeAmount));
20653
20841
  }
20654
20842
  /** The live Executor renewal watches under `signer`, the operator's x-only key. */
20655
20843
  async liveRenewalWatches(signer) {
@@ -20657,35 +20845,34 @@ var Wallet2 = class extends ReadonlyWallet {
20657
20845
  (w) => w.live && w.signer === signer
20658
20846
  );
20659
20847
  }
20660
- /** Whether the Executor can renew `amount` at `watch`: not for `maxFee + dust` or less. */
20661
- renews(watch, amount) {
20662
- return amount > BigInt(watch.contract.params.maxFee) + this.dustAmount;
20663
- }
20664
20848
  /**
20665
- * @internal Where the wallet's own renewals pay `amount`: the newest live Executor renewal
20666
- * contract under the current operator, so the Executor renews the coin from then on. One the
20667
- * displayed boarding key does not own comes first: a coin at that key's contract rotates the
20668
- * boarding address. The wallet's address when none applies, for `maxFee + dust` or less, which
20669
- * the Executor cannot renew, or when a renewed coin carries assets, which `settle()` places
20670
- * only at the wallet's address. Also the wallet's address when any of `inputScripts` sits at a
20671
- * live renewal contract, whatever the reason: the Executor had its chance at that coin, and
20672
- * paying it back there only repeats the miss. Fail-open: a renewal must not fail over a
20673
- * delegation lookup.
20849
+ * @internal Where the wallet's own renewals pay `amount`: {@link getAddress}, except for
20850
+ * `maxFee + dust` or less, which the Executor cannot renew, and when any of `inputScripts`
20851
+ * sits at a live renewal contract, whatever the reason: the Executor had its chance at that
20852
+ * coin, and paying it back there only repeats the miss. Both pay the wallet's own address.
20853
+ * Fail-open: a renewal must not fail over a delegation lookup.
20854
+ *
20855
+ * {@link VtxoManager} does not ask for a renewal of a coin that carries assets: `settle()`
20856
+ * places assets only at {@link getAddress}, which that renewal pays whatever the rules above say.
20674
20857
  */
20675
20858
  async renewalAddress(amount, inputScripts = []) {
20676
- const own = await this.getAddress();
20677
- try {
20678
- const { hrp, serverPubKey } = ArkAddress.decode(own);
20679
- const displayed = hex.encode(this._boardingTapscript.options.pubKey);
20680
- const underOperator = await this.liveRenewalWatches(hex.encode(serverPubKey));
20681
- if (underOperator.some((w) => inputScripts.includes(w.contract.script))) return own;
20682
- const live = underOperator.filter((w) => this.renews(w, amount));
20683
- const watch = live.find((w) => w.owner !== displayed) ?? live[0];
20684
- return watch ? watch.script.address(hrp, serverPubKey).encode() : own;
20685
- } catch (e) {
20686
- console.warn("Unable to inspect Executor renewal watches", e);
20687
- return own;
20859
+ const own = this.offchainTapscript;
20860
+ const serverPubKey = this.arkServerPublicKey;
20861
+ const addressOf = (tapscript) => tapscript.address(this.network.hrp, serverPubKey).encode();
20862
+ if (inputScripts.length > 0) {
20863
+ try {
20864
+ const live = await this.liveRenewalWatches(
20865
+ toXOnlySignerHex(hex.encode(serverPubKey))
20866
+ );
20867
+ if (live.some((w) => inputScripts.includes(w.contract.script))) {
20868
+ return addressOf(own);
20869
+ }
20870
+ } catch (e) {
20871
+ console.warn("Unable to inspect Executor renewal watches", e);
20872
+ return addressOf(own);
20873
+ }
20688
20874
  }
20875
+ return addressOf(await this.destinationTapscript(serverPubKey, own, amount));
20689
20876
  }
20690
20877
  /**
20691
20878
  * Shared submit/persist tail of `send` and {@link sendSelectedVtxosToSelf}; callers own coin
@@ -23197,6 +23384,14 @@ var WalletMessageHandler = class {
23197
23384
  payload: { address }
23198
23385
  });
23199
23386
  }
23387
+ case "GET_OWN_ADDRESS": {
23388
+ const address = await readonlyWallet.getOwnAddress();
23389
+ return this.tagged({
23390
+ id,
23391
+ type: "OWN_ADDRESS",
23392
+ payload: { address }
23393
+ });
23394
+ }
23200
23395
  case "GET_BOARDING_ADDRESS": {
23201
23396
  const address = await readonlyWallet.getBoardingAddress();
23202
23397
  return this.tagged({
@@ -24501,6 +24696,7 @@ var initWaitBackoffMs = (attempt) => Math.min(100 * 2 ** attempt, INIT_WAIT_BACK
24501
24696
  var DEFAULT_MESSAGE_TIMEOUTS = {
24502
24697
  // Fast reads — fail quickly
24503
24698
  GET_ADDRESS: 1e4,
24699
+ GET_OWN_ADDRESS: 1e4,
24504
24700
  GET_BALANCE: 1e4,
24505
24701
  GET_BOARDING_ADDRESS: 1e4,
24506
24702
  GET_STATUS: 1e4,
@@ -24595,6 +24791,7 @@ var DEFAULT_MESSAGE_TIMEOUTS = {
24595
24791
  };
24596
24792
  var DEDUPABLE_REQUEST_TYPES = /* @__PURE__ */ new Set([
24597
24793
  "GET_ADDRESS",
24794
+ "GET_OWN_ADDRESS",
24598
24795
  "GET_OPERATOR_INFO",
24599
24796
  "INDEXER_GET_VTXOS",
24600
24797
  "INDEXER_GET_VIRTUAL_TXS",
@@ -25193,6 +25390,22 @@ var ServiceWorkerReadonlyWallet = class _ServiceWorkerReadonlyWallet {
25193
25390
  throw new Error(`Failed to get address: ${error}`);
25194
25391
  }
25195
25392
  }
25393
+ async getOwnAddress() {
25394
+ const message = {
25395
+ id: getRandomId(),
25396
+ tag: this.messageTag,
25397
+ type: "GET_OWN_ADDRESS"
25398
+ };
25399
+ try {
25400
+ const response = await this.sendMessage(message);
25401
+ return response.payload.address;
25402
+ } catch (error) {
25403
+ if (error instanceof Error && error.message === "Unknown message") {
25404
+ return this.getAddress();
25405
+ }
25406
+ throw new Error(`Failed to get own address: ${error}`);
25407
+ }
25408
+ }
25196
25409
  async getBoardingAddress() {
25197
25410
  const message = {
25198
25411
  id: getRandomId(),
@@ -29261,7 +29474,9 @@ var Arkade = class _Arkade {
29261
29474
  * the program's literal type, so `functions` is strongly typed.
29262
29475
  *
29263
29476
  * Declared `server`/`user` params default to the client's keys. Compiler
29264
- * artifacts reserve the operator key and exit delay to the connected operator.
29477
+ * artifacts reserve the operator key and exit delay to the connected operator,
29478
+ * and the witness program of each contract they instantiate to the derived one
29479
+ * (see {@link ArkadeContract}'s constructor).
29265
29480
  * Struct and array params are passed whole by name (see {@link ArkadeNestedValue}).
29266
29481
  */
29267
29482
  contract(program, args = {}) {
@@ -29273,18 +29488,7 @@ var Arkade = class _Arkade {
29273
29488
  args = { ...args, user: this.userKey };
29274
29489
  }
29275
29490
  if (declared.includes("SERVER_EXIT_DELAY")) {
29276
- const delay = this.serverExitDelay;
29277
- if (delay === void 0 || delay <= 0n)
29278
- throw new Error(
29279
- "compiler artifact: server must provide a positive unilateral exit delay"
29280
- );
29281
- const typed = toTimelock(delay);
29282
- if (typed.type === "seconds" && delay % 512n !== 0n) {
29283
- throw new Error(
29284
- `compiler artifact: server exit delay ${delay}s must be a multiple of 512 seconds`
29285
- );
29286
- }
29287
- const sequence = BigInt(timelockToSequence(typed));
29491
+ const sequence = exitDelaySequence(this.serverExitDelay);
29288
29492
  if (args.SERVER_EXIT_DELAY !== void 0 && args.SERVER_EXIT_DELAY !== sequence && args.SERVER_EXIT_DELAY !== Number(sequence)) {
29289
29493
  throw new Error(
29290
29494
  "compiler artifact: reserved SERVER_EXIT_DELAY must match the connected server"
@@ -29303,6 +29507,11 @@ var Arkade = class _Arkade {
29303
29507
  }
29304
29508
  };
29305
29509
  var ArkadeContract = class _ArkadeContract {
29510
+ /**
29511
+ * Compile `program` with `args` against `keys` (the client's by default). Each contract a
29512
+ * compiler artifact instantiates is bound to its witness program, derived with `keys` and the
29513
+ * client's exit delay; a value passed for it by hand must match.
29514
+ */
29306
29515
  constructor(client, program, args = {}, keys) {
29307
29516
  this.client = client;
29308
29517
  this.program = program;
@@ -29313,6 +29522,7 @@ var ArkadeContract = class _ArkadeContract {
29313
29522
  userKey: client.userKey,
29314
29523
  emulatorKey: client.emulatorKey
29315
29524
  };
29525
+ instantiate(program, this.args, this.keys, client.serverExitDelay);
29316
29526
  this.vtxoScript = new ArkadeProgramScript(program, this.args, this.keys);
29317
29527
  this.tapTree = this.vtxoScript.encode();
29318
29528
  this.compiled = this.vtxoScript.compiled;
@@ -29933,6 +30143,47 @@ function unspendable(coin, now) {
29933
30143
  function witnessBytes({ contract, args }, segment, ref) {
29934
30144
  return witnessRefToBytes(ref, args[segment], contract.args);
29935
30145
  }
30146
+ function exitDelaySequence(delay) {
30147
+ if (delay === void 0 || delay <= 0n)
30148
+ throw new Error("compiler artifact: server must provide a positive unilateral exit delay");
30149
+ const typed = toTimelock(delay);
30150
+ if (typed.type === "seconds" && delay % 512n !== 0n) {
30151
+ throw new Error(
30152
+ `compiler artifact: server exit delay ${delay}s must be a multiple of 512 seconds`
30153
+ );
30154
+ }
30155
+ return BigInt(timelockToSequence(typed));
30156
+ }
30157
+ function instantiate(program, args, keys, exitDelay) {
30158
+ const defs = new Map((program.params ?? []).map((def) => [def.name, def]));
30159
+ for (const [param, child] of Object.entries(instantiatedContracts(program))) {
30160
+ const childArgs = { server: keys.serverKey };
30161
+ for (const [name, from] of Object.entries(child.args)) {
30162
+ if (typeof from !== "string") {
30163
+ childArgs[name] = from;
30164
+ continue;
30165
+ }
30166
+ const value = Object.hasOwn(args, from) ? args[from] : void 0;
30167
+ if (value === void 0) {
30168
+ throw new Error(`program parameter '${from}' is declared but not bound in args`);
30169
+ }
30170
+ validateParamValue(defs.get(from), value);
30171
+ childArgs[name] = value;
30172
+ }
30173
+ if (child.program.params?.some((p) => p.name === "SERVER_EXIT_DELAY")) {
30174
+ childArgs.SERVER_EXIT_DELAY = exitDelaySequence(exitDelay);
30175
+ }
30176
+ instantiate(child.program, childArgs, keys, exitDelay);
30177
+ const key = new ArkadeProgramScript(child.program, childArgs, keys).tweakedPublicKey;
30178
+ const passed = args[param];
30179
+ if (passed !== void 0 && !(passed instanceof Uint8Array && equalBytes(passed, key))) {
30180
+ throw new Error(
30181
+ `compiler artifact: '${param}' must be the ${child.program.name} witness program derived from its arguments`
30182
+ );
30183
+ }
30184
+ args[param] = key;
30185
+ }
30186
+ }
29936
30187
  function flattenValue(name, value, out, ancestors = /* @__PURE__ */ new Set()) {
29937
30188
  if (typeof value !== "object" || value === null || ArrayBuffer.isView(value)) {
29938
30189
  if (Object.hasOwn(out, name)) throw new Error(`duplicate argument '${name}'`);
@@ -30486,5 +30737,5 @@ function createDefaultPaymentRouter(wallet) {
30486
30737
  */
30487
30738
 
30488
30739
  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 };
30489
- //# sourceMappingURL=chunk-HWWSLCQN.js.map
30490
- //# sourceMappingURL=chunk-HWWSLCQN.js.map
30740
+ //# sourceMappingURL=chunk-ZECZ2MKX.js.map
30741
+ //# sourceMappingURL=chunk-ZECZ2MKX.js.map