@arkade-os/sdk 0.5.13 → 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 (90) hide show
  1. package/README.md +55 -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-Dhbe00Ya.d.ts → asyncStorageTaskQueue-B3umqlkb.d.ts} +1 -1
  9. package/dist/{asyncStorageTaskQueue-Y4BlVm41.d.cts → asyncStorageTaskQueue-Dq6AJHNv.d.cts} +1 -1
  10. package/dist/{chunk-TYSUFG2K.cjs → chunk-35GRSVCZ.cjs} +11 -11
  11. package/dist/{chunk-TYSUFG2K.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-6WPP4UGN.cjs → chunk-CMFRCBZW.cjs} +1245 -658
  15. package/dist/chunk-CMFRCBZW.cjs.map +1 -0
  16. package/dist/{chunk-HS7TKVOZ.cjs → chunk-FKHUXSYW.cjs} +8 -4
  17. package/dist/chunk-FKHUXSYW.cjs.map +1 -0
  18. package/dist/{chunk-BP4NA7HK.js → chunk-HVUZKXB2.js} +4 -4
  19. package/dist/{chunk-BP4NA7HK.js.map → chunk-HVUZKXB2.js.map} +1 -1
  20. package/dist/{chunk-6XVTGWQK.cjs → chunk-INQAIZUO.cjs} +17 -17
  21. package/dist/{chunk-6XVTGWQK.cjs.map → chunk-INQAIZUO.cjs.map} +1 -1
  22. package/dist/{chunk-WFJPLXOE.cjs → chunk-JSYS2KX3.cjs} +18 -18
  23. package/dist/{chunk-WFJPLXOE.cjs.map → chunk-JSYS2KX3.cjs.map} +1 -1
  24. package/dist/{chunk-QSERJPTT.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-TD4PKK2I.cjs → chunk-VIQF74QJ.cjs} +38 -33
  29. package/dist/chunk-VIQF74QJ.cjs.map +1 -0
  30. package/dist/{chunk-D4QH6L54.js → chunk-XPZ7TMXH.js} +4 -4
  31. package/dist/{chunk-D4QH6L54.js.map → chunk-XPZ7TMXH.js.map} +1 -1
  32. package/dist/{chunk-BA36SQY2.js → chunk-YYSHQPCG.js} +3 -3
  33. package/dist/{chunk-BA36SQY2.js.map → chunk-YYSHQPCG.js.map} +1 -1
  34. package/dist/{chunk-LHLRG2BE.js → chunk-Z4LG3CZ4.js} +8 -5
  35. package/dist/chunk-Z4LG3CZ4.js.map +1 -0
  36. package/dist/{chunk-Y3AWLHQP.js → chunk-ZECZ2MKX.js} +730 -143
  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 +10 -10
  41. package/dist/compiler.d.ts +10 -10
  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 +3 -3
  46. package/dist/contracts/handlers/index.d.ts +3 -3
  47. package/dist/contracts/handlers/index.js +3 -3
  48. package/dist/{index-BQwrHcOh.d.cts → index-Bi22mLsh.d.cts} +212 -43
  49. package/dist/{index-BapVvuoI.d.ts → index-CiLMmCHX.d.ts} +2 -2
  50. package/dist/{index-DuXylQrN.d.ts → index-DOdoDqvM.d.ts} +212 -43
  51. package/dist/{index-BaTItxPx.d.cts → index-DnKugm-h.d.cts} +2 -2
  52. package/dist/index.cjs +327 -327
  53. package/dist/index.d.cts +149 -114
  54. package/dist/index.d.ts +149 -114
  55. package/dist/index.js +5 -5
  56. package/dist/{program-DPzf5qsk.d.cts → program-ZWUAWy_9.d.cts} +1 -1
  57. package/dist/{program-38A2Twvj.d.ts → program-zdDO4cMt.d.ts} +1 -1
  58. package/dist/repositories/realm/index.cjs +38 -38
  59. package/dist/repositories/realm/index.d.cts +2 -2
  60. package/dist/repositories/realm/index.d.ts +2 -2
  61. package/dist/repositories/realm/index.js +6 -6
  62. package/dist/repositories/sqlite/index.cjs +36 -36
  63. package/dist/repositories/sqlite/index.d.cts +2 -2
  64. package/dist/repositories/sqlite/index.d.ts +2 -2
  65. package/dist/repositories/sqlite/index.js +6 -6
  66. package/dist/{taskRunner-BxOmg-O6.d.ts → taskRunner-CoE4Xx9K.d.ts} +1 -1
  67. package/dist/{taskRunner-D2itCXf6.d.cts → taskRunner-DFG0BN_R.d.cts} +1 -1
  68. package/dist/wallet/expo/background.cjs +15 -15
  69. package/dist/wallet/expo/background.d.cts +3 -3
  70. package/dist/wallet/expo/background.d.ts +3 -3
  71. package/dist/wallet/expo/background.js +7 -7
  72. package/dist/wallet/expo/index.cjs +19 -16
  73. package/dist/wallet/expo/index.cjs.map +1 -1
  74. package/dist/wallet/expo/index.d.cts +3 -2
  75. package/dist/wallet/expo/index.d.ts +3 -2
  76. package/dist/wallet/expo/index.js +9 -6
  77. package/dist/wallet/expo/index.js.map +1 -1
  78. package/dist/worker/expo/index.cjs +10 -10
  79. package/dist/worker/expo/index.d.cts +4 -4
  80. package/dist/worker/expo/index.d.ts +4 -4
  81. package/dist/worker/expo/index.js +6 -6
  82. package/package.json +3 -3
  83. package/dist/chunk-6WPP4UGN.cjs.map +0 -1
  84. package/dist/chunk-ACIQZLWL.cjs.map +0 -1
  85. package/dist/chunk-HS7TKVOZ.cjs.map +0 -1
  86. package/dist/chunk-LHLRG2BE.js.map +0 -1
  87. package/dist/chunk-QSERJPTT.js.map +0 -1
  88. package/dist/chunk-TD4PKK2I.cjs.map +0 -1
  89. package/dist/chunk-X57WKONW.js.map +0 -1
  90. package/dist/chunk-Y3AWLHQP.js.map +0 -1
package/README.md CHANGED
@@ -432,6 +432,12 @@ try {
432
432
 
433
433
  `OnchainCosignAmbiguousError` means the transaction may have been broadcast (a transport failure, or a server error after submission): do not retry with other coins. The inputs stay pending until the chain resolves.
434
434
 
435
+ For `sendOnchain` and `cosignOnchainTx` that check is enough. `Ramps.offboardExact` is stricter, because `isCosignFallback(e)` only says arkd did not sign. The wallet already did, and an operator that kept the signed transaction can complete it later, so it rethrows every `OnchainCosignRejectedError` after signing instead of paying through a batch. Paying from other coins could pay twice, and a batch offboard cannot be made to conflict with the kept transaction: arkd refuses an intent that has onchain (boarding) inputs and onchain outputs (`INVALID_INTENT_PROOF`). The caller picks the strategy:
436
+
437
+ - Wait for the held inputs to resolve and retry. The hold ends when an onchain sync sees the coins spent, or releases them once the chain tip is 6 blocks (`ONCHAIN_PENDING_RELEASE_BLOCKS`, fixed, not `onchainCosignMarginBlocks`) past the tip at signing. There is no event for it: track the block height and retry after that. The sync may show that the original payment went through, so before retrying check that it did not complete (the coins are spent, or the recipient has the funds), and retry only if it did not.
438
+ - Settle the boarding coins into VTXOs first (no onchain output), then offboard from those. That spends the coins, so the kept transaction can no longer confirm, but it joins a batch before the coins expire, which costs the user a fee and a fresh VTXO lifetime.
439
+ - Accept the risk and pay again, if the operator is trusted not to complete the transaction.
440
+
435
441
  Contracts carry a `scope`: `"offchain"`, `"onchain"` or `"both"`. It controls whether the contract's onchain coins are watched and spent through cosigning; boarding contracts default to `"onchain"`.
436
442
 
437
443
  Automatic behaviour:
@@ -728,8 +734,54 @@ const balance = await manager.getRecoverableBalance()
728
734
  ```
729
735
 
730
736
 
737
+ ### Executor
738
+
739
+ The Executor renews the wallet's virtual outputs and boards its deposits while the wallet is
740
+ offline. It is opt-in: without it the wallet behaves as before.
741
+
742
+ ```typescript
743
+ import { Wallet, RestExecutorProvider } from '@arkade-os/sdk'
744
+
745
+ const wallet = await Wallet.create({
746
+ identity,
747
+ executorProvider: new RestExecutorProvider('https://executor.arkade.sh'),
748
+ })
749
+ // ServiceWorkerWallet.setup takes `executorUrl` instead
750
+
751
+ const executor = await wallet.getExecutorManager()
752
+ const params = { renewalWindow: 30 * 60, maxFee: 1_000 } // seconds, sats
753
+ await executor?.registerBoarding(params)
754
+ await executor?.registerRenewal(params)
755
+ ```
756
+
757
+ Call both at every startup: they are idempotent, and the Executor expires a watch that never
758
+ held a coin. See `registerBoarding` and `registerRenewal` for the details.
759
+
760
+ #### Receiving
761
+
762
+ - After `registerRenewal`, `getAddress()` answers the receive key's renewal contract, its
763
+ delegated twin, while that watch is live, and the wallet's own address otherwise. It can
764
+ change without a payment (a watch registers or ends, the operator signer rotates): read it
765
+ when you show it, never store it.
766
+ - `getOwnAddress()` is the wallet's own address, for anything bound to the wallet, such as an
767
+ LNURL handle. On an HD wallet it rotates with the receive key.
768
+ - `getBoardingAddress()` answers the delegated boarding address; the Executor boards a deposit
769
+ there into the renewal contract.
770
+ - Not delegated: look-ahead addresses and `getNewAddresses`. What lands there is renewed by the
771
+ wallet itself.
772
+
773
+ #### Trust and privacy
774
+
775
+ - The Executor can delay a renewal or a board, not spend: it spends only through leaves the
776
+ emulator enforces, which pay the wallet. The wallet keeps its own paths and renews a coin
777
+ itself once half the `renewalWindow` is left.
778
+ - It sees the amount and time of every payment to a twin, and can link an HD wallet's twins to
779
+ one wallet.
780
+
731
781
  ### Delegation
732
782
 
783
+ > **Deprecated**: the delegator is retired; use the [Executor](#executor).
784
+
733
785
  Delegation allows users to outsource virtual output renewal to a third-party delegation service.
734
786
 
735
787
  Instead of the delegating user renewing virtual outputs by themselves, their delegate will automatically settle them before they expire, sending the funds back to the user's wallet address (minus a service fee).
@@ -1608,7 +1660,9 @@ await wallet.send({ address: contract.address, amount: 10_000 })
1608
1660
 
1609
1661
  `contract.on('vtxo_received' | 'vtxo_spent' | 'connection_reset', cb)` reports activity from subscription on and returns a handle with `off()`. Coins that predate it are not replayed and a reconnect re-syncs silently, so read `contract.getVtxos()` (every stored VTXO, spent ones included) after subscribing and on each `connection_reset`.
1610
1662
 
1611
- The connected operator supplies `<SERVER_KEY>` (the reserved `server` parameter in normalized Programs) and `<SERVER_EXIT_DELAY>`; conflicting overrides fail, and time-based delays that are not multiples of 512 seconds fail rather than changing the advertised delay. Resolved bindings are persisted, so restoring the contract keeps its script through server key or policy changes. A declared constructor named `user` defaults to the connected identity; other constructor keys remain caller-provided. Pass a struct or array param whole by its source name, such as `{ owners: [{ key }, { key }] }`; the flattened names it binds, such as `owners.0.key`, are also accepted, and a missing, extra or duplicated field fails with its full name. Child-output placeholders remain explicit `bytes32` constructor bindings. Leaf call inputs used as script operands cannot produce a fixed address and are rejected; raw CSV operands must be canonical BIP68 encodings.
1663
+ The connected operator supplies the operator placeholders, which [`programFromArtifact`](./src/arkade/artifact.ts) reads as the reserved `server` and `SERVER_EXIT_DELAY` parameters and the emulator key. Compiler 0.1.0 accepts constructor inputs with those two names, but the SDK refuses them, so rename them in the source. Conflicting overrides fail, and time-based delays that are not multiples of 512 seconds fail rather than changing the advertised delay. Resolved bindings are persisted, so restoring the contract keeps its script through server key or policy changes. A declared constructor named `user` defaults to the connected identity; other constructor keys remain caller-provided. Pass a struct or array param whole by its source name, such as `{ owners: [{ key }, { key }] }`; the flattened names it binds, such as `owners.0.key`, are also accepted, and a missing, extra or duplicated field fails with its full name. Leaf call inputs used as script operands cannot produce a fixed address and are rejected; raw CSV operands must be canonical BIP68 encodings.
1664
+
1665
+ A contract that instantiates another, as in `tx.outputs[0].script == new SingleSig(receiver)`, compiles to a `<CONTRACT:SingleSig(<receiver>)>` placeholder for the child's witness program. Pass the artifact of every contract it instantiates, directly or through another, as one flat list: `arkade.programFromArtifact(htlc, { contracts: [singleSig] })`. Each must have the code hash the parent pins in its `contracts` field; the SDK recomputes that hash from the child's own fields in the order arkadec wrote them, so a missing, edited or re-serialized child is refused, and so is a parent artifact without `contracts` pins, which needs recompiling. Building the contract, with `client.contract()` or `new ArkadeContract(...)`, then compiles each child with the same keys as the contract and the connected exit delay, from only the values the parent passes, and binds its witness program to a `bytes32` param such as `contract_SingleSig_receiver`; a value passed for it by hand must match. Only that key is persisted, so restoring the contract needs no child artifacts. `compile()` from `@arkade-os/sdk/compiler` takes the same `contracts` option, with the artifacts of the child contracts compiled on their own.
1612
1666
 
1613
1667
  Call arguments are grouped by the script whose witness they fill: `arkadeScript` holds the covenant inputs, which go into the emulator packet, and `tapscript` holds the non-signature leaf inputs, which go into the leaf's `ConditionWitness`, as in `contract.functions.claim({ arkadeScript: [preimage, flag], tapscript: [leafPreimage] })`. Each list follows declaration order with one argument per source parameter, so a struct or array input is passed whole, as in `contract.functions.spend({ arkadeScript: [request, oracles] })`. Omit the key of a segment without inputs, and call a function without inputs with no arguments. Same-named inputs in the two scopes stay independent. Hand-written programs declare inputs on the segment whose `witness` names them (`tapscript.inputs`, `arkadeScript.inputs`). Leaf signatures are PSBT signatures, not condition arguments: `send()` supports the connected identity and infrastructure signers; additional identities and covenant-tweaked leaf keys require explicit PSBT signing via `build()`. Covenant signature arguments remain caller-provided; transaction-bound Arkade `checkSig` signatures require an Arkade-specific digest helper, which is deferred. CSV leaves require aged onchain outputs and cannot use this offchain builder. Typed call validation and these spending limits apply to every normalized Program. The public `SignerRef` union is unchanged; version 1 programs store emulator signer placement in optional `emulatorIndex` metadata.
1614
1668
 
@@ -1,23 +1,23 @@
1
1
  'use strict';
2
2
 
3
- var chunk6XVTGWQK_cjs = require('../chunk-6XVTGWQK.cjs');
4
- require('../chunk-WFJPLXOE.cjs');
5
- require('../chunk-HS7TKVOZ.cjs');
3
+ var chunkINQAIZUO_cjs = require('../chunk-INQAIZUO.cjs');
4
+ require('../chunk-JSYS2KX3.cjs');
5
+ require('../chunk-FKHUXSYW.cjs');
6
6
  require('../chunk-6TBTL42M.cjs');
7
7
 
8
8
 
9
9
 
10
10
  Object.defineProperty(exports, "ExpoArkProvider", {
11
11
  enumerable: true,
12
- get: function () { return chunk6XVTGWQK_cjs.ExpoArkProvider; }
12
+ get: function () { return chunkINQAIZUO_cjs.ExpoArkProvider; }
13
13
  });
14
14
  Object.defineProperty(exports, "ExpoIndexerProvider", {
15
15
  enumerable: true,
16
- get: function () { return chunk6XVTGWQK_cjs.ExpoIndexerProvider; }
16
+ get: function () { return chunkINQAIZUO_cjs.ExpoIndexerProvider; }
17
17
  });
18
18
  Object.defineProperty(exports, "ExpoOperatorProvider", {
19
19
  enumerable: true,
20
- get: function () { return chunk6XVTGWQK_cjs.ExpoOperatorProvider; }
20
+ get: function () { return chunkINQAIZUO_cjs.ExpoOperatorProvider; }
21
21
  });
22
22
  //# sourceMappingURL=expo.cjs.map
23
23
  //# sourceMappingURL=expo.cjs.map
@@ -1,5 +1,5 @@
1
- import { u as RestOperatorProvider, q as SettlementEvent, T as TxNotificationEvent, v as RestIndexerProvider, w as SubscriptionEvent, x as SubscriptionHeartbeat } from '../index-BQwrHcOh.cjs';
2
- export { y as ArkProvider, z as IndexerProvider, B as OperatorProvider } from '../index-BQwrHcOh.cjs';
1
+ import { u as RestOperatorProvider, q as SettlementEvent, T as TxNotificationEvent, v as RestIndexerProvider, w as SubscriptionEvent, x as SubscriptionHeartbeat } from '../index-Bi22mLsh.cjs';
2
+ export { y as ArkProvider, z as IndexerProvider, B as OperatorProvider } from '../index-Bi22mLsh.cjs';
3
3
  import '@scure/btc-signer/utils.js';
4
4
  import '@scure/btc-signer';
5
5
  import '@scure/btc-signer/psbt.js';
@@ -1,5 +1,5 @@
1
- import { u as RestOperatorProvider, q as SettlementEvent, T as TxNotificationEvent, v as RestIndexerProvider, w as SubscriptionEvent, x as SubscriptionHeartbeat } from '../index-DuXylQrN.js';
2
- export { y as ArkProvider, z as IndexerProvider, B as OperatorProvider } from '../index-DuXylQrN.js';
1
+ import { u as RestOperatorProvider, q as SettlementEvent, T as TxNotificationEvent, v as RestIndexerProvider, w as SubscriptionEvent, x as SubscriptionHeartbeat } from '../index-DOdoDqvM.js';
2
+ export { y as ArkProvider, z as IndexerProvider, B as OperatorProvider } from '../index-DOdoDqvM.js';
3
3
  import '@scure/btc-signer/utils.js';
4
4
  import '@scure/btc-signer';
5
5
  import '@scure/btc-signer/psbt.js';
@@ -1,6 +1,6 @@
1
- export { ExpoArkProvider, ExpoIndexerProvider, ExpoOperatorProvider } from '../chunk-BP4NA7HK.js';
2
- import '../chunk-BA36SQY2.js';
3
- import '../chunk-LHLRG2BE.js';
1
+ export { ExpoArkProvider, ExpoIndexerProvider, ExpoOperatorProvider } from '../chunk-HVUZKXB2.js';
2
+ import '../chunk-YYSHQPCG.js';
3
+ import '../chunk-Z4LG3CZ4.js';
4
4
  import '../chunk-GB67AGXG.js';
5
5
  //# sourceMappingURL=expo.js.map
6
6
  //# sourceMappingURL=expo.js.map
@@ -0,0 +1,87 @@
1
+ import { S as SourceRange, P as Program } from './program-ZWUAWy_9.cjs';
2
+
3
+ /**
4
+ * Read the JSON `arkadec` writes into a {@link Program}: `$param` placeholders,
5
+ * @scure opcode names, and one structured tapleaf per compiler leaf.
6
+ */
7
+
8
+ interface ArtifactParameter {
9
+ name: string;
10
+ type: string;
11
+ }
12
+ interface ArtifactStruct {
13
+ name: string;
14
+ fields: ArtifactParameter[];
15
+ }
16
+ interface ArtifactWitnessElement {
17
+ name: string;
18
+ type: string;
19
+ encoding?: string;
20
+ injected?: boolean;
21
+ }
22
+ interface ArtifactLeaf {
23
+ name: string;
24
+ witness?: ArtifactWitnessElement[];
25
+ asm: string[];
26
+ }
27
+ interface ArtifactCovenant {
28
+ inputs: ArtifactParameter[];
29
+ asm: string[];
30
+ }
31
+ interface ArtifactGroup {
32
+ name: string;
33
+ arkade?: ArtifactCovenant;
34
+ leaves: ArtifactLeaf[];
35
+ }
36
+ interface ContractArtifact {
37
+ formatVersion?: number;
38
+ contractName: string;
39
+ constructorInputs: ArtifactParameter[];
40
+ structs?: ArtifactStruct[];
41
+ functions: ArtifactGroup[];
42
+ /** The `codeHash` of each contract this one instantiates with `new`, by contract name. */
43
+ contracts?: Record<string, string>;
44
+ /** `sha256:<hex>` of the fields that determine the scripts. The SDK recomputes it instead. */
45
+ codeHash?: string;
46
+ fingerprint?: string;
47
+ }
48
+ /** What {@link programFromArtifact} reads besides the artifact. */
49
+ interface ProgramFromArtifactOptions {
50
+ /** The build's debug file: each covenant segment then carries its `sourceMap`. */
51
+ debug?: ContractDebugInfo;
52
+ /**
53
+ * The artifact of every contract instantiated with `new`, directly or through another one, in
54
+ * any order. Each must match the `codeHash` its parent pins in `contracts`. That hash covers the
55
+ * fields in arkadec's order, so an artifact re-serialized with reordered keys (as Postgres
56
+ * `jsonb` does) is refused: keep the JSON arkadec wrote. At most 256 instantiations, with
57
+ * programs of at most 1,048,576 characters in all, are read, counting a child once per path
58
+ * that reaches it.
59
+ */
60
+ contracts?: readonly ContractArtifact[];
61
+ }
62
+ /** The compiler's debug file: each covenant's source map, keyed by spend group. */
63
+ interface ContractDebugInfo {
64
+ formatVersion: number;
65
+ /** The {@link ContractArtifact.fingerprint} of the build that wrote it. */
66
+ artifactFingerprint?: string;
67
+ functions: Record<string, {
68
+ sourceMap: SourceRange[];
69
+ }>;
70
+ }
71
+ /** `true` when `value` is an arkadec artifact rather than a Program. */
72
+ declare function isContractArtifact(value: unknown): value is ContractArtifact;
73
+ /**
74
+ * Adds `server`, and one `bytes32` param per `<CONTRACT:Name(…)>` placeholder, which an
75
+ * `ArkadeContract` binds to that contract's witness program when it is built. Each `Name` needs its
76
+ * artifact in `options.contracts` and its pin in the artifact's own `contracts`, or this throws.
77
+ * With the build's `debug` file, passed bare or as `debug`, each covenant segment also carries its
78
+ * `sourceMap`.
79
+ *
80
+ * `<OPERATOR_KEY>` reads as `server` and `<OPERATOR_EXIT_DELAY>` as `SERVER_EXIT_DELAY`.
81
+ * `<OPERATOR_KEY:f>` reads as the server key followed by the emulator key tweaked by `f`'s Arkade
82
+ * Script, or the tweaked emulator key alone in a CSV leaf, until arkd and the emulator share one
83
+ * operator key.
84
+ */
85
+ declare function programFromArtifact(artifact: ContractArtifact, options?: ProgramFromArtifactOptions | ContractDebugInfo): Program;
86
+
87
+ export { type ContractArtifact as C, type ProgramFromArtifactOptions as P, type ContractDebugInfo as a, isContractArtifact as i, programFromArtifact as p };
@@ -0,0 +1,87 @@
1
+ import { S as SourceRange, P as Program } from './program-zdDO4cMt.js';
2
+
3
+ /**
4
+ * Read the JSON `arkadec` writes into a {@link Program}: `$param` placeholders,
5
+ * @scure opcode names, and one structured tapleaf per compiler leaf.
6
+ */
7
+
8
+ interface ArtifactParameter {
9
+ name: string;
10
+ type: string;
11
+ }
12
+ interface ArtifactStruct {
13
+ name: string;
14
+ fields: ArtifactParameter[];
15
+ }
16
+ interface ArtifactWitnessElement {
17
+ name: string;
18
+ type: string;
19
+ encoding?: string;
20
+ injected?: boolean;
21
+ }
22
+ interface ArtifactLeaf {
23
+ name: string;
24
+ witness?: ArtifactWitnessElement[];
25
+ asm: string[];
26
+ }
27
+ interface ArtifactCovenant {
28
+ inputs: ArtifactParameter[];
29
+ asm: string[];
30
+ }
31
+ interface ArtifactGroup {
32
+ name: string;
33
+ arkade?: ArtifactCovenant;
34
+ leaves: ArtifactLeaf[];
35
+ }
36
+ interface ContractArtifact {
37
+ formatVersion?: number;
38
+ contractName: string;
39
+ constructorInputs: ArtifactParameter[];
40
+ structs?: ArtifactStruct[];
41
+ functions: ArtifactGroup[];
42
+ /** The `codeHash` of each contract this one instantiates with `new`, by contract name. */
43
+ contracts?: Record<string, string>;
44
+ /** `sha256:<hex>` of the fields that determine the scripts. The SDK recomputes it instead. */
45
+ codeHash?: string;
46
+ fingerprint?: string;
47
+ }
48
+ /** What {@link programFromArtifact} reads besides the artifact. */
49
+ interface ProgramFromArtifactOptions {
50
+ /** The build's debug file: each covenant segment then carries its `sourceMap`. */
51
+ debug?: ContractDebugInfo;
52
+ /**
53
+ * The artifact of every contract instantiated with `new`, directly or through another one, in
54
+ * any order. Each must match the `codeHash` its parent pins in `contracts`. That hash covers the
55
+ * fields in arkadec's order, so an artifact re-serialized with reordered keys (as Postgres
56
+ * `jsonb` does) is refused: keep the JSON arkadec wrote. At most 256 instantiations, with
57
+ * programs of at most 1,048,576 characters in all, are read, counting a child once per path
58
+ * that reaches it.
59
+ */
60
+ contracts?: readonly ContractArtifact[];
61
+ }
62
+ /** The compiler's debug file: each covenant's source map, keyed by spend group. */
63
+ interface ContractDebugInfo {
64
+ formatVersion: number;
65
+ /** The {@link ContractArtifact.fingerprint} of the build that wrote it. */
66
+ artifactFingerprint?: string;
67
+ functions: Record<string, {
68
+ sourceMap: SourceRange[];
69
+ }>;
70
+ }
71
+ /** `true` when `value` is an arkadec artifact rather than a Program. */
72
+ declare function isContractArtifact(value: unknown): value is ContractArtifact;
73
+ /**
74
+ * Adds `server`, and one `bytes32` param per `<CONTRACT:Name(…)>` placeholder, which an
75
+ * `ArkadeContract` binds to that contract's witness program when it is built. Each `Name` needs its
76
+ * artifact in `options.contracts` and its pin in the artifact's own `contracts`, or this throws.
77
+ * With the build's `debug` file, passed bare or as `debug`, each covenant segment also carries its
78
+ * `sourceMap`.
79
+ *
80
+ * `<OPERATOR_KEY>` reads as `server` and `<OPERATOR_EXIT_DELAY>` as `SERVER_EXIT_DELAY`.
81
+ * `<OPERATOR_KEY:f>` reads as the server key followed by the emulator key tweaked by `f`'s Arkade
82
+ * Script, or the tweaked emulator key alone in a CSV leaf, until arkd and the emulator share one
83
+ * operator key.
84
+ */
85
+ declare function programFromArtifact(artifact: ContractArtifact, options?: ProgramFromArtifactOptions | ContractDebugInfo): Program;
86
+
87
+ export { type ContractArtifact as C, type ProgramFromArtifactOptions as P, type ContractDebugInfo as a, isContractArtifact as i, programFromArtifact as p };
@@ -1,4 +1,4 @@
1
- import { c as TaskQueue, b as TaskItem, d as TaskResult } from './taskRunner-BxOmg-O6.js';
1
+ import { c as TaskQueue, b as TaskItem, d as TaskResult } from './taskRunner-CoE4Xx9K.js';
2
2
 
3
3
  /**
4
4
  * Minimal async key-value storage interface.
@@ -1,4 +1,4 @@
1
- import { c as TaskQueue, b as TaskItem, d as TaskResult } from './taskRunner-D2itCXf6.cjs';
1
+ import { c as TaskQueue, b as TaskItem, d as TaskResult } from './taskRunner-DFG0BN_R.cjs';
2
2
 
3
3
  /**
4
4
  * Minimal async key-value storage interface.
@@ -1,7 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var chunk6WPP4UGN_cjs = require('./chunk-6WPP4UGN.cjs');
4
- var chunkHS7TKVOZ_cjs = require('./chunk-HS7TKVOZ.cjs');
3
+ var chunkCMFRCBZW_cjs = require('./chunk-CMFRCBZW.cjs');
4
+ var chunkFKHUXSYW_cjs = require('./chunk-FKHUXSYW.cjs');
5
5
 
6
6
  // src/worker/expo/taskRunner.ts
7
7
  async function runTasks(queue, processors, deps) {
@@ -33,7 +33,7 @@ async function runTasks(queue, processors, deps) {
33
33
  }
34
34
  const result = {
35
35
  ...partial,
36
- id: chunk6WPP4UGN_cjs.getRandomId(),
36
+ id: chunkCMFRCBZW_cjs.getRandomId(),
37
37
  executedAt: Date.now()
38
38
  };
39
39
  await queue.pushResult(result);
@@ -45,7 +45,7 @@ async function runTasks(queue, processors, deps) {
45
45
  function createTaskDependencies(options) {
46
46
  return {
47
47
  ...options,
48
- extendVtxo: (vtxo, contract) => chunk6WPP4UGN_cjs.extendVirtualCoinForContract(vtxo, contract)
48
+ extendVtxo: (vtxo, contract) => chunkCMFRCBZW_cjs.extendVirtualCoinForContract(vtxo, contract)
49
49
  };
50
50
  }
51
51
 
@@ -55,15 +55,15 @@ var contractPollProcessor = {
55
55
  taskType: CONTRACT_POLL_TASK_TYPE,
56
56
  async execute(item, deps) {
57
57
  const { contractRepository, walletRepository, indexerProvider, extendVtxo } = deps;
58
- const contracts = await chunk6WPP4UGN_cjs.collectContracts(contractRepository, {
58
+ const contracts = await chunkCMFRCBZW_cjs.collectContracts(contractRepository, {
59
59
  watch: ["watched", "awaiting-funds"]
60
60
  });
61
61
  let contractsProcessed = 0;
62
62
  let vtxosSaved = 0;
63
63
  for (const contract of contracts) {
64
64
  const allVtxos = [];
65
- for await (const { vtxos } of chunkHS7TKVOZ_cjs.indexerPages(
66
- (pageIndex) => chunkHS7TKVOZ_cjs.getNormalizedVtxos(indexerProvider, {
65
+ for await (const { vtxos } of chunkFKHUXSYW_cjs.indexerPages(
66
+ (pageIndex) => chunkFKHUXSYW_cjs.getNormalizedVtxos(indexerProvider, {
67
67
  scripts: [contract.script],
68
68
  pageIndex,
69
69
  pageSize: 100
@@ -73,12 +73,12 @@ var contractPollProcessor = {
73
73
  allVtxos.push(extendVtxo(vtxo, contract));
74
74
  }
75
75
  }
76
- const filtered = chunk6WPP4UGN_cjs.warnAndFilterVtxosForScript(
76
+ const filtered = chunkCMFRCBZW_cjs.warnAndFilterVtxosForScript(
77
77
  allVtxos,
78
78
  contract.script,
79
79
  "contractPollProcessor"
80
80
  );
81
- await chunk6WPP4UGN_cjs.saveVtxosForContract(walletRepository, contract, filtered);
81
+ await chunkCMFRCBZW_cjs.saveVtxosForContract(walletRepository, contract, filtered);
82
82
  vtxosSaved += filtered.length;
83
83
  contractsProcessed++;
84
84
  }
@@ -95,5 +95,5 @@ exports.CONTRACT_POLL_TASK_TYPE = CONTRACT_POLL_TASK_TYPE;
95
95
  exports.contractPollProcessor = contractPollProcessor;
96
96
  exports.createTaskDependencies = createTaskDependencies;
97
97
  exports.runTasks = runTasks;
98
- //# sourceMappingURL=chunk-TYSUFG2K.cjs.map
99
- //# sourceMappingURL=chunk-TYSUFG2K.cjs.map
98
+ //# sourceMappingURL=chunk-35GRSVCZ.cjs.map
99
+ //# sourceMappingURL=chunk-35GRSVCZ.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/worker/expo/taskRunner.ts","../src/worker/expo/processors/contractPollProcessor.ts"],"names":["getRandomId","extendVirtualCoinForContract","collectContracts","indexerPages","getNormalizedVtxos","warnAndFilterVtxosForScript","saveVtxosForContract"],"mappings":";;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AAWC,6CAAA;AAAA,QACb,QAAA;AAAA,QACA,QAAA,CAAS,MAAA;AAAA,QACT;AAAA,OACJ;AACA,MAAA,MAAMC,sCAAA,CAAqB,gBAAA,EAAkB,QAAA,EAAU,QAAQ,CAAA;AAC/D,MAAA,UAAA,IAAc,QAAA,CAAS,MAAA;AACvB,MAAA,kBAAA,EAAA;AAAA,IACJ;AAEA,IAAA,OAAO;AAAA,MACH,YAAY,IAAA,CAAK,EAAA;AAAA,MACjB,IAAA,EAAM,uBAAA;AAAA,MACN,MAAA,EAAQ,SAAA;AAAA,MACR,IAAA,EAAM,EAAE,kBAAA,EAAoB,UAAA;AAAW,KAC3C;AAAA,EACJ;AACJ","file":"chunk-TYSUFG2K.cjs","sourcesContent":["import type { TaskItem, TaskResult, TaskQueue } from \"./taskQueue\";\nimport type { WalletRepository } from \"../../repositories/walletRepository\";\nimport type { ContractRepository } from \"../../repositories/contractRepository\";\nimport type { IndexerProvider } from \"../../providers/indexer\";\nimport type { OperatorProvider } from \"../../providers/ark\";\nimport type { ExtendedVirtualCoin, VirtualCoin } from \"../../wallet\";\nimport type { Contract } from \"../../contracts/types\";\nimport { getRandomId, extendVirtualCoinForContract } from \"../../wallet/utils\";\n\n/**\n * Shared dependencies injected into every processor at runtime.\n *\n * `extendVtxo` requires the owning contract — processors must resolve each\n * vtxo's `script` to a known contract (via the contract repository) before\n * calling this. The strict signature prevents the footgun where a missing\n * contract silently falls back to the wallet's default tapscript.\n */\nexport interface TaskDependencies {\n walletRepository: WalletRepository;\n contractRepository: ContractRepository;\n indexerProvider: IndexerProvider;\n arkProvider: OperatorProvider;\n extendVtxo: (vtxo: VirtualCoin, contract: Contract) => ExtendedVirtualCoin;\n}\n\n/**\n * A stateless unit that handles one type of task item.\n *\n * Processors must not keep in-memory state across invocations —\n * all coordination lives in the @see TaskQueue and repositories.\n *\n * The `TDeps` parameter defaults to @see TaskDependencies but\n * can be overridden for domain-specific processors (e.g. swap processing).\n */\nexport interface TaskProcessor<TDeps = TaskDependencies> {\n readonly taskType: string;\n execute(item: TaskItem, deps: TDeps): Promise<Omit<TaskResult, \"id\" | \"executedAt\">>;\n}\n\n/**\n * Run all pending tasks from the queue through matching processors.\n *\n * For each task in the inbox:\n * 1. Find the processor whose `taskType` matches `task.type`.\n * 2. Execute it, producing a @see TaskResult.\n * 3. Push the result to the outbox and remove the task from the inbox.\n *\n * Tasks with no matching processor produce a `\"noop\"` result.\n * Processor errors produce a `\"failed\"` result with the error message.\n */\nexport async function runTasks<TDeps = TaskDependencies>(\n queue: TaskQueue,\n processors: TaskProcessor<TDeps>[],\n deps: TDeps,\n): Promise<TaskResult[]> {\n const tasks = await queue.getTasks();\n const processorMap = new Map(processors.map((p) => [p.taskType, p]));\n const results: TaskResult[] = [];\n\n for (const task of tasks) {\n const processor = processorMap.get(task.type);\n\n let partial: Omit<TaskResult, \"id\" | \"executedAt\">;\n\n if (!processor) {\n partial = {\n taskItemId: task.id,\n type: task.type,\n status: \"noop\",\n };\n } else {\n try {\n partial = await processor.execute(task, deps);\n } catch (error) {\n partial = {\n taskItemId: task.id,\n type: task.type,\n status: \"failed\",\n data: {\n error: error instanceof Error ? error.message : String(error),\n },\n };\n }\n }\n\n const result: TaskResult = {\n ...partial,\n id: getRandomId(),\n executedAt: Date.now(),\n };\n\n await queue.pushResult(result);\n await queue.removeTask(task.id);\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Options for @see createTaskDependencies.\n */\nexport interface CreateTaskDependenciesOptions {\n walletRepository: WalletRepository;\n contractRepository: ContractRepository;\n indexerProvider: IndexerProvider;\n arkProvider: OperatorProvider;\n}\n\n/**\n * Build the @see TaskDependencies needed by task processors\n * (e.g. `src/worker/expo/processors/contractPollProcessor.ts`)\n *\n * This is the same construction that `defineExpoBackgroundTask` does\n * internally, extracted so that consumers with custom schedulers\n * (e.g. bare React Native with `react-native-background-fetch`)\n * can build deps without depending on Expo.\n */\nexport function createTaskDependencies(options: CreateTaskDependenciesOptions): TaskDependencies {\n return {\n ...options,\n extendVtxo: (vtxo: VirtualCoin, contract: Contract) =>\n extendVirtualCoinForContract(vtxo, contract),\n };\n}\n","import { collectContracts } from \"../../../repositories/contractRepository\";\nimport type { TaskItem, TaskResult } from \"../taskQueue\";\nimport type { TaskProcessor, TaskDependencies } from \"../taskRunner\";\nimport type { ExtendedVirtualCoin } from \"../../../wallet\";\nimport { getNormalizedVtxos, indexerPages } from \"../../../wallet/vtxo\";\nimport {\n warnAndFilterVtxosForScript,\n saveVtxosForContract,\n} from \"../../../contracts/vtxoOwnership\";\n\nexport const CONTRACT_POLL_TASK_TYPE = \"contract-poll\";\n\n/**\n * Polls the indexer for the latest VTXO state of every contract and\n * persists the results to the wallet repository.\n *\n * Replicates the polling subset of @see ContractManager.initialize:\n * 1. Load every watched contract from the contract repository.\n * 2. Paginated fetch of every VTXO (including spent) from the indexer.\n * 3. Extend each VTXO with tapscript data.\n * 4. Save to the wallet repository.\n *\n * NOTE: the indexer query deliberately omits `spendableOnly`. Every\n * repository implements `saveVtxos` as an upsert with no batch delete,\n * so filtering to spendable-only would leave VTXOs that became spent\n * between polls marked as spendable forever. Fetching the full set lets\n * the upsert overwrite stale records with their latest state.\n */\nexport const contractPollProcessor: TaskProcessor = {\n taskType: CONTRACT_POLL_TASK_TYPE,\n\n async execute(\n item: TaskItem,\n deps: TaskDependencies,\n ): Promise<Omit<TaskResult, \"id\" | \"executedAt\">> {\n const { contractRepository, walletRepository, indexerProvider, extendVtxo } = deps;\n\n // Background channel, so it covers exactly what the watcher's\n // subscription covers: `retained` rows are kept for reads only.\n const contracts = await collectContracts(contractRepository, {\n watch: [\"watched\", \"awaiting-funds\"],\n });\n let contractsProcessed = 0;\n let vtxosSaved = 0;\n\n for (const contract of contracts) {\n const allVtxos: ExtendedVirtualCoin[] = [];\n for await (const { vtxos } of indexerPages((pageIndex) =>\n getNormalizedVtxos(indexerProvider, {\n scripts: [contract.script],\n pageIndex,\n pageSize: 100,\n }),\n )) {\n for (const vtxo of vtxos) {\n allVtxos.push(extendVtxo(vtxo, contract));\n }\n }\n\n // Skip wrong-script rows (legacy duplicates or indexer drift)\n // before persisting; the loop must keep going for the remaining\n // contracts even when one row is rejected.\n const filtered = warnAndFilterVtxosForScript(\n allVtxos,\n contract.script,\n \"contractPollProcessor\",\n );\n await saveVtxosForContract(walletRepository, contract, filtered);\n vtxosSaved += filtered.length;\n contractsProcessed++;\n }\n\n return {\n taskItemId: item.id,\n type: CONTRACT_POLL_TASK_TYPE,\n status: \"success\",\n data: { contractsProcessed, vtxosSaved },\n };\n },\n};\n"]}
1
+ {"version":3,"sources":["../src/worker/expo/taskRunner.ts","../src/worker/expo/processors/contractPollProcessor.ts"],"names":["getRandomId","extendVirtualCoinForContract","collectContracts","indexerPages","getNormalizedVtxos","warnAndFilterVtxosForScript","saveVtxosForContract"],"mappings":";;;;;;AAkDA,eAAsB,QAAA,CAClB,KAAA,EACA,UAAA,EACA,IAAA,EACqB;AACrB,EAAA,MAAM,KAAA,GAAQ,MAAM,KAAA,CAAM,QAAA,EAAS;AACnC,EAAA,MAAM,YAAA,GAAe,IAAI,GAAA,CAAI,UAAA,CAAW,GAAA,CAAI,CAAC,CAAA,KAAM,CAAC,CAAA,CAAE,QAAA,EAAU,CAAC,CAAC,CAAC,CAAA;AACnE,EAAA,MAAM,UAAwB,EAAC;AAE/B,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACtB,IAAA,MAAM,SAAA,GAAY,YAAA,CAAa,GAAA,CAAI,IAAA,CAAK,IAAI,CAAA;AAE5C,IAAA,IAAI,OAAA;AAEJ,IAAA,IAAI,CAAC,SAAA,EAAW;AACZ,MAAA,OAAA,GAAU;AAAA,QACN,YAAY,IAAA,CAAK,EAAA;AAAA,QACjB,MAAM,IAAA,CAAK,IAAA;AAAA,QACX,MAAA,EAAQ;AAAA,OACZ;AAAA,IACJ,CAAA,MAAO;AACH,MAAA,IAAI;AACA,QAAA,OAAA,GAAU,MAAM,SAAA,CAAU,OAAA,CAAQ,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;AACzB,IAAA,IAAI,UAAA,GAAa,CAAA;AAEjB,IAAA,KAAA,MAAW,YAAY,SAAA,EAAW;AAC9B,MAAA,MAAM,WAAkC,EAAC;AACzC,MAAA,WAAA,MAAiB,EAAE,OAAM,IAAKC,8BAAA;AAAA,QAAa,CAAC,SAAA,KACxCC,oCAAA,CAAmB,eAAA,EAAiB;AAAA,UAChC,OAAA,EAAS,CAAC,QAAA,CAAS,MAAM,CAAA;AAAA,UACzB,SAAA;AAAA,UACA,QAAA,EAAU;AAAA,SACb;AAAA,OACL,EAAG;AACC,QAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACtB,UAAA,QAAA,CAAS,IAAA,CAAK,UAAA,CAAW,IAAA,EAAM,QAAQ,CAAC,CAAA;AAAA,QAC5C;AAAA,MACJ;AAKA,MAAA,MAAM,QAAA,GAAWC,6CAAA;AAAA,QACb,QAAA;AAAA,QACA,QAAA,CAAS,MAAA;AAAA,QACT;AAAA,OACJ;AACA,MAAA,MAAMC,sCAAA,CAAqB,gBAAA,EAAkB,QAAA,EAAU,QAAQ,CAAA;AAC/D,MAAA,UAAA,IAAc,QAAA,CAAS,MAAA;AACvB,MAAA,kBAAA,EAAA;AAAA,IACJ;AAEA,IAAA,OAAO;AAAA,MACH,YAAY,IAAA,CAAK,EAAA;AAAA,MACjB,IAAA,EAAM,uBAAA;AAAA,MACN,MAAA,EAAQ,SAAA;AAAA,MACR,IAAA,EAAM,EAAE,kBAAA,EAAoB,UAAA;AAAW,KAC3C;AAAA,EACJ;AACJ","file":"chunk-35GRSVCZ.cjs","sourcesContent":["import type { TaskItem, TaskResult, TaskQueue } from \"./taskQueue\";\nimport type { WalletRepository } from \"../../repositories/walletRepository\";\nimport type { ContractRepository } from \"../../repositories/contractRepository\";\nimport type { IndexerProvider } from \"../../providers/indexer\";\nimport type { OperatorProvider } from \"../../providers/ark\";\nimport type { ExtendedVirtualCoin, VirtualCoin } from \"../../wallet\";\nimport type { Contract } from \"../../contracts/types\";\nimport { getRandomId, extendVirtualCoinForContract } from \"../../wallet/utils\";\n\n/**\n * Shared dependencies injected into every processor at runtime.\n *\n * `extendVtxo` requires the owning contract — processors must resolve each\n * vtxo's `script` to a known contract (via the contract repository) before\n * calling this. The strict signature prevents the footgun where a missing\n * contract silently falls back to the wallet's default tapscript.\n */\nexport interface TaskDependencies {\n walletRepository: WalletRepository;\n contractRepository: ContractRepository;\n indexerProvider: IndexerProvider;\n arkProvider: OperatorProvider;\n extendVtxo: (vtxo: VirtualCoin, contract: Contract) => ExtendedVirtualCoin;\n}\n\n/**\n * A stateless unit that handles one type of task item.\n *\n * Processors must not keep in-memory state across invocations —\n * all coordination lives in the @see TaskQueue and repositories.\n *\n * The `TDeps` parameter defaults to @see TaskDependencies but\n * can be overridden for domain-specific processors (e.g. swap processing).\n */\nexport interface TaskProcessor<TDeps = TaskDependencies> {\n readonly taskType: string;\n execute(item: TaskItem, deps: TDeps): Promise<Omit<TaskResult, \"id\" | \"executedAt\">>;\n}\n\n/**\n * Run all pending tasks from the queue through matching processors.\n *\n * For each task in the inbox:\n * 1. Find the processor whose `taskType` matches `task.type`.\n * 2. Execute it, producing a @see TaskResult.\n * 3. Push the result to the outbox and remove the task from the inbox.\n *\n * Tasks with no matching processor produce a `\"noop\"` result.\n * Processor errors produce a `\"failed\"` result with the error message.\n */\nexport async function runTasks<TDeps = TaskDependencies>(\n queue: TaskQueue,\n processors: TaskProcessor<TDeps>[],\n deps: TDeps,\n): Promise<TaskResult[]> {\n const tasks = await queue.getTasks();\n const processorMap = new Map(processors.map((p) => [p.taskType, p]));\n const results: TaskResult[] = [];\n\n for (const task of tasks) {\n const processor = processorMap.get(task.type);\n\n let partial: Omit<TaskResult, \"id\" | \"executedAt\">;\n\n if (!processor) {\n partial = {\n taskItemId: task.id,\n type: task.type,\n status: \"noop\",\n };\n } else {\n try {\n partial = await processor.execute(task, deps);\n } catch (error) {\n partial = {\n taskItemId: task.id,\n type: task.type,\n status: \"failed\",\n data: {\n error: error instanceof Error ? error.message : String(error),\n },\n };\n }\n }\n\n const result: TaskResult = {\n ...partial,\n id: getRandomId(),\n executedAt: Date.now(),\n };\n\n await queue.pushResult(result);\n await queue.removeTask(task.id);\n results.push(result);\n }\n\n return results;\n}\n\n/**\n * Options for @see createTaskDependencies.\n */\nexport interface CreateTaskDependenciesOptions {\n walletRepository: WalletRepository;\n contractRepository: ContractRepository;\n indexerProvider: IndexerProvider;\n arkProvider: OperatorProvider;\n}\n\n/**\n * Build the @see TaskDependencies needed by task processors\n * (e.g. `src/worker/expo/processors/contractPollProcessor.ts`)\n *\n * This is the same construction that `defineExpoBackgroundTask` does\n * internally, extracted so that consumers with custom schedulers\n * (e.g. bare React Native with `react-native-background-fetch`)\n * can build deps without depending on Expo.\n */\nexport function createTaskDependencies(options: CreateTaskDependenciesOptions): TaskDependencies {\n return {\n ...options,\n extendVtxo: (vtxo: VirtualCoin, contract: Contract) =>\n extendVirtualCoinForContract(vtxo, contract),\n };\n}\n","import { collectContracts } from \"../../../repositories/contractRepository\";\nimport type { TaskItem, TaskResult } from \"../taskQueue\";\nimport type { TaskProcessor, TaskDependencies } from \"../taskRunner\";\nimport type { ExtendedVirtualCoin } from \"../../../wallet\";\nimport { getNormalizedVtxos, indexerPages } from \"../../../wallet/vtxo\";\nimport {\n warnAndFilterVtxosForScript,\n saveVtxosForContract,\n} from \"../../../contracts/vtxoOwnership\";\n\nexport const CONTRACT_POLL_TASK_TYPE = \"contract-poll\";\n\n/**\n * Polls the indexer for the latest VTXO state of every contract and\n * persists the results to the wallet repository.\n *\n * Replicates the polling subset of @see ContractManager.initialize:\n * 1. Load every watched contract from the contract repository.\n * 2. Paginated fetch of every VTXO (including spent) from the indexer.\n * 3. Extend each VTXO with tapscript data.\n * 4. Save to the wallet repository.\n *\n * NOTE: the indexer query deliberately omits `spendableOnly`. Every\n * repository implements `saveVtxos` as an upsert with no batch delete,\n * so filtering to spendable-only would leave VTXOs that became spent\n * between polls marked as spendable forever. Fetching the full set lets\n * the upsert overwrite stale records with their latest state.\n */\nexport const contractPollProcessor: TaskProcessor = {\n taskType: CONTRACT_POLL_TASK_TYPE,\n\n async execute(\n item: TaskItem,\n deps: TaskDependencies,\n ): Promise<Omit<TaskResult, \"id\" | \"executedAt\">> {\n const { contractRepository, walletRepository, indexerProvider, extendVtxo } = deps;\n\n // Background channel, so it covers exactly what the watcher's\n // subscription covers: `retained` rows are kept for reads only.\n const contracts = await collectContracts(contractRepository, {\n watch: [\"watched\", \"awaiting-funds\"],\n });\n let contractsProcessed = 0;\n let vtxosSaved = 0;\n\n for (const contract of contracts) {\n const allVtxos: ExtendedVirtualCoin[] = [];\n for await (const { vtxos } of indexerPages((pageIndex) =>\n getNormalizedVtxos(indexerProvider, {\n scripts: [contract.script],\n pageIndex,\n pageSize: 100,\n }),\n )) {\n for (const vtxo of vtxos) {\n allVtxos.push(extendVtxo(vtxo, contract));\n }\n }\n\n // Skip wrong-script rows (legacy duplicates or indexer drift)\n // before persisting; the loop must keep going for the remaining\n // contracts even when one row is rejected.\n const filtered = warnAndFilterVtxosForScript(\n allVtxos,\n contract.script,\n \"contractPollProcessor\",\n );\n await saveVtxosForContract(walletRepository, contract, filtered);\n vtxosSaved += filtered.length;\n contractsProcessed++;\n }\n\n return {\n taskItemId: item.id,\n type: CONTRACT_POLL_TASK_TYPE,\n status: \"success\",\n data: { contractsProcessed, vtxosSaved },\n };\n },\n};\n"]}