@6529-collections/stream-sdk 0.0.0-stage → 0.1.0-bootstrap.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +201 -0
  3. package/NOTICE +4 -0
  4. package/README.md +413 -2
  5. package/dist/actions/accounts.d.ts +58 -0
  6. package/dist/actions/accounts.js +73 -0
  7. package/dist/actions/content.d.ts +22 -0
  8. package/dist/actions/content.js +45 -0
  9. package/dist/actions/curated.d.ts +177 -0
  10. package/dist/actions/curated.js +279 -0
  11. package/dist/actions/editions.d.ts +100 -0
  12. package/dist/actions/editions.js +161 -0
  13. package/dist/actions/independent.d.ts +149 -0
  14. package/dist/actions/independent.js +274 -0
  15. package/dist/actions/money.d.ts +117 -0
  16. package/dist/actions/money.js +148 -0
  17. package/dist/actions/record.d.ts +144 -0
  18. package/dist/actions/record.js +229 -0
  19. package/dist/actions/sale.d.ts +82 -0
  20. package/dist/actions/sale.js +113 -0
  21. package/dist/actions/shared.d.ts +40 -0
  22. package/dist/actions/shared.js +70 -0
  23. package/dist/actions/vault.d.ts +58 -0
  24. package/dist/actions/vault.js +94 -0
  25. package/dist/constants.d.ts +130 -0
  26. package/dist/constants.js +65 -0
  27. package/dist/display.d.ts +31 -0
  28. package/dist/display.js +28 -0
  29. package/dist/encoding.d.ts +110 -0
  30. package/dist/encoding.js +138 -0
  31. package/dist/errors.d.ts +76 -0
  32. package/dist/errors.js +66 -0
  33. package/dist/files/fetch.d.ts +85 -0
  34. package/dist/files/fetch.js +208 -0
  35. package/dist/files/verify.d.ts +36 -0
  36. package/dist/files/verify.js +125 -0
  37. package/dist/generated/abis/AccessManager.d.ts +1125 -0
  38. package/dist/generated/abis/AccessManager.js +1471 -0
  39. package/dist/generated/abis/Accounts.d.ts +1568 -0
  40. package/dist/generated/abis/Accounts.js +2049 -0
  41. package/dist/generated/abis/ClaimRouter.d.ts +343 -0
  42. package/dist/generated/abis/ClaimRouter.js +452 -0
  43. package/dist/generated/abis/ConsolidationAdapter.d.ts +97 -0
  44. package/dist/generated/abis/ConsolidationAdapter.js +133 -0
  45. package/dist/generated/abis/ContentStore.d.ts +812 -0
  46. package/dist/generated/abis/ContentStore.js +1073 -0
  47. package/dist/generated/abis/EconomicsResolver.d.ts +586 -0
  48. package/dist/generated/abis/EconomicsResolver.js +769 -0
  49. package/dist/generated/abis/Eip712CurationVerifier.d.ts +304 -0
  50. package/dist/generated/abis/Eip712CurationVerifier.js +406 -0
  51. package/dist/generated/abis/EnglishAuction.d.ts +1435 -0
  52. package/dist/generated/abis/EnglishAuction.js +1865 -0
  53. package/dist/generated/abis/GovernedVault.d.ts +468 -0
  54. package/dist/generated/abis/GovernedVault.js +617 -0
  55. package/dist/generated/abis/IndependentEditionAuction.d.ts +2373 -0
  56. package/dist/generated/abis/IndependentEditionAuction.js +3076 -0
  57. package/dist/generated/abis/IndependentStream6529.d.ts +1408 -0
  58. package/dist/generated/abis/IndependentStream6529.js +1834 -0
  59. package/dist/generated/abis/IndependentStreamDeployer.d.ts +141 -0
  60. package/dist/generated/abis/IndependentStreamDeployer.js +188 -0
  61. package/dist/generated/abis/IndependentStreamEditions6529.d.ts +963 -0
  62. package/dist/generated/abis/IndependentStreamEditions6529.js +1253 -0
  63. package/dist/generated/abis/IndependentStreamRegistry.d.ts +1351 -0
  64. package/dist/generated/abis/IndependentStreamRegistry.js +1755 -0
  65. package/dist/generated/abis/PackageRegistry.d.ts +1205 -0
  66. package/dist/generated/abis/PackageRegistry.js +1573 -0
  67. package/dist/generated/abis/RevenueEscrow.d.ts +626 -0
  68. package/dist/generated/abis/RevenueEscrow.js +820 -0
  69. package/dist/generated/abis/SaleStarter.d.ts +48 -0
  70. package/dist/generated/abis/SaleStarter.js +67 -0
  71. package/dist/generated/abis/SepoliaOpenGate.d.ts +317 -0
  72. package/dist/generated/abis/SepoliaOpenGate.js +419 -0
  73. package/dist/generated/abis/SplitLedger.d.ts +1097 -0
  74. package/dist/generated/abis/SplitLedger.js +1438 -0
  75. package/dist/generated/abis/StatementLog.d.ts +958 -0
  76. package/dist/generated/abis/StatementLog.js +1248 -0
  77. package/dist/generated/abis/Stream6529.d.ts +1490 -0
  78. package/dist/generated/abis/Stream6529.js +1941 -0
  79. package/dist/generated/abis/StreamDirectory6529.d.ts +355 -0
  80. package/dist/generated/abis/StreamDirectory6529.js +468 -0
  81. package/dist/generated/abis/StreamEditions6529.d.ts +1240 -0
  82. package/dist/generated/abis/StreamEditions6529.js +1614 -0
  83. package/dist/generated/abis/StreamTerms.d.ts +312 -0
  84. package/dist/generated/abis/StreamTerms.js +409 -0
  85. package/dist/generated/abis/StreamWorkFacts6529.d.ts +810 -0
  86. package/dist/generated/abis/StreamWorkFacts6529.js +1049 -0
  87. package/dist/generated/abis/UniformEditionAuction.d.ts +2372 -0
  88. package/dist/generated/abis/UniformEditionAuction.js +3074 -0
  89. package/dist/generated/abis/WorkDelivery.d.ts +605 -0
  90. package/dist/generated/abis/WorkDelivery.js +786 -0
  91. package/dist/generated/abis/WorkRules.d.ts +1154 -0
  92. package/dist/generated/abis/WorkRules.js +1501 -0
  93. package/dist/generated/abis/index.d.ts +28 -0
  94. package/dist/generated/abis/index.js +31 -0
  95. package/dist/generated/instances.d.ts +7 -0
  96. package/dist/generated/instances.js +9 -0
  97. package/dist/generated/sepoliaR10.d.ts +1391 -0
  98. package/dist/generated/sepoliaR10.js +1545 -0
  99. package/dist/hashing/content.d.ts +42 -0
  100. package/dist/hashing/content.js +54 -0
  101. package/dist/hashing/ids.d.ts +67 -0
  102. package/dist/hashing/ids.js +73 -0
  103. package/dist/hashing/items.d.ts +30 -0
  104. package/dist/hashing/items.js +44 -0
  105. package/dist/hashing/packages.d.ts +35 -0
  106. package/dist/hashing/packages.js +76 -0
  107. package/dist/hashing/vault.d.ts +17 -0
  108. package/dist/hashing/vault.js +37 -0
  109. package/dist/hashing/workState.d.ts +31 -0
  110. package/dist/hashing/workState.js +37 -0
  111. package/dist/index.d.ts +44 -0
  112. package/dist/index.js +47 -0
  113. package/dist/instance.d.ts +236 -0
  114. package/dist/instance.js +99 -0
  115. package/dist/items.d.ts +85 -0
  116. package/dist/items.js +144 -0
  117. package/dist/reads/accounts.d.ts +86 -0
  118. package/dist/reads/accounts.js +121 -0
  119. package/dist/reads/chain.d.ts +54 -0
  120. package/dist/reads/chain.js +133 -0
  121. package/dist/reads/creation.d.ts +139 -0
  122. package/dist/reads/creation.js +256 -0
  123. package/dist/reads/editionSale.d.ts +120 -0
  124. package/dist/reads/editionSale.js +182 -0
  125. package/dist/reads/metadata.d.ts +195 -0
  126. package/dist/reads/metadata.js +191 -0
  127. package/dist/reads/money.d.ts +51 -0
  128. package/dist/reads/money.js +68 -0
  129. package/dist/reads/network.d.ts +137 -0
  130. package/dist/reads/network.js +157 -0
  131. package/dist/reads/sale.d.ts +94 -0
  132. package/dist/reads/sale.js +133 -0
  133. package/dist/reads/vault.d.ts +47 -0
  134. package/dist/reads/vault.js +75 -0
  135. package/dist/reads/work.d.ts +293 -0
  136. package/dist/reads/work.js +338 -0
  137. package/dist/reads/workPage.d.ts +197 -0
  138. package/dist/reads/workPage.js +169 -0
  139. package/dist/signing/messages.d.ts +679 -0
  140. package/dist/signing/messages.js +397 -0
  141. package/dist/testing.d.ts +17 -0
  142. package/dist/testing.js +18 -0
  143. package/dist/types.d.ts +167 -0
  144. package/dist/types.js +14 -0
  145. package/docs/publishing.md +54 -0
  146. package/docs/reference.md +335 -0
  147. package/docs/using-from-a-site.md +175 -0
  148. package/package.json +93 -4
package/README.md CHANGED
@@ -1,3 +1,414 @@
1
- # Temporary Holding Version
1
+ # 6529 Stream SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The reference TypeScript library for 6529 Stream: how to read a work, show it, verify it and use
4
+ the contracts. It is built on [viem](https://viem.sh) and has no React, no Next.js and no
5
+ website code in it.
6
+
7
+ > **Status: first release, pre-audit, test network only.** The contracts this library targets
8
+ > are pre-audit and run on the Sepolia test network. The library has not been audited either.
9
+ > Nothing here claims an audit, production readiness or correctness. It refuses to run against
10
+ > a chain that is not a test network. It is not published to npm yet; the package is ready to
11
+ > be (see [`docs/publishing.md`](docs/publishing.md)).
12
+
13
+ ## What this is for
14
+
15
+ The 6529 Stream contracts live in
16
+ [6529-Collections/6529-stream](https://github.com/6529-Collections/6529-stream). A contract is only
17
+ as useful as how easily others can show and use its works correctly, so the code that does that
18
+ is published here, on its own. The 6529.io pages are one consumer of this library, the same as a
19
+ marketplace, a wallet or your own site would be.
20
+
21
+ It is also here to be reviewed. A wrong hash or a wrong signature in a frontend can hurt a user
22
+ as surely as a fault in a contract. Every read, action, hash and signed message names the
23
+ contract function it rests on, with a link to the source;
24
+ [`docs/reference.md`](docs/reference.md) lists them all.
25
+
26
+ ## Show a work in five minutes
27
+
28
+ Install the library and viem (Node 22 or later). Until it is on npm, install it from GitHub;
29
+ the install builds it.
30
+
31
+ ```sh
32
+ npm install github:6529-Collections/6529-stream-sdk viem
33
+ ```
34
+
35
+ Once it is published, it is `npm install @6529-collections/stream-sdk viem`: prebuilt ES
36
+ modules with type declarations, and no install script.
37
+
38
+ Save this as `work.mjs` and run `node work.mjs`:
39
+
40
+ ```js
41
+ import { createPublicClient, http } from "viem";
42
+ import { sepolia } from "viem/chains";
43
+ import { readWorkPage, sepoliaR10 } from "@6529-collections/stream-sdk";
44
+
45
+ // Name an RPC you trust (see "What verified means") that keeps the chain's old logs (see
46
+ // "The RPC provider you need"), and let viem batch the reads.
47
+ const client = createPublicClient({
48
+ chain: sepolia,
49
+ transport: http("https://sepolia.gateway.tenderly.co"),
50
+ batch: { multicall: true },
51
+ });
52
+
53
+ const page = await readWorkPage(client, sepoliaR10, { tokenId: 2n }); // the sample work: examples/sample.ts
54
+
55
+ console.log(page.record.parsed?.name, "by artist", page.work.artistId);
56
+ console.log("first sale:", page.work.firstSale, "| checks:", page.checks);
57
+ const art = page.files[0];
58
+ console.log(art.mimeType, art.check.status, art.bytes ? `${art.bytes.length} bytes, show as ${art.display.kind}` : "no bytes: do not show it as verified");
59
+ ```
60
+
61
+ Token 2 is "Tidal Lines", an edition master whose art is an SVG stored on chain. It verifies
62
+ in full: every check in `checks` is true, and the art's 10,229 bytes are fetched from the chain
63
+ and match the hash the token stores. Its 1/1 sold for 0.05 ETH and its edition sale is over, so
64
+ the page also shows a settled sale, an edition (1 copy minted, a sealed maximum of 1, a cap of
65
+ 5) and a seller vault the artist has drawn from. A file that cannot be fetched (token 1's, which
66
+ was registered and never stored) is reported as `unavailable`, with `checks.filesVerified`
67
+ false: the last line of the example prints that case too.
68
+
69
+ `readWorkPage` returns the work's facts, the item it was minted from, its files with their
70
+ bytes, its record, licence, royalty, vaults, sale and edition sale, with what was checked
71
+ (`checks`) and the contract and function behind each part (`sources`).
72
+
73
+ Or clone the repository and run the examples:
74
+
75
+ ```sh
76
+ git clone https://github.com/6529-Collections/6529-stream-sdk
77
+ cd 6529-stream-sdk
78
+ npm install
79
+ npm run example:read-work # a work, printed as text
80
+ npm run example:work-page # all of readWorkPage, as JSON
81
+ npm run example:network # how the instance is governed
82
+ npm run example:wallet -- status
83
+ ```
84
+
85
+ `SEPOLIA_RPC_URL` chooses the RPC for every example.
86
+
87
+ Building pages on it? [`docs/using-from-a-site.md`](docs/using-from-a-site.md) has the shape of
88
+ `readWorkPage`, the rules for showing files, and what to show a signer.
89
+
90
+ ## The RPC provider you need
91
+
92
+ Most reads of a work look up events: the transaction that minted it, the item it was minted
93
+ from, the edition's original cap, the bids and the settlement, the payees of a vault. The
94
+ library scans those events from the instance's start block (`instance.startBlock`) to the
95
+ latest block, so **the RPC provider must serve logs back to that block**.
96
+
97
+ Not every provider does. Some prune old history (EIP-4444) and answer a request for older
98
+ logs with error 4444, "pruned history unavailable". A public endpoint can be a mix of nodes,
99
+ so that the same request works one time and fails the next.
100
+
101
+ - The library asks again a few times, which is enough when only some of the provider's nodes
102
+ have pruned. If the provider still refuses, the read throws a `HistoryUnavailableError`
103
+ (`code: "HISTORY_UNAVAILABLE"`, with the block range refused), not a bare RPC error.
104
+ - Use a provider that keeps full log history: an archive node, or a full node that has not
105
+ pruned logs. With viem's `fallback` transport you can name a second one.
106
+ - Reads of current state use no logs and work on any provider: `readWork`, `readSale`,
107
+ `readEditionSale`, `readSplit`, `readWorkFiles`, the account reads and the file fetches.
108
+ - These scan events and need the history: `readWorkPage`, `readWorkItem`, `readWorkMint`,
109
+ `readSaleHistory`, `readEditionBids`, `readEdition` (for the original cap), `readWorks`,
110
+ `readStatements`, `readVault`, `readRoyaltyVault` and `readNetwork` (for scheduled calls).
111
+
112
+ The examples and the live tests use the list in `examples/rpc.ts`, or the URL (or URLs,
113
+ separated by commas) in `SEPOLIA_RPC_URL`.
114
+
115
+ ## What verified means
116
+
117
+ The library checks data against the hashes the contracts store. It does not check your RPC.
118
+
119
+ - **Proven locally, whatever the source:** a file's bytes match its file ID (every chunk's
120
+ keccak256, the length, the encoding, the MIME type and the SHA-256 all hash to the ID); an
121
+ item hashes to an item hash; a media list hashes to the item's media hash; a payee list
122
+ derives a vault address. A gateway (Arweave, IPFS) therefore needs no trust: a wrong answer
123
+ is detected and skipped.
124
+ - **Taken from your RPC:** which file IDs, item hash, owner, sale state and locators belong to
125
+ a token. An RPC that lies about those can present a different, self-consistent work, and
126
+ every check above still passes. Nothing short of a light client removes that.
127
+
128
+ So "verified" in this library means: consistent with what the chain holds, as your RPC reports
129
+ it. Use an RPC you trust, or read through two and compare.
130
+
131
+ **Verified is not safe to display.** The content store accepts any file type, including SVG,
132
+ HTML and JavaScript, and those can run code. `displayAdvice(mimeType)` (and `display` on every
133
+ file of `readWorkPage`) says how to show a file without giving it power over your page:
134
+
135
+ | Kind | Show it |
136
+ | --- | --- |
137
+ | `image` | In `<img>`, from a blob or data URL |
138
+ | `svg` | Only in `<img>`. Never inline it, never set it as `innerHTML`, never open it as a document from your own origin |
139
+ | `document` (HTML, scripts) | Only in an `<iframe sandbox="allow-scripts">`, without `allow-same-origin`, from a blob or `srcdoc` |
140
+ | `media` | In `<audio>` or `<video>` |
141
+ | `text` | As text, never as HTML |
142
+ | `download` | Offer it as a download |
143
+
144
+ Text from a record, a collection name, a statement URI or token metadata is whatever its author
145
+ wrote: escape it. The default gateways (`arweave.net`, `ipfs.io`, `dweb.link`) are public
146
+ services that see the address of whoever fetches; pass your own in `gateways` if that matters.
147
+
148
+ ## The parts
149
+
150
+ ### 1. Addresses, ABIs and protocol strings
151
+
152
+ [`src/generated/`](src/generated) is written by [`scripts/generate.mjs`](scripts/generate.mjs)
153
+ and never typed by hand.
154
+
155
+ - **Addresses, chain ID, start block, the network account** come from an instance's deployment
156
+ record and genesis file in the contracts repository. The current instance is Sepolia r10
157
+ ([`deployments/11155111/core-1795840548.json`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/deployments/11155111/core-1795840548.json)),
158
+ exported as `sepoliaR10`.
159
+ - **ABIs** are the ones of the commit the instance was deployed from (the record's
160
+ `sourceCommit`), each checked against the SHA-256 in that commit's `abi/manifest.json`. The
161
+ two merged edition-auction ABIs are checked entry by entry against the two manifest files
162
+ they are merged from.
163
+ - **The protocol's own strings** (`instance.protocol`): each signing contract's EIP-712 domain
164
+ name and version, the labels that start each hash, the module slots. They are read out of
165
+ the Solidity source at `sourceCommit`, found by identifier, so they belong to an instance
166
+ and the library hard-codes none of them. If a later instance is built from source that
167
+ spells them differently, generating it picks that up, and the tests compare each domain with
168
+ what the deployed contract reports about itself.
169
+ - **Every deployed contract and its source** (`instance.contracts`, `contractAt(instance, address)`): the address, the Solidity contract and its source file at `sourceCommit`, with a URL. A page can link every fact and action to the code without keeping its own list.
170
+ - **The governance table** (`instance.governance`): roles, their holders at genesis, the role
171
+ and wait of every governed function, the settings.
172
+ - **The chain guard.** Every read and every action checks that the client is on the instance's
173
+ chain (`assertInstanceChain`) before it sends anything or returns a result. A client with an
174
+ account is asked every time, because a browser wallet can switch network between two steps,
175
+ and the chain is named again when a transaction is sent, so viem refuses a send on another
176
+ chain. An instance that is not on a test network is refused outright, by the library and by
177
+ the generator. (A client without an account is asked once. If you build such a client on a
178
+ wallet's provider, give it an account or make a new client when the wallet switches.)
179
+
180
+ r10 has a test-only **open gate** (`sepoliaR10.openGate`, the `SepoliaOpenGate` contract). With
181
+ the gate open nothing is curated: every package anyone submits is approved. It exists so that
182
+ anyone can try the curated flow on Sepolia. It is not part of the protocol, and the functions
183
+ that use it say so in their names (`createCollectionThroughGate`, `registerPackageThroughGate`).
184
+
185
+ To generate again, from a checkout of the contracts repository (only its git history is read):
186
+
187
+ ```sh
188
+ node scripts/instances.mjs --contracts ../6529-stream # every instance in scripts/instances.mjs
189
+ node scripts/instances.mjs --contracts ../6529-stream --check # compare, write nothing
190
+ ```
191
+
192
+ A new instance is one entry in [`scripts/instances.mjs`](scripts/instances.mjs): its name,
193
+ record, flows file and commit. Its constant, the list `instances` (by name) and
194
+ `latestInstance` are generated too. For another deployment of the same code (a local chain, a
195
+ fresh test deployment from the same commit) no generation is needed:
196
+ `instanceFromRecord(sepoliaR10, record, { name, network })` takes every address from the
197
+ deployment record.
198
+
199
+ Each contract's ABI is its own module (`@6529-collections/stream-sdk/abis/Stream6529`), and
200
+ the package is marked free of side effects, so a bundler keeps only what a page uses.
201
+
202
+ CI regenerates everything from the contracts repository on every pull request and fails if
203
+ `src/generated/` differs. Every ABI, the test gate's included, is checked against the SHA-256
204
+ the contracts repository's own manifest gives for it.
205
+
206
+ ### 2. Hashing and signing
207
+
208
+ One implementation of every hash and every signed message the contracts check. The functions
209
+ whose result depends on the protocol's strings take them as their first argument
210
+ (`itemHash(instance.protocol, item)`), and signatures take their domain from
211
+ `signingDomains(instance)`.
212
+
213
+ | Function | What it is | Contract |
214
+ | --- | --- | --- |
215
+ | `itemHash`, `mediaHash`, `licenseKey` | An item's identity, the hash of its media list, a license's key | `StreamHashing` |
216
+ | `itemLeaf`, `packageTree`, `isPackageItem` | The package root every party signs, and each item's proof | `StreamHashing.leaf`, `isItem` |
217
+ | `manifestId`, `prepareFile` | A file's ID in the content store, from its chunks | `ContentStore.manifestId` |
218
+ | `saleId`, `statementSubjectKey` | Sale IDs and statement subjects | `EnglishAuction.saleIdOf`, `StatementLog.subjectKey` |
219
+ | `listingSubject`, `independentConsent` | What an Independent Stream consent covers | `IndependentStreamRegistry.listingSubject`, `Core.independentConsent` |
220
+ | `workStateHash` | The state a change to a work is signed for | `WorkRules.workStateHash` |
221
+ | `royaltyPayees` | The payee list of a work's royalty vault | `Splits.royaltyPayees` |
222
+ | `packageAcceptanceTypedData`, `moveToStreamTypedData` | A party accepts a package; the artist moves an item to Stream | `PackageRegistry` |
223
+ | `packageApprovalTypedData` | A curation signer approves a package | `Eip712CurationVerifier` |
224
+ | `artistRegistrationTypedData`, `consentTypedData`, `identityChangeTypedData`, `replacementAcceptanceTypedData` | Account messages | `Accounts` |
225
+ | `relicenseTypedData`, `royaltyRateChangeTypedData`, `renouncePowersTypedData` | Changes to a work | `WorkRules` |
226
+ | `releaseAuthorizationTypedData` | A payee lets someone relay a vault release | `SplitLedger` |
227
+ | `statementAuthorizationTypedData` | A signed statement | `StatementLog` |
228
+ | `encodeStreamMintRequest`, `encodeIndependentMint`, `encodeCuratedEditionOpen`, `encodeIndependentEditionOpen`, `encodeIndependent721Config`, `encodeIndependentEditionsConfig` | The byte encodings the contracts take as opaque `bytes` | see each function |
229
+
230
+ Each `...TypedData` function returns typed data for viem's `signTypedData` or `hashTypedData`.
231
+
232
+ **The package tree has one layout here:** OpenZeppelin's `StandardMerkleTree`, the one the
233
+ contracts' hashing library names. The leaves `keccak256(itemHash)` are sorted ascending and
234
+ each parent is the sorted-pair hash of its two children, so the order of the items does not
235
+ change the root. The contract accepts any sorted-pair tree, which means two tools can compute
236
+ different valid roots for the same items; a tool that wants the root this library computes
237
+ uses this layout. The tests check it against `@openzeppelin/merkle-tree`.
238
+
239
+ **How they are proven.** [`vectors/SdkVectors.t.sol`](vectors/SdkVectors.t.sol) is a Foundry
240
+ test that runs inside the contracts repository on the fully deployed test stack. It prints
241
+ every hash, digest and encoding the Solidity code produces. A signed message becomes a vector
242
+ only after the real contract accepted the signature, or its digest came from the contract's
243
+ own view function. The result is
244
+ [`test/vectors/sepolia-r10.json`](test/vectors/sepolia-r10.json), which records the commit it
245
+ came from. [`test/solidity-vectors.test.ts`](test/solidity-vectors.test.ts) checks the
246
+ TypeScript against every value: digests must be equal, and signatures made with the vectors'
247
+ test keys must be equal byte for byte. Producing the file again is one command
248
+ (`npm run vectors`); see [`vectors/README.md`](vectors/README.md). CI does not run Foundry, so
249
+ it trusts the committed file; the live suite below, which runs daily, compares the same
250
+ digests with the deployed contracts.
251
+
252
+ Two rules the library keeps, and asks of its users:
253
+
254
+ - **Do not sign a hash an RPC supplied.** Every hash that goes into a signature is computed
255
+ locally from values the signer can see.
256
+ - **Deadlines come from the chain's clock** (`chainDeadline`), never from the computer's. The
257
+ block time itself comes from the RPC, so it is refused when it is more than a day from the
258
+ computer's clock: a wrong answer cannot stretch a signature's life.
259
+ - **A vault's address in a signature is computed here** (`vaultAddress`): it follows from the
260
+ payee list alone, and the ledger's answer must agree.
261
+
262
+ ### 3. Reads
263
+
264
+ | Function | What it answers |
265
+ | --- | --- |
266
+ | `readWorkPage` | What a page about one work shows, in one call: the rows below for that work, its files and record fetched and verified, what was checked, and the source of each part. It does not include other works by the artist, statements, or artist names (the chain holds profile IDs, not names) |
267
+ | `readWork` | A work's permanent facts: item hash, artist, collection, kind, seed, owner, royalty, license, record, files, and how its first sale ended |
268
+ | `readWorkItem` | The full item it was minted from (parties, payees and shares, license, sale and edition terms), checked against the item hash the token stores |
269
+ | `readWorkMint` | The mint's facts: content hash, package root, seller vault, the start transaction |
270
+ | `readWorkFiles` | Each file's hash, size, type, whether it is on chain, and its Arweave and IPFS copies |
271
+ | `readWorks` | The works of a contract, a collection or an artist |
272
+ | `readTokenMetadata`, `readContractMetadata` | What marketplaces and wallets see: `tokenURI` and `contractURI`, parsed. Compare it with what you show |
273
+ | `parseRecord` | The known keys of a descriptive record, typed |
274
+ | `readEdition` | The edition of a master: copies minted, the sealed maximum (a ceiling, not a count), the creator's original cap (from the creation event), a holder's balance |
275
+ | `readSplit`, `readVault`, `readRoyaltyVault`, `readRoyalty` | The seller vault and what each payee can release; any vault by address; the royalty vault; a royalty for a price |
276
+ | `readEscrow`, `readNetworkVaults` | What the revenue escrow holds for an account; the network's fee vault and museum vault |
277
+ | `readSale`, `readSaleHistory` | The 1/1 auction: state, top bid, end time, minimum bid; its bids and settlement |
278
+ | `readEditionSale`, `readEditionBid`, `readEditionBids` | The edition auction: status, ladder, units per step, end times, result; bids and outcomes |
279
+ | `readWorkState` | A work's changeable state, its state hash, renounced powers, a pending finalize notice |
280
+ | `readStatements` | The statements made about a token or a package |
281
+ | `readArtistId`, `readAccountOf`, `readAccount`, `readIsWallet`, `readPendingChange`, `readIsConsolidated`, `readClaimable` | Accounts, consolidated wallets, and the ETH an account can withdraw |
282
+ | `readCollections`, `readGate`, `readPackageStatus`, `previewCuratedItem`, `readListingPlan`, `readMintedToken` | What a creation flow checks before it signs or sends |
283
+ | `readNetwork` | How the instance is governed (section 6) |
284
+
285
+ The same functions read an artist's own (Independent Stream) contract: pass its address as
286
+ `token`.
287
+
288
+ **Sale proceeds and royalties wait in two different vaults.** The price of the first sale goes
289
+ to the work's seller vault, where each payee takes its share (`releaseFromVault`). Royalties
290
+ from later sales go to a second vault, the royalty vault, which splits them between the network
291
+ and the seller vault. `readRoyaltyVault` shows it, `collectRoyalties` moves the seller vault's
292
+ part on (anyone may), and the payees then take their shares as before.
293
+
294
+ ### 4. Files
295
+
296
+ `fetchFile` and `fetchWorkFile` return a file only after its bytes were checked against its
297
+ file ID.
298
+
299
+ 1. The file's manifest is read from the content store and proven against the file ID: the
300
+ chunk hashes, length, encoding, MIME type and SHA-256 must hash to the ID (`readManifest`).
301
+ 2. From the chain, every chunk must match its keccak256 and the decoded file its SHA-256.
302
+ 3. From Arweave or IPFS, the bytes a gateway answers must have the manifest's SHA-256. A
303
+ gateway that answers anything else is skipped.
304
+
305
+ `fetchRecord` does the same for a work's descriptive record and parses it. At most 8 RPC calls
306
+ run at once for one file, so a large file does not flood a public RPC.
307
+
308
+ ### 5. Actions
309
+
310
+ Plain functions that take `{ public, wallet }` (two viem clients; they may be the same object)
311
+ and an instance. Each simulates its call first, so a call that would revert is never sent, then
312
+ sends it and waits for the receipt. Steps that are done already send nothing and say so.
313
+
314
+ | Flow | Functions |
315
+ | --- | --- |
316
+ | Store files | `prepareFile`, `storeFile`, `attestFileComplete` |
317
+ | Curated work through the test gate | `createCollectionThroughGate`, `buildItem`, `packageTree`, `registerPackageThroughGate`, `previewCuratedItem`, `acceptPackage`, `signMove`, `startCuratedSale`, `openRecord`, `openCuratedEditionSale` |
318
+ | Independent Stream | `deployIndependentContract`, `deployIndependentEditions`, `listIndependentContract`, `approveIndependentItem`, `signIndependentConsent`, `startIndependentSale`, `openIndependentEditionSale`, `openRecord` |
319
+ | The 1/1 sale | `placeBid`, `settleSale`, `claimAuctionCredit`, `claimDelivery`, `restartSale`, `settleOrRefund`, `withdrawBid`, `sendRescuedToMuseum` |
320
+ | The edition sale | `bidEdition`, `raiseEditionBid`, `settleEditionSale`, `claimEditionBid`, `claimEditionBidFor`, `claimEditionCredit`, `abandonEditionSale` |
321
+ | The vaults | `releaseFromVault`, `releaseFromVaultTo`, `collectRoyalties`, `claimMany` (batch, through the claim router), `signReleaseAuthorization` and `releaseSigned` (a payee lets someone else send its share), `flushEscrow`, `expireEscrow`, `forwardVault` |
322
+ | A work's record | `setRecord`, `finalizeRecord`, `addLocator` |
323
+ | Changes that need every party | `signRelicenseConsent`, `signRoyaltyRateConsent` (the network then makes the call), `signRenounce`, `renouncePowers` |
324
+ | Accounts | `stageIdentityChange`, `executeIdentityChange`, `cancelIdentityChange` (also contests a replacement), `signReplacementAcceptance` (the new root accepts a replacement by the network) |
325
+
326
+ A complete, runnable curated flow (store the files, register, accept, start, publish the
327
+ record) is in [`examples/wallet.ts`](examples/wallet.ts), in the `create` command. Works by
328
+ several parties are built with `buildItem`'s `collaborators` and `payees`; every party accepts
329
+ the package with `acceptPackage`, and each takes its share from the vault itself.
330
+
331
+ What the actions are careful about:
332
+
333
+ - **An item is checked before anyone signs for it.** An item that breaks a rule of the
334
+ registry (payees out of order, a zero share, a payee who is not a party) is approved and
335
+ accepted all the same and only refused when its sale starts, without a reason, after every
336
+ party has signed. `itemProblems` names the broken rule, `previewCuratedItem` also asks the
337
+ registry, and `buildItem`, `acceptPackage` (given the items) and `signMove` run them first.
338
+ - **"Already minted" compares the item hash.** A token contract mints a content hash once.
339
+ Finding the same image minted does not mean it is this work: another artist or collection
340
+ makes another item. `readMintedToken` adopts a token only when its item hash is this item's,
341
+ and otherwise stops with `CONTENT_ALREADY_MINTED`.
342
+ - **An artist ID is read, never assumed.** A new account's ID is its wallet's address as a
343
+ number, but an account keeps its ID when its root is replaced, and a wallet can act for an
344
+ account through consolidation without being its root. `readAccountOf` is the one function
345
+ that answers "whose wallet is this"; the contracts can only say it for a root today, so for
346
+ a consolidated wallet it checks the accounts the caller names. Deploying an artist's own
347
+ contract from a consolidated wallet needs the account's `artistId` passed in.
348
+ - **A listing is signed for the share that was shown.** `listIndependentContract` takes the
349
+ network's share the artist agreed to and signs nothing if the chain now says another.
350
+ - **"Take out" is offered to the right wallet.** A payee named by artist ID is paid at its
351
+ account's payout address, and only that address can send the release; the artist's other
352
+ wallets cannot. `readSplit` says for each payee where the money goes and who can send
353
+ (`paidTo`, `canRelease`), `releaseFromVault` refuses another caller with the reason,
354
+ and from another wallet the payout address signs (`signReleaseAuthorization`) and anyone
355
+ sends (`releaseSigned`).
356
+ - **ETH is sent only to the instance's own contracts.** The edition actions refuse an auction
357
+ address that is not one of the instance's two.
358
+
359
+ Errors thrown by the library are `StreamSdkError`s with a stable `code` (`StreamErrorCode`).
360
+ A revert of a contract comes through as viem's error, with the contract's own error name.
361
+
362
+ ### 6. The network
363
+
364
+ `readNetwork` is a read-only view of how an instance is governed right now: the network
365
+ account, the modules in force and any waiting to replace them, each role and who holds it, the
366
+ role every governed function needs and its wait, the settings, and the calls scheduled in the
367
+ access manager with the time each can run. What to look at comes from the instance's genesis
368
+ table (`instance.governance`, generated); each value is then read from the chain and flagged
369
+ if it differs. The access manager cannot list a role's members, so an account that was granted
370
+ a role after genesis is found only if you name it (`extraAccounts`).
371
+
372
+ ## How it is tested
373
+
374
+ | Command | What it checks | Needs |
375
+ | --- | --- | --- |
376
+ | `npm test` | Every hash, signature and encoding against the Solidity vectors; file verification; the guards; the item rules | nothing |
377
+ | `npm run test:live` | Each digest against the view functions of the deployed r10 contracts; a real work, its page, vaults, metadata and the governance | a Sepolia RPC |
378
+ | `npm run test:fork` | Every action, end to end, on a local fork of r10 with throwaway keys, and the wallet example run as a user would. The network's own calls (pause, royalty change, relicense, rescue) are made by impersonating the role holders the governance table names, scheduled and executed after their wait where the role has one | `anvil` and a Sepolia RPC |
379
+
380
+ CI runs, on every pull request: typecheck, lint, `npm test`, the reference-table check, the
381
+ build, a pack-and-install test from an empty project, the unit tests on the oldest viem the
382
+ package allows, and a regeneration of `src/generated/` from the contracts repository. The live
383
+ suite runs daily in its own workflow. The fork suite is run by hand.
384
+
385
+ ## What is not here yet
386
+
387
+ - No npm package: install from GitHub.
388
+ - The wallet example is a command-line script, not an app.
389
+ - Test networks only, and one instance at a time: Sepolia r10. The library carries one set of
390
+ ABIs and one set of protocol strings per instance, and r10 renamed the signing domains and
391
+ hash labels, so the earlier r9 instance is not in this release (it is in the git history,
392
+ at the commit before r10 was added).
393
+ - The curated flow goes through the test gate. On an instance without one, a curation signer
394
+ signs the approval (`packageApprovalTypedData` is here; the signer's tooling is not).
395
+ - No actions for calls only the network or a role holder can make (the relicense and royalty
396
+ calls themselves, pausing, statements, replacing an account's root, a file's preferred
397
+ locator). The consents and messages those calls need are here and tested, and `readNetwork`
398
+ shows who may make them.
399
+ - Only ETH: releases of other assets from a vault are possible (`asset`) but not exercised.
400
+ - Files registered with a digest other than SHA-256 are not checked, so they are refused.
401
+ - No indexer. Event reads scan from the instance's start block in windows on every call, which
402
+ suits a testnet's volumes.
403
+ - The source links in the doc comments point at one commit of the contracts repository. They
404
+ are updated when the library moves to a new instance.
405
+
406
+ ## Reporting a problem
407
+
408
+ Ordinary bugs: open an issue. Anything that could be exploited: do not open a public issue; see
409
+ [SECURITY.md](SECURITY.md).
410
+
411
+ ## License
412
+
413
+ [Apache License 2.0](LICENSE). See [NOTICE](NOTICE). Changes are listed in
414
+ [CHANGELOG.md](CHANGELOG.md).
@@ -0,0 +1,58 @@
1
+ import { type Client } from "viem";
2
+ import { type StreamInstance } from "../instance.js";
3
+ import type { ArtistIdentity } from "../types.js";
4
+ import { type Sent, type StreamClients } from "./shared.js";
5
+ /** A change to an account that is waiting to take effect. */
6
+ export interface PendingIdentityChange {
7
+ /** `"own"`: staged by the account itself. `"replacement"`: the network replaces the root. */
8
+ readonly kind: "own" | "replacement";
9
+ /** The identity after the change. */
10
+ readonly next: ArtistIdentity;
11
+ /** Unix seconds from which anyone may apply it with `executeIdentityChange`. */
12
+ readonly executableAt: number;
13
+ /** When a wallet of the account contested a replacement (Unix seconds), or 0. */
14
+ readonly contestedAt: number;
15
+ }
16
+ /**
17
+ * The change waiting on an account, or null. An account's own change (new payout address,
18
+ * root or profile) waits 2 days; a replacement of the root by the network waits 14 days and
19
+ * can be contested by the account.
20
+ *
21
+ * Contract: [`Accounts.pendingChange`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/identity/Accounts.sol).
22
+ */
23
+ export declare function readPendingChange(client: Client, instance: StreamInstance, artistId: bigint): Promise<PendingIdentityChange | null>;
24
+ /**
25
+ * Stages an account's own change: a new payout address, root or profile. A wallet of the
26
+ * account signs it (`IdentityChange`) and anyone relays it; here the connected wallet does
27
+ * both. It takes effect when someone calls `executeIdentityChange` at least 2 days later.
28
+ *
29
+ * `next` is the whole identity after the change: root, payout address and the two profile
30
+ * fields. All four are signed, so all four come from the caller: read the current ones with
31
+ * `readAccount`, show them, and pass them back with what changes. (Filling the unchanged
32
+ * fields in from an RPC here would let a wrong answer redirect the account's payouts inside a
33
+ * signature for something else.) A new root must already be a wallet of the account, and a
34
+ * payout address must be one the network allows (`Accounts.isPayoutAllowed`).
35
+ *
36
+ * Contract: [`Accounts.stageChange`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/identity/Accounts.sol);
37
+ * message `IdentityChange` (`identityChangeTypedData`) at the account's `changeNonce`.
38
+ */
39
+ export declare function stageIdentityChange(clients: StreamClients, instance: StreamInstance, args: {
40
+ readonly artistId: bigint;
41
+ readonly next: ArtistIdentity;
42
+ readonly lifetimeSeconds?: number;
43
+ }): Promise<Sent & {
44
+ next: ArtistIdentity;
45
+ }>;
46
+ /**
47
+ * Applies an account's due change. Anyone may, from `readPendingChange(...).executableAt`.
48
+ *
49
+ * Contract: [`Accounts.executeChange`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/identity/Accounts.sol).
50
+ */
51
+ export declare function executeIdentityChange(clients: StreamClients, instance: StreamInstance, artistId: bigint): Promise<Sent>;
52
+ /**
53
+ * A wallet of the account cancels the account's own pending change, or contests a pending
54
+ * replacement of its root by the network.
55
+ *
56
+ * Contract: [`Accounts.cancelChange`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/identity/Accounts.sol).
57
+ */
58
+ export declare function cancelIdentityChange(clients: StreamClients, instance: StreamInstance, artistId: bigint): Promise<Sent>;
@@ -0,0 +1,73 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { isAddressEqual, zeroAddress } from "viem";
3
+ import { readContract } from "viem/actions";
4
+ import { FlowError } from "../errors.js";
5
+ import { accountsAbi } from "../generated/abis/Accounts.js";
6
+ import { assertInstanceChain } from "../instance.js";
7
+ import { chainDeadline, orOnRevert } from "../reads/chain.js";
8
+ import { identityChangeTypedData, signingDomains, walletProof } from "../signing/messages.js";
9
+ import { assertReady, send, sign } from "./shared.js";
10
+ /**
11
+ * The change waiting on an account, or null. An account's own change (new payout address,
12
+ * root or profile) waits 2 days; a replacement of the root by the network waits 14 days and
13
+ * can be contested by the account.
14
+ *
15
+ * Contract: [`Accounts.pendingChange`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/identity/Accounts.sol).
16
+ */
17
+ export async function readPendingChange(client, instance, artistId) {
18
+ await assertInstanceChain(client, instance);
19
+ const pending = await orOnRevert(readContract(client, { address: instance.addresses.accounts, abi: accountsAbi, functionName: "pendingChange", args: [artistId] }), null);
20
+ if (!pending || pending.kind === 0)
21
+ return null;
22
+ return { kind: pending.kind === 1 ? "own" : "replacement", next: pending.next, executableAt: pending.executableAt, contestedAt: pending.contestedAt };
23
+ }
24
+ /**
25
+ * Stages an account's own change: a new payout address, root or profile. A wallet of the
26
+ * account signs it (`IdentityChange`) and anyone relays it; here the connected wallet does
27
+ * both. It takes effect when someone calls `executeIdentityChange` at least 2 days later.
28
+ *
29
+ * `next` is the whole identity after the change: root, payout address and the two profile
30
+ * fields. All four are signed, so all four come from the caller: read the current ones with
31
+ * `readAccount`, show them, and pass them back with what changes. (Filling the unchanged
32
+ * fields in from an RPC here would let a wrong answer redirect the account's payouts inside a
33
+ * signature for something else.) A new root must already be a wallet of the account, and a
34
+ * payout address must be one the network allows (`Accounts.isPayoutAllowed`).
35
+ *
36
+ * Contract: [`Accounts.stageChange`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/identity/Accounts.sol);
37
+ * message `IdentityChange` (`identityChangeTypedData`) at the account's `changeNonce`.
38
+ */
39
+ export async function stageIdentityChange(clients, instance, args) {
40
+ const account = await assertReady(clients, instance);
41
+ const accounts = { address: instance.addresses.accounts, abi: accountsAbi };
42
+ // The nonce is the account's counter: a wrong one makes the change fail, it cannot change what is signed for.
43
+ const nonce = await readContract(clients.public, { ...accounts, functionName: "changeNonce", args: [args.artistId] });
44
+ const next = { root: args.next.root, payout: args.next.payout, profileId: args.next.profileId, profileDocHash: args.next.profileDocHash };
45
+ if (isAddressEqual(next.payout, zeroAddress) || isAddressEqual(next.root, zeroAddress)) {
46
+ throw new FlowError("INVALID_INPUT", "An account's root and payout address are never zero.");
47
+ }
48
+ const deadline = await chainDeadline(clients.public, args.lifetimeSeconds ?? 3_600);
49
+ const signature = await sign(clients, identityChangeTypedData(signingDomains(instance).accounts, { artistId: args.artistId, next, nonce, deadline }));
50
+ const sent = await send(clients, instance, {
51
+ ...accounts,
52
+ functionName: "stageChange",
53
+ args: [args.artistId, next, deadline, walletProof(account, signature)],
54
+ });
55
+ return { ...sent, next };
56
+ }
57
+ /**
58
+ * Applies an account's due change. Anyone may, from `readPendingChange(...).executableAt`.
59
+ *
60
+ * Contract: [`Accounts.executeChange`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/identity/Accounts.sol).
61
+ */
62
+ export async function executeIdentityChange(clients, instance, artistId) {
63
+ return send(clients, instance, { address: instance.addresses.accounts, abi: accountsAbi, functionName: "executeChange", args: [artistId] });
64
+ }
65
+ /**
66
+ * A wallet of the account cancels the account's own pending change, or contests a pending
67
+ * replacement of its root by the network.
68
+ *
69
+ * Contract: [`Accounts.cancelChange`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/identity/Accounts.sol).
70
+ */
71
+ export async function cancelIdentityChange(clients, instance, artistId) {
72
+ return send(clients, instance, { address: instance.addresses.accounts, abi: accountsAbi, functionName: "cancelChange", args: [artistId] });
73
+ }
@@ -0,0 +1,22 @@
1
+ import { type Hex } from "viem";
2
+ import { type PreparedFile } from "../hashing/content.js";
3
+ import { type StreamInstance } from "../instance.js";
4
+ import { type StreamClients } from "./shared.js";
5
+ /**
6
+ * Stores a file in the content store: writes each chunk that is not there yet, then registers
7
+ * the manifest. Anyone may store any file, and a chunk or file stored already is skipped, so
8
+ * the call can be repeated after a failure. With `upload: false` only the manifest is
9
+ * registered: the file gets its ID, and its bytes are served from Arweave or IPFS.
10
+ *
11
+ * Every work needs its own primary bytes: a token contract mints a content hash once.
12
+ *
13
+ * Contract: [`ContentStore.writeChunk`, `registerManifest`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/content/ContentStore.sol).
14
+ *
15
+ * @returns the file ID (computed locally by `prepareFile`) and the transactions sent.
16
+ */
17
+ export declare function storeFile(clients: StreamClients, instance: StreamInstance, file: PreparedFile, options?: {
18
+ readonly upload?: boolean;
19
+ }): Promise<{
20
+ fileId: Hex;
21
+ transactions: Hex[];
22
+ }>;
@@ -0,0 +1,45 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { isAddressEqual, zeroAddress } from "viem";
3
+ import { readContract } from "viem/actions";
4
+ import { contentStoreAbi } from "../generated/abis/ContentStore.js";
5
+ import { chunkData } from "../hashing/content.js";
6
+ import {} from "../instance.js";
7
+ import { isFileRegistered } from "../reads/creation.js";
8
+ import { send } from "./shared.js";
9
+ /**
10
+ * Stores a file in the content store: writes each chunk that is not there yet, then registers
11
+ * the manifest. Anyone may store any file, and a chunk or file stored already is skipped, so
12
+ * the call can be repeated after a failure. With `upload: false` only the manifest is
13
+ * registered: the file gets its ID, and its bytes are served from Arweave or IPFS.
14
+ *
15
+ * Every work needs its own primary bytes: a token contract mints a content hash once.
16
+ *
17
+ * Contract: [`ContentStore.writeChunk`, `registerManifest`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/content/ContentStore.sol).
18
+ *
19
+ * @returns the file ID (computed locally by `prepareFile`) and the transactions sent.
20
+ */
21
+ export async function storeFile(clients, instance, file, options = {}) {
22
+ const store = { address: instance.addresses.contentStore, abi: contentStoreAbi };
23
+ const transactions = [];
24
+ if (options.upload !== false) {
25
+ for (const [index, chunk] of file.chunks.entries()) {
26
+ const chunkHash = file.chunkHashes[index];
27
+ if (chunkHash === undefined)
28
+ throw new Error("a prepared file has one hash per chunk");
29
+ const pointer = await readContract(clients.public, { ...store, functionName: "chunkPointer", args: [chunkHash] });
30
+ if (!isAddressEqual(pointer, zeroAddress))
31
+ continue;
32
+ const { hash } = await send(clients, instance, { ...store, functionName: "writeChunk", args: [chunkData(chunk)] });
33
+ transactions.push(hash);
34
+ }
35
+ }
36
+ if (!(await isFileRegistered(clients.public, instance, file.fileId))) {
37
+ const { hash } = await send(clients, instance, {
38
+ ...store,
39
+ functionName: "registerManifest",
40
+ args: [file.chunkHashes, file.length, file.encoding, file.mimeType, file.sha256],
41
+ });
42
+ transactions.push(hash);
43
+ }
44
+ return { fileId: file.fileId, transactions };
45
+ }