@6529-collections/stream-sdk 0.0.0-stage → 0.1.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
@@ -0,0 +1,157 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { decodeAbiParameters, getAbiItem, isAddressEqual, stringToHex, toFunctionSelector, zeroAddress } from "viem";
3
+ import { call, readContract } from "viem/actions";
4
+ import { PRODUCT } from "../constants.js";
5
+ import { accessManagerAbi } from "../generated/abis/AccessManager.js";
6
+ import { economicsResolverAbi } from "../generated/abis/EconomicsResolver.js";
7
+ import { englishAuctionAbi } from "../generated/abis/EnglishAuction.js";
8
+ import { stream6529Abi } from "../generated/abis/Stream6529.js";
9
+ import { streamDirectory6529Abi } from "../generated/abis/StreamDirectory6529.js";
10
+ import { uniformEditionAuctionAbi } from "../generated/abis/UniformEditionAuction.js";
11
+ import { assertInstanceChain } from "../instance.js";
12
+ import { chainTime, orOnRevert, scanEvents } from "./chain.js";
13
+ const OPERATION_SCHEDULED = /*#__PURE__*/ getAbiItem({ abi: accessManagerAbi, name: "OperationScheduled" });
14
+ /**
15
+ * A read-only view of how an instance is governed right now: the network account, the modules
16
+ * in force and any waiting to replace them, each role and who holds it, the role each governed
17
+ * function needs, the settings, and the calls scheduled in the access manager with the time
18
+ * each can run.
19
+ *
20
+ * The roles, functions and settings to look at come from the instance's genesis table
21
+ * (`instance.governance`); each is then read from the chain, and a value that differs from
22
+ * genesis is flagged (`unchanged: false`, `changed: true`). Role holders checked are the
23
+ * network, the genesis holders, the open gate if there is one, and any `extraAccounts`: the
24
+ * access manager cannot list a role's members, so an account granted a role later is found
25
+ * only if it is named.
26
+ *
27
+ * Contract: [`AccessManager`](https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/manager/AccessManager.sol)
28
+ * `hasRole`, `getTargetFunctionRole`, `getSchedule`, event `OperationScheduled`;
29
+ * [`StreamDirectory6529`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/core/StreamDirectory6529.sol)
30
+ * and the token contracts' `moduleOf`, `pendingModule`, `moduleDelay`;
31
+ * [`EconomicsResolver.economics`, `museum`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/economics/EconomicsResolver.sol).
32
+ */
33
+ export async function readNetwork(client, instance, options = {}) {
34
+ await assertInstanceChain(client, instance);
35
+ const a = instance.addresses;
36
+ const manager = { address: a.accessManager, abi: accessManagerAbi };
37
+ const now = await chainTime(client);
38
+ // --- modules
39
+ const holdersOfSlots = [
40
+ { on: "Stream6529", address: a.stream, kind: "token" },
41
+ { on: "StreamEditions6529", address: a.streamEditions, kind: "token" },
42
+ { on: "StreamDirectory6529", address: a.streamDirectory, kind: "directory" },
43
+ ];
44
+ const slotReads = holdersOfSlots.flatMap((holder) => instance.protocol.slots.filter((slot) => slot.on === holder.kind).map((slot) => ({ holder, slot, key: stringToHex(slot.name, { size: 32 }) })));
45
+ const modules = await Promise.all(slotReads.map(async ({ holder, slot, key }) => {
46
+ // The token contracts and the directory answer the same two functions.
47
+ const on = { address: holder.address, abi: streamDirectory6529Abi };
48
+ const [module, pending] = await Promise.all([
49
+ orOnRevert(readContract(client, { ...on, functionName: "moduleOf", args: [key] }), zeroAddress),
50
+ orOnRevert(readContract(client, { ...on, functionName: "pendingModule", args: [key] }), null),
51
+ ]);
52
+ return {
53
+ on: holder.on,
54
+ address: holder.address,
55
+ slot: slot.name,
56
+ what: slot.what,
57
+ module: isAddressEqual(module, zeroAddress) ? null : module,
58
+ pending: pending && !isAddressEqual(pending.module, zeroAddress) ? { module: pending.module, readyAt: pending.readyAt } : null,
59
+ };
60
+ }));
61
+ const moduleDelays = await Promise.all(holdersOfSlots.map(async (holder) => ({
62
+ on: holder.on,
63
+ seconds: await readContract(client, { address: holder.address, abi: streamDirectory6529Abi, functionName: "moduleDelay" }),
64
+ })));
65
+ // --- roles
66
+ const candidates = [
67
+ { account: instance.network, label: "The network" },
68
+ ...instance.governance.holdersAtGenesis.map((holder) => ({ account: holder.account, label: holder.label })),
69
+ ...(instance.openGate ? [{ account: instance.openGate, label: "The test-only open gate" }] : []),
70
+ ...(options.extraAccounts ?? []),
71
+ ].filter((candidate, index, all) => all.findIndex((other) => isAddressEqual(other.account, candidate.account)) === index);
72
+ const roles = await Promise.all(instance.governance.roles.map(async (role) => {
73
+ const id = BigInt(role.id);
74
+ const checked = await Promise.all(candidates.map(async (candidate) => {
75
+ const [isMember, executionDelay] = await readContract(client, { ...manager, functionName: "hasRole", args: [id, candidate.account] });
76
+ return { ...candidate, isMember, executionDelay };
77
+ }));
78
+ return { id, name: role.name, executionDelay: role.executionDelay, holders: checked.filter((holder) => holder.isMember) };
79
+ }));
80
+ // --- governed functions
81
+ const roleIds = new Map(instance.governance.roles.map((role) => [role.name, BigInt(role.id)]));
82
+ const functions = await Promise.all(instance.governance.functions.map(async (governed) => {
83
+ const roleIdNow = isAddressEqual(governed.address, a.accessManager)
84
+ ? (roleIds.get(governed.role) ?? 0n)
85
+ : await readContract(client, { ...manager, functionName: "getTargetFunctionRole", args: [governed.address, governed.selector] });
86
+ return {
87
+ contract: governed.contract,
88
+ address: governed.address,
89
+ signature: governed.signature,
90
+ role: governed.role,
91
+ delay: governed.delay,
92
+ roleIdNow,
93
+ unchanged: roleIdNow === roleIds.get(governed.role),
94
+ note: governed.note ?? null,
95
+ };
96
+ }));
97
+ // --- settings: each getter takes no arguments and answers one number
98
+ const settings = await Promise.all(instance.governance.settings.map(async (setting) => {
99
+ const answer = await orOnRevert(call(client, { to: setting.address, data: toFunctionSelector(setting.getter) }), null);
100
+ const value = answer?.data ? decodeAbiParameters([{ type: "uint256" }], answer.data)[0] : null;
101
+ const atGenesis = BigInt(setting.atGenesis);
102
+ return { contract: setting.contract, address: setting.address, getter: setting.getter, now: value, atGenesis, changed: value !== atGenesis };
103
+ }));
104
+ // --- scheduled calls: every OperationScheduled whose schedule is still set
105
+ const scheduledLogs = await scanEvents(client, instance, { address: a.accessManager, event: OPERATION_SCHEDULED }, options);
106
+ const lastById = new Map(scheduledLogs.map((log) => [log.args.operationId, log.args]));
107
+ const scheduled = (await Promise.all([...lastById.values()].map(async (operation) => {
108
+ const executableAt = await readContract(client, { ...manager, functionName: "getSchedule", args: [operation.operationId] });
109
+ if (executableAt === 0)
110
+ return null;
111
+ const governed = instance.governance.functions.find((entry) => isAddressEqual(entry.address, operation.target) && operation.data.toLowerCase().startsWith(entry.selector.toLowerCase()));
112
+ return {
113
+ operationId: operation.operationId,
114
+ caller: operation.caller,
115
+ target: operation.target,
116
+ what: governed ? `${governed.contract}.${governed.signature}` : null,
117
+ data: operation.data,
118
+ executableAt,
119
+ ready: BigInt(executableAt) <= now,
120
+ };
121
+ }))).filter((operation) => operation !== null);
122
+ // --- the rest
123
+ const [network, pendingNetwork, englishPaused, editionPaused, independentPaused, auctionMints, editionMints, museum, ...economics] = await Promise.all([
124
+ readContract(client, { ...manager, functionName: "network" }),
125
+ readContract(client, { ...manager, functionName: "pendingNetwork" }),
126
+ readContract(client, { address: a.englishAuction, abi: englishAuctionAbi, functionName: "paused" }),
127
+ readContract(client, { address: a.editionAuction, abi: uniformEditionAuctionAbi, functionName: "paused" }),
128
+ readContract(client, { address: a.independentEditionAuction, abi: uniformEditionAuctionAbi, functionName: "paused" }),
129
+ readContract(client, { address: a.stream, abi: stream6529Abi, functionName: "isMinter", args: [a.englishAuction] }),
130
+ readContract(client, { address: a.streamEditions, abi: stream6529Abi, functionName: "isMinter", args: [a.editionAuction] }),
131
+ readContract(client, { address: a.economics, abi: economicsResolverAbi, functionName: "museum" }),
132
+ ...["STREAM", "EDITIONS", "INDEPENDENT"].map((product) => readContract(client, { address: a.economics, abi: economicsResolverAbi, functionName: "economics", args: [PRODUCT[product]] })),
133
+ ]);
134
+ const products = ["stream", "editions", "independent"];
135
+ return {
136
+ network,
137
+ pendingNetwork: isAddressEqual(pendingNetwork, zeroAddress) ? null : pendingNetwork,
138
+ networkUnchanged: isAddressEqual(network, instance.network),
139
+ accessManager: a.accessManager,
140
+ modules,
141
+ moduleDelays,
142
+ roles,
143
+ functions,
144
+ settings,
145
+ scheduled,
146
+ paused: { englishAuction: englishPaused, editionAuction: editionPaused, independentEditionAuction: independentPaused },
147
+ minters: { englishAuctionOnStream: auctionMints, editionAuctionOnEditions: editionMints },
148
+ economics: economics.map((terms, index) => ({
149
+ product: products[index] ?? "stream",
150
+ feeRecipient: terms.feeRecipient,
151
+ feeShare: terms.feeShare,
152
+ royaltyRate: terms.royaltyRate,
153
+ })),
154
+ museum,
155
+ readAt: now,
156
+ };
157
+ }
@@ -0,0 +1,94 @@
1
+ import { type Address, type Client, type Hex } from "viem";
2
+ import { type StreamInstance } from "../instance.js";
3
+ import { type LogScanOptions } from "./chain.js";
4
+ import type { WorkRef } from "./work.js";
5
+ /** The state of a 1/1's sale. */
6
+ export type SaleState = "none" | "active" | "paused" | "ended" | "settled" | "cancelled" | "unknown";
7
+ /** The English auction of a 1/1, as the contract answers now. */
8
+ export interface Sale {
9
+ readonly saleId: bigint;
10
+ readonly token: Address;
11
+ readonly tokenId: bigint;
12
+ /**
13
+ * `"active"` while bids are taken, `"ended"` once the end time passed and nobody settled yet,
14
+ * `"settled"` after `settle`. The contract derives it from the block time, so it is current
15
+ * as of the block read.
16
+ */
17
+ readonly state: SaleState;
18
+ /** The raw `AuctionState` number. */
19
+ readonly stateCode: number;
20
+ /**
21
+ * The standing top bid in wei and its bidder; 0 and null when nobody holds a bid. (After a
22
+ * bid was returned the contract keeps its amount as a floor; that is not a standing bid.)
23
+ */
24
+ readonly bid: bigint;
25
+ readonly bidder: Address | null;
26
+ /** Who receives the work if the top bid wins. */
27
+ readonly recipient: Address | null;
28
+ /** Unix seconds. A bid inside the last `extensionWindow` seconds moves it. */
29
+ readonly endTime: bigint;
30
+ readonly pausedAt: bigint;
31
+ /** Unix seconds of the latest restart of an unsold Independent Stream work, or 0. */
32
+ readonly restartedAt: bigint;
33
+ /** The least a new bid must pay, in wei; null when the sale takes no bids. */
34
+ readonly minimumBid: bigint | null;
35
+ /** The split wallet that receives the artist portion. */
36
+ readonly seller: Address;
37
+ /** The network's share of the price, out of 100,000. */
38
+ readonly feeShare: number;
39
+ /** The winner who still has to collect the work with `claimDelivery`, or null. */
40
+ readonly pendingDelivery: Address | null;
41
+ /** Unix seconds from which `settleOrRefund` is accepted, or 0. */
42
+ readonly refusableAt: bigint;
43
+ /** The auction's settings: how long a sale runs, the anti-snipe window, the least raise (out of 100,000). */
44
+ readonly config: {
45
+ readonly duration: number;
46
+ readonly extensionWindow: number;
47
+ readonly incrementShare: number;
48
+ };
49
+ /** Seconds after the end before an unsold Independent Stream work can be offered again. */
50
+ readonly restartDelay: number;
51
+ /** The contract's pause: it stops new starts and restarts only. Bids, settling and claims still work. */
52
+ readonly contractPaused: boolean;
53
+ }
54
+ /**
55
+ * The state of a work's first sale: the top bid, the end time, what a new bid must pay and
56
+ * what can be done next.
57
+ *
58
+ * Contract: [`EnglishAuction.auction`, `auctionClock`, `minimumBid`, `pendingDelivery`, `refusableAt`, `config`, `paused`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/sales/EnglishAuction.sol).
59
+ */
60
+ export declare function readSale(client: Client, instance: StreamInstance, ref: WorkRef): Promise<Sale>;
61
+ /** One bid on a 1/1. */
62
+ export interface SaleBid {
63
+ readonly bidder: Address;
64
+ readonly recipient: Address;
65
+ readonly amount: bigint;
66
+ /** The sale's end time after this bid. */
67
+ readonly endTime: bigint;
68
+ readonly blockNumber: bigint;
69
+ readonly transactionHash: Hex;
70
+ }
71
+ /** The history of a 1/1's sale, from its events. */
72
+ export interface SaleHistory {
73
+ /** The transaction that first started the sale (it carries the item), or null. */
74
+ readonly firstStartTransaction: Hex | null;
75
+ /** How many times the sale started: more than 1 when an unsold work was offered again. */
76
+ readonly starts: number;
77
+ /** The bids of the latest run, newest first. */
78
+ readonly bids: readonly SaleBid[];
79
+ /** How the latest run settled, or null: the buyer (zero address when unsold), the price and the split. */
80
+ readonly settlement: {
81
+ readonly buyer: Address | null;
82
+ readonly price: bigint;
83
+ readonly sellerProceeds: bigint;
84
+ readonly fee: bigint;
85
+ readonly transactionHash: Hex;
86
+ } | null;
87
+ }
88
+ /**
89
+ * The bids and the settlement of a work's sale, from the auction's events. A restart keeps
90
+ * the sale ID, so only events since the latest start count.
91
+ *
92
+ * Contract: the `SaleStarted`, `BidPlaced` and `SaleSettled` events of [`EnglishAuction`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/sales/EnglishAuction.sol).
93
+ */
94
+ export declare function readSaleHistory(client: Client, instance: StreamInstance, ref: WorkRef, options?: LogScanOptions): Promise<SaleHistory>;
@@ -0,0 +1,133 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { getAbiItem, isAddressEqual, zeroAddress } from "viem";
3
+ import { readContract } from "viem/actions";
4
+ import { AUCTION_STATE } from "../constants.js";
5
+ import { englishAuctionAbi } from "../generated/abis/EnglishAuction.js";
6
+ import { saleId as saleIdOf } from "../hashing/ids.js";
7
+ import { assertInstanceChain } from "../instance.js";
8
+ import { orOnRevert, scanEvents } from "./chain.js";
9
+ const STATE_NAMES = {
10
+ [AUCTION_STATE.NONE]: "none",
11
+ [AUCTION_STATE.ACTIVE]: "active",
12
+ [AUCTION_STATE.PAUSED]: "paused",
13
+ [AUCTION_STATE.ENDED]: "ended",
14
+ [AUCTION_STATE.SETTLED]: "settled",
15
+ [AUCTION_STATE.CANCELLED]: "cancelled",
16
+ };
17
+ /**
18
+ * The state of a work's first sale: the top bid, the end time, what a new bid must pay and
19
+ * what can be done next.
20
+ *
21
+ * Contract: [`EnglishAuction.auction`, `auctionClock`, `minimumBid`, `pendingDelivery`, `refusableAt`, `config`, `paused`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/sales/EnglishAuction.sol).
22
+ */
23
+ export async function readSale(client, instance, ref) {
24
+ await assertInstanceChain(client, instance);
25
+ const token = ref.token ?? instance.addresses.stream;
26
+ const id = saleIdOf(token, ref.tokenId);
27
+ const auction = { address: instance.addresses.englishAuction, abi: englishAuctionAbi };
28
+ const [known, minimumBid, pendingDelivery, refusableAt, config, contractPaused, restartDelay] = await Promise.all([
29
+ // Both revert with UnknownSale for a token whose sale never started.
30
+ orOnRevert(Promise.all([
31
+ readContract(client, { ...auction, functionName: "auction", args: [id] }),
32
+ readContract(client, { ...auction, functionName: "auctionClock", args: [id] }),
33
+ ]), null),
34
+ orOnRevert(readContract(client, { ...auction, functionName: "minimumBid", args: [id] }), null),
35
+ orOnRevert(readContract(client, { ...auction, functionName: "pendingDelivery", args: [id] }), zeroAddress),
36
+ orOnRevert(readContract(client, { ...auction, functionName: "refusableAt", args: [id] }), 0n),
37
+ readContract(client, { ...auction, functionName: "config" }),
38
+ readContract(client, { ...auction, functionName: "paused" }),
39
+ readContract(client, { ...auction, functionName: "RESTART_DELAY" }),
40
+ ]);
41
+ const orNull = (address) => (isAddressEqual(address, zeroAddress) ? null : address);
42
+ const settings = { duration: config.duration, extensionWindow: config.extensionWindow, incrementShare: config.incrementShare };
43
+ if (!known) {
44
+ return {
45
+ saleId: id,
46
+ token,
47
+ tokenId: ref.tokenId,
48
+ state: "none",
49
+ stateCode: AUCTION_STATE.NONE,
50
+ bid: 0n,
51
+ bidder: null,
52
+ recipient: null,
53
+ endTime: 0n,
54
+ pausedAt: 0n,
55
+ restartedAt: 0n,
56
+ minimumBid: null,
57
+ seller: zeroAddress,
58
+ feeShare: 0,
59
+ pendingDelivery: null,
60
+ refusableAt: 0n,
61
+ config: settings,
62
+ restartDelay: Number(restartDelay),
63
+ contractPaused,
64
+ };
65
+ }
66
+ const [state, clock] = known;
67
+ return {
68
+ saleId: id,
69
+ token,
70
+ tokenId: ref.tokenId,
71
+ state: STATE_NAMES[state.state] ?? "unknown",
72
+ stateCode: state.state,
73
+ bid: isAddressEqual(state.bidder, zeroAddress) ? 0n : state.bid,
74
+ bidder: orNull(state.bidder),
75
+ recipient: orNull(state.recipient),
76
+ endTime: state.endTime,
77
+ pausedAt: state.pausedAt,
78
+ restartedAt: clock[3],
79
+ minimumBid: state.state === AUCTION_STATE.ACTIVE ? minimumBid : null,
80
+ seller: state.seller,
81
+ feeShare: Number(state.feeShare),
82
+ pendingDelivery: orNull(pendingDelivery),
83
+ refusableAt,
84
+ config: settings,
85
+ restartDelay: Number(restartDelay),
86
+ contractPaused,
87
+ };
88
+ }
89
+ const SALE_STARTED = /*#__PURE__*/ getAbiItem({ abi: englishAuctionAbi, name: "SaleStarted" });
90
+ const BID_PLACED = /*#__PURE__*/ getAbiItem({ abi: englishAuctionAbi, name: "BidPlaced" });
91
+ const SALE_SETTLED = /*#__PURE__*/ getAbiItem({ abi: englishAuctionAbi, name: "SaleSettled" });
92
+ /**
93
+ * The bids and the settlement of a work's sale, from the auction's events. A restart keeps
94
+ * the sale ID, so only events since the latest start count.
95
+ *
96
+ * Contract: the `SaleStarted`, `BidPlaced` and `SaleSettled` events of [`EnglishAuction`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/sales/EnglishAuction.sol).
97
+ */
98
+ export async function readSaleHistory(client, instance, ref, options = {}) {
99
+ await assertInstanceChain(client, instance);
100
+ const id = saleIdOf(ref.token ?? instance.addresses.stream, ref.tokenId);
101
+ const address = instance.addresses.englishAuction;
102
+ const [starts, bids, settles] = await Promise.all([
103
+ scanEvents(client, instance, { address, event: SALE_STARTED, args: { saleId: id } }, options),
104
+ scanEvents(client, instance, { address, event: BID_PLACED, args: { saleId: id } }, options),
105
+ scanEvents(client, instance, { address, event: SALE_SETTLED, args: { saleId: id } }, options),
106
+ ]);
107
+ const since = starts.at(-1)?.blockNumber ?? 0n;
108
+ const settled = settles.filter((log) => log.blockNumber >= since).at(-1);
109
+ return {
110
+ firstStartTransaction: starts[0]?.transactionHash ?? null,
111
+ starts: starts.length,
112
+ bids: bids
113
+ .filter((log) => log.blockNumber >= since)
114
+ .map((log) => ({
115
+ bidder: log.args.bidder,
116
+ recipient: log.args.recipient,
117
+ amount: log.args.amount,
118
+ endTime: log.args.endTime,
119
+ blockNumber: log.blockNumber,
120
+ transactionHash: log.transactionHash,
121
+ }))
122
+ .reverse(),
123
+ settlement: settled
124
+ ? {
125
+ buyer: isAddressEqual(settled.args.buyer, zeroAddress) ? null : settled.args.buyer,
126
+ price: settled.args.price,
127
+ sellerProceeds: settled.args.sellerProceeds,
128
+ fee: settled.args.fee,
129
+ transactionHash: settled.transactionHash,
130
+ }
131
+ : null,
132
+ };
133
+ }
@@ -0,0 +1,47 @@
1
+ import { type Address, type Client } from "viem";
2
+ import { type StreamInstance } from "../instance.js";
3
+ import type { Payee } from "../types.js";
4
+ import { type LogScanOptions } from "./chain.js";
5
+ import { type Split, type WorkRef } from "./work.js";
6
+ /**
7
+ * The payee list of a work's royalty vault: the work's seller vault takes everything but the
8
+ * network's share, and the network's fee recipient takes that share, both as fixed payees in
9
+ * address order. With a fee share of zero there is no royalty vault: royalties go straight
10
+ * to the seller vault.
11
+ *
12
+ * Contract: [`Splits.royaltyPayees`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/economics/Splits.sol).
13
+ */
14
+ export declare function royaltyPayees(seller: Address, feeRecipient: Address, feeShare: number): Payee[];
15
+ /**
16
+ * A vault (split wallet) by its address: its payees, and what each has released and can
17
+ * release now in ETH. The payee list is not stored on chain; it is read from the event the
18
+ * ledger emitted when the vault was created, and checked: the list must derive this address.
19
+ * Returns null for a vault nobody has created yet (ETH sent to its address is still held for
20
+ * it; build its payee list from the work's item and use `readSplit`).
21
+ *
22
+ * Contract: the `WalletCreated` event and `walletFor`, `releasable`, `released` of
23
+ * [`SplitLedger`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/economics/SplitLedger.sol).
24
+ */
25
+ export declare function readVault(client: Client, instance: StreamInstance, wallet: Address, options?: LogScanOptions): Promise<Split | null>;
26
+ /** Where a work's royalties go, and what waits there. */
27
+ export interface RoyaltyVault {
28
+ /** The address marketplaces pay royalties to (`royaltyInfo`). */
29
+ readonly receiver: Address;
30
+ /**
31
+ * The royalty vault's payees: the work's seller vault and the network's fee recipient. Null
32
+ * when the receiver is the seller vault itself (no network share), or was never created.
33
+ */
34
+ readonly split: Split | null;
35
+ /** The seller vault among the payees, with what can be moved on to it now. */
36
+ readonly sellerShare: Split["payees"][number] | null;
37
+ }
38
+ /**
39
+ * The royalty vault of a work. Royalties are NOT paid to the seller vault: they go to a
40
+ * second vault that splits them between the network and the seller vault. Anyone can move the
41
+ * seller vault's part on (`collectRoyalties`), and the work's payees then take their shares
42
+ * from the seller vault as they do for sale proceeds (`releaseFromVault`).
43
+ *
44
+ * Contract: [`Stream6529.workOf`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/core/StreamBase.sol)
45
+ * (`royaltyReceiver`), and `readVault`.
46
+ */
47
+ export declare function readRoyaltyVault(client: Client, instance: StreamInstance, ref: WorkRef, options?: LogScanOptions): Promise<RoyaltyVault>;
@@ -0,0 +1,75 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { getAbiItem, isAddressEqual, zeroAddress } from "viem";
3
+ import { readContract } from "viem/actions";
4
+ import { DENOMINATOR, ZERO_HASH } from "../constants.js";
5
+ import { StreamSdkError } from "../errors.js";
6
+ import { splitLedgerAbi } from "../generated/abis/SplitLedger.js";
7
+ import { stream6529Abi } from "../generated/abis/Stream6529.js";
8
+ import { assertInstanceChain } from "../instance.js";
9
+ import { scanEvents } from "./chain.js";
10
+ import { readSplit } from "./work.js";
11
+ /**
12
+ * The payee list of a work's royalty vault: the work's seller vault takes everything but the
13
+ * network's share, and the network's fee recipient takes that share, both as fixed payees in
14
+ * address order. With a fee share of zero there is no royalty vault: royalties go straight
15
+ * to the seller vault.
16
+ *
17
+ * Contract: [`Splits.royaltyPayees`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/economics/Splits.sol).
18
+ */
19
+ export function royaltyPayees(seller, feeRecipient, feeShare) {
20
+ const sellerPayee = { artistId: 0n, account: seller, share: DENOMINATOR - feeShare };
21
+ const feePayee = { artistId: 0n, account: feeRecipient, share: feeShare };
22
+ return BigInt(seller) < BigInt(feeRecipient) ? [sellerPayee, feePayee] : [feePayee, sellerPayee];
23
+ }
24
+ const WALLET_CREATED = /*#__PURE__*/ getAbiItem({ abi: splitLedgerAbi, name: "WalletCreated" });
25
+ /**
26
+ * A vault (split wallet) by its address: its payees, and what each has released and can
27
+ * release now in ETH. The payee list is not stored on chain; it is read from the event the
28
+ * ledger emitted when the vault was created, and checked: the list must derive this address.
29
+ * Returns null for a vault nobody has created yet (ETH sent to its address is still held for
30
+ * it; build its payee list from the work's item and use `readSplit`).
31
+ *
32
+ * Contract: the `WalletCreated` event and `walletFor`, `releasable`, `released` of
33
+ * [`SplitLedger`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/economics/SplitLedger.sol).
34
+ */
35
+ export async function readVault(client, instance, wallet, options = {}) {
36
+ await assertInstanceChain(client, instance);
37
+ const created = await scanEvents(client, instance, { address: instance.addresses.splitLedger, event: WALLET_CREATED, args: { wallet } }, options);
38
+ const log = created[0];
39
+ if (!log)
40
+ return null;
41
+ if (log.args.salt !== ZERO_HASH)
42
+ throw new StreamSdkError("MISMATCH", `Vault ${wallet} was created with a salt this release does not handle.`);
43
+ const split = await readSplit(client, instance, log.args.payees);
44
+ if (!isAddressEqual(split.wallet, wallet)) {
45
+ throw new StreamSdkError("MISMATCH", `The payee list in the WalletCreated event does not derive vault ${wallet}.`);
46
+ }
47
+ return split;
48
+ }
49
+ /**
50
+ * The royalty vault of a work. Royalties are NOT paid to the seller vault: they go to a
51
+ * second vault that splits them between the network and the seller vault. Anyone can move the
52
+ * seller vault's part on (`collectRoyalties`), and the work's payees then take their shares
53
+ * from the seller vault as they do for sale proceeds (`releaseFromVault`).
54
+ *
55
+ * Contract: [`Stream6529.workOf`](https://github.com/6529-Collections/6529-stream/blob/c6d4965861907841519cf3878c9db7052424a9a0/src/core/StreamBase.sol)
56
+ * (`royaltyReceiver`), and `readVault`.
57
+ */
58
+ export async function readRoyaltyVault(client, instance, ref, options = {}) {
59
+ await assertInstanceChain(client, instance);
60
+ const work = await readContract(client, { address: ref.token ?? instance.addresses.stream, abi: stream6529Abi, functionName: "workOf", args: [ref.tokenId] });
61
+ const receiver = work.royaltyReceiver;
62
+ if (isAddressEqual(receiver, zeroAddress))
63
+ return { receiver, split: null, sellerShare: null };
64
+ const split = await readVault(client, instance, receiver, options);
65
+ // In a royalty vault both payees are fixed addresses, and the one that is itself a vault of the ledger is the seller vault.
66
+ let sellerShare = null;
67
+ if (split?.payees.length === 2 && split.payees.every((payee) => payee.artistId === 0n)) {
68
+ for (const payee of split.payees) {
69
+ const isVault = await readContract(client, { address: instance.addresses.splitLedger, abi: splitLedgerAbi, functionName: "isWallet", args: [payee.listed.account] });
70
+ if (isVault)
71
+ sellerShare = payee;
72
+ }
73
+ }
74
+ return { receiver, split: sellerShare ? split : null, sellerShare };
75
+ }