@fangorn-network/sdk 0.1.5 → 0.2.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.
- package/lib/cli/cli.js +83 -46
- package/lib/cli/sell.d.ts +2 -2
- package/lib/cli/sell.js +15 -9
- package/lib/cli/stage.d.ts +21 -3
- package/lib/cli/stage.js +110 -24
- package/lib/config.d.ts +327 -1
- package/lib/config.js +11 -2
- package/lib/contracts/data-registry/abi.d.ts +42 -1
- package/lib/contracts/data-registry/abi.js +47 -1
- package/lib/contracts/data-registry/index.d.ts +45 -3
- package/lib/contracts/data-registry/index.js +69 -14
- package/lib/contracts/data-registry/mmr.d.ts +9 -2
- package/lib/contracts/data-registry/mmr.js +6 -2
- package/lib/contracts/index.d.ts +2 -2
- package/lib/contracts/index.js +2 -2
- package/lib/contracts/settlement-registry/abi.d.ts +1 -1
- package/lib/contracts/settlement-registry/abi.js +1 -1
- package/lib/contracts/write.d.ts +29 -5
- package/lib/contracts/write.js +78 -12
- package/lib/crypto/encryption.js +3 -0
- package/lib/crypto/paid.d.ts +1 -1
- package/lib/crypto/paid.js +4 -1
- package/lib/engine/index.d.ts +23 -4
- package/lib/engine/index.js +49 -21
- package/lib/engine/records.d.ts +9 -1
- package/lib/engine/records.js +32 -6
- package/lib/erc8004.d.ts +1 -1
- package/lib/erc8004.js +12 -4
- package/lib/fangorn.d.ts +12 -2
- package/lib/fangorn.js +38 -17
- package/lib/feed.d.ts +23 -2
- package/lib/feed.js +43 -6
- package/lib/index.d.ts +3 -3
- package/lib/index.js +4 -4
- package/lib/providers/storage/index.js +1 -1
- package/lib/providers/storage/pinata.js +14 -6
- package/lib/providers/storage/signed-url.js +21 -8
- package/lib/providers/storage/types.d.ts +9 -1
- package/lib/providers/storage/types.js +54 -1
- package/lib/providers/storage/utils.d.ts +3 -1
- package/lib/providers/storage/utils.js +3 -3
- package/lib/test/mem-registry.d.ts +3 -3
- package/lib/test/mem-registry.js +7 -5
- package/lib/test/testbed.d.ts +5190 -5190
- package/lib/test/testbed.js +1 -1
- package/package.json +6 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { prepareWrite, requireWallet, sendWrite } from "../write.js";
|
|
1
2
|
import { DATA_REGISTRY_ABI } from "./abi.js";
|
|
2
3
|
import { getLogsInWindows } from "../logs.js";
|
|
3
|
-
import { prepareWrite, requireWallet, sendWrite } from "../write.js";
|
|
4
4
|
import { keccak256, toHex } from "viem";
|
|
5
5
|
|
|
6
6
|
//#region src/contracts/data-registry/index.ts
|
|
@@ -129,13 +129,13 @@ var ChainRegistry = class {
|
|
|
129
129
|
write(fn, args) {
|
|
130
130
|
return sendWrite(this.publicClient, requireWallet(this.walletClient, fn), this.data, DATA_REGISTRY_ABI, fn, args);
|
|
131
131
|
}
|
|
132
|
-
/** U's `Updated` events, narrowed on-chain by publisher and repo. */
|
|
133
|
-
source(filter) {
|
|
132
|
+
/** U's `Updated` events of one version, narrowed on-chain by publisher and repo. */
|
|
133
|
+
source(filter, event) {
|
|
134
134
|
const ids = filter.repo === void 0 ? {} : { repo_id: repoId(filter.repo) };
|
|
135
135
|
const who = filter.publisher === void 0 ? {} : { publisher: filter.publisher };
|
|
136
136
|
return {
|
|
137
137
|
address: this.data,
|
|
138
|
-
abi:
|
|
138
|
+
abi: [event],
|
|
139
139
|
eventName: "Updated",
|
|
140
140
|
args: {
|
|
141
141
|
...who,
|
|
@@ -144,28 +144,36 @@ var ChainRegistry = class {
|
|
|
144
144
|
};
|
|
145
145
|
}
|
|
146
146
|
async log(filter, from, to) {
|
|
147
|
-
const sorted = (await getLogsInWindows(this.publicClient, from, to, (fromBlock, toBlock) => this.publicClient.getContractEvents({
|
|
148
|
-
...this.source(filter),
|
|
147
|
+
const sorted = (await getLogsInWindows(this.publicClient, from, to, async (fromBlock, toBlock) => (await Promise.all(UPDATED_EVENTS.map((event) => this.publicClient.getContractEvents({
|
|
148
|
+
...this.source(filter, event),
|
|
149
149
|
fromBlock,
|
|
150
150
|
toBlock,
|
|
151
151
|
strict: true
|
|
152
|
-
}), this.logWindow)).sort((a, b) => a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1);
|
|
152
|
+
})))).flat(), this.logWindow)).sort((a, b) => a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1);
|
|
153
153
|
return this.withTimestamps(sorted);
|
|
154
154
|
}
|
|
155
|
-
/**
|
|
155
|
+
/**
|
|
156
|
+
* Old-version logs don't carry their block's timestamp: one block read per
|
|
157
|
+
* distinct block. New-version logs carry it.
|
|
158
|
+
*/
|
|
156
159
|
async withTimestamps(logs) {
|
|
157
|
-
const blocks = [...new Set(logs.map((l) => l.blockNumber))];
|
|
160
|
+
const blocks = [...new Set(logs.filter((l) => l.args.timestamp === void 0).map((l) => l.blockNumber))];
|
|
158
161
|
const times = new Map(await Promise.all(blocks.map(async (n) => [n, (await this.publicClient.getBlock({ blockNumber: n })).timestamp])));
|
|
159
|
-
return logs.map((l) => toEntry(l, times.get(l.blockNumber) ?? 0n));
|
|
162
|
+
return logs.map((l) => toEntry(l, l.args.timestamp ?? times.get(l.blockNumber) ?? 0n));
|
|
160
163
|
}
|
|
161
164
|
watch(filter, onEntry, onError, pollingInterval) {
|
|
162
165
|
let queue = Promise.resolve();
|
|
166
|
+
const publisher = filter.publisher?.toLowerCase();
|
|
167
|
+
const id = filter.repo === void 0 ? void 0 : repoId(filter.repo);
|
|
163
168
|
return this.publicClient.watchContractEvent({
|
|
164
|
-
|
|
169
|
+
address: this.data,
|
|
170
|
+
abi: UPDATED_EVENTS,
|
|
165
171
|
strict: true,
|
|
166
172
|
pollingInterval,
|
|
167
173
|
onLogs: (logs) => {
|
|
168
|
-
|
|
174
|
+
const live = logs.filter((l) => !l.removed && l.eventName === "Updated" && (publisher === void 0 || l.args.publisher.toLowerCase() === publisher) && (id === void 0 || l.args.repo_id === id));
|
|
175
|
+
if (!live.length) return;
|
|
176
|
+
queue = queue.then(() => this.withTimestamps(live)).then((entries) => {
|
|
169
177
|
for (const e of entries) onEntry(e);
|
|
170
178
|
}).catch((e) => onError?.(e));
|
|
171
179
|
},
|
|
@@ -186,6 +194,51 @@ function updateArgs(u) {
|
|
|
186
194
|
u.car
|
|
187
195
|
];
|
|
188
196
|
}
|
|
197
|
+
/** `Updated` as the contract emits it. */
|
|
198
|
+
const UPDATED = DATA_REGISTRY_ABI.find((i) => i.type === "event" && i.name === "Updated");
|
|
199
|
+
/**
|
|
200
|
+
* `Updated` as the contract emitted it before it gained `index` and `timestamp`
|
|
201
|
+
* (contracts 0f178bb). The proxy is upgraded in place, so the log before the
|
|
202
|
+
* upgrade has this topic.
|
|
203
|
+
*/
|
|
204
|
+
const UPDATED_V0 = {
|
|
205
|
+
type: "event",
|
|
206
|
+
name: "Updated",
|
|
207
|
+
anonymous: false,
|
|
208
|
+
inputs: [
|
|
209
|
+
{
|
|
210
|
+
name: "publisher",
|
|
211
|
+
type: "address",
|
|
212
|
+
indexed: true
|
|
213
|
+
},
|
|
214
|
+
{
|
|
215
|
+
name: "repo_id",
|
|
216
|
+
type: "bytes32",
|
|
217
|
+
indexed: true
|
|
218
|
+
},
|
|
219
|
+
{
|
|
220
|
+
name: "repo",
|
|
221
|
+
type: "string",
|
|
222
|
+
indexed: false
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
name: "pos",
|
|
226
|
+
type: "uint64",
|
|
227
|
+
indexed: false
|
|
228
|
+
},
|
|
229
|
+
{
|
|
230
|
+
name: "parent",
|
|
231
|
+
type: "bytes32",
|
|
232
|
+
indexed: false
|
|
233
|
+
},
|
|
234
|
+
{
|
|
235
|
+
name: "head",
|
|
236
|
+
type: "bytes32",
|
|
237
|
+
indexed: false
|
|
238
|
+
}
|
|
239
|
+
]
|
|
240
|
+
};
|
|
241
|
+
const UPDATED_EVENTS = [UPDATED_V0, UPDATED];
|
|
189
242
|
function toEntry(log, timestamp) {
|
|
190
243
|
return {
|
|
191
244
|
publisher: log.args.publisher,
|
|
@@ -195,9 +248,11 @@ function toEntry(log, timestamp) {
|
|
|
195
248
|
head: log.args.head,
|
|
196
249
|
t: log.blockNumber,
|
|
197
250
|
timestamp,
|
|
198
|
-
|
|
251
|
+
index: log.args.index,
|
|
252
|
+
id: `${log.transactionHash}:${log.logIndex.toString()}`,
|
|
253
|
+
repoId: log.args.repo_id
|
|
199
254
|
};
|
|
200
255
|
}
|
|
201
256
|
|
|
202
257
|
//#endregion
|
|
203
|
-
export { ChainRegistry, EPOCH_SECONDS, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage };
|
|
258
|
+
export { ChainRegistry, EPOCH_SECONDS, UPDATED_V0, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage };
|
|
@@ -2,8 +2,15 @@ import { UpdateEntry } from "./index.js";
|
|
|
2
2
|
import { Hex } from "viem";
|
|
3
3
|
|
|
4
4
|
//#region src/contracts/data-registry/mmr.d.ts
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The leaf the contract appended for one log entry. The contract hashes the repo's raw bytes,
|
|
8
|
+
* which need not be UTF-8: a decoded `repo` with U+FFFD in it re-hashes to another id, so pass
|
|
9
|
+
* the event's indexed `repo_id` as `repoId` where the entry has it.
|
|
10
|
+
*/
|
|
11
|
+
declare const logLeaf: (e: UpdateEntry & {
|
|
12
|
+
repoId?: Hex;
|
|
13
|
+
}) => Hex;
|
|
7
14
|
/** A mountain range as its length and peaks; `peaks[h]` is live where bit h of n is set. */
|
|
8
15
|
interface Mmr {
|
|
9
16
|
n: number;
|
|
@@ -3,7 +3,11 @@ import { encodeAbiParameters, keccak256, stringToHex, zeroHash } from "viem";
|
|
|
3
3
|
|
|
4
4
|
//#region src/contracts/data-registry/mmr.ts
|
|
5
5
|
const tag = (s) => stringToHex(s, { size: 32 });
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* The leaf the contract appended for one log entry. The contract hashes the repo's raw bytes,
|
|
8
|
+
* which need not be UTF-8: a decoded `repo` with U+FFFD in it re-hashes to another id, so pass
|
|
9
|
+
* the event's indexed `repo_id` as `repoId` where the entry has it.
|
|
10
|
+
*/
|
|
7
11
|
const logLeaf = (e) => keccak256(encodeAbiParameters([
|
|
8
12
|
{ type: "bytes32" },
|
|
9
13
|
{ type: "address" },
|
|
@@ -14,7 +18,7 @@ const logLeaf = (e) => keccak256(encodeAbiParameters([
|
|
|
14
18
|
], [
|
|
15
19
|
tag("leaf"),
|
|
16
20
|
e.publisher,
|
|
17
|
-
repoId(e.repo),
|
|
21
|
+
e.repoId ?? repoId(e.repo),
|
|
18
22
|
BigInt(e.pos),
|
|
19
23
|
e.head,
|
|
20
24
|
e.timestamp
|
package/lib/contracts/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PreparedTx } from "./write.js";
|
|
2
|
-
import { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFilter, Registry, RepoRef, UPDATE_TYPES, UpdateEntry, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./data-registry/index.js";
|
|
2
|
+
import { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFilter, Registry, RepoRef, UPDATED_V0, UPDATE_TYPES, UpdateEntry, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./data-registry/index.js";
|
|
3
3
|
import { DATA_REGISTRY_ABI } from "./data-registry/abi.js";
|
|
4
4
|
import { RegisterArgs, SettleArgs, SettlementPayment, SettlementRegistryClient, TERMS_TYPES, Terms, TermsJson, WHOLE_REPO, recordKey, registerNonce, settlementDomain, subjectOf, termsFromJson, termsToJson } from "./settlement-registry/index.js";
|
|
5
5
|
import { SETTLEMENT_REGISTRY_ABI } from "./settlement-registry/abi.js";
|
|
6
6
|
import { EMPTY_MMR, Mmr, logLeaf, mmrAppend, mmrRoot } from "./data-registry/mmr.js";
|
|
7
|
-
export { ChainRegistry, ChainRegistryConfig, CommitUpdate, DATA_REGISTRY_ABI, EMPTY_MMR, EPOCH_SECONDS, LogFilter, Mmr, type PreparedTx, RegisterArgs, Registry, RepoRef, SETTLEMENT_REGISTRY_ABI, SettleArgs, SettlementPayment, SettlementRegistryClient, TERMS_TYPES, Terms, TermsJson, UPDATE_TYPES, UpdateEntry, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, logLeaf, mmrAppend, mmrRoot, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
|
|
7
|
+
export { ChainRegistry, ChainRegistryConfig, CommitUpdate, DATA_REGISTRY_ABI, EMPTY_MMR, EPOCH_SECONDS, LogFilter, Mmr, type PreparedTx, RegisterArgs, Registry, RepoRef, SETTLEMENT_REGISTRY_ABI, SettleArgs, SettlementPayment, SettlementRegistryClient, TERMS_TYPES, Terms, TermsJson, UPDATED_V0, UPDATE_TYPES, UpdateEntry, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, logLeaf, mmrAppend, mmrRoot, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
|
package/lib/contracts/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DATA_REGISTRY_ABI } from "./data-registry/abi.js";
|
|
2
|
-
import { ChainRegistry, EPOCH_SECONDS, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./data-registry/index.js";
|
|
2
|
+
import { ChainRegistry, EPOCH_SECONDS, UPDATED_V0, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./data-registry/index.js";
|
|
3
3
|
import { SETTLEMENT_REGISTRY_ABI } from "./settlement-registry/abi.js";
|
|
4
4
|
import { SettlementRegistryClient, TERMS_TYPES, WHOLE_REPO, recordKey, registerNonce, settlementDomain, subjectOf, termsFromJson, termsToJson } from "./settlement-registry/index.js";
|
|
5
5
|
import { EMPTY_MMR, logLeaf, mmrAppend, mmrRoot } from "./data-registry/mmr.js";
|
|
6
6
|
|
|
7
|
-
export { ChainRegistry, DATA_REGISTRY_ABI, EMPTY_MMR, EPOCH_SECONDS, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, TERMS_TYPES, UPDATE_TYPES, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, logLeaf, mmrAppend, mmrRoot, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
|
|
7
|
+
export { ChainRegistry, DATA_REGISTRY_ABI, EMPTY_MMR, EPOCH_SECONDS, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, TERMS_TYPES, UPDATED_V0, UPDATE_TYPES, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, logLeaf, mmrAppend, mmrRoot, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//#region src/contracts/settlement-registry/abi.d.ts
|
|
2
2
|
/**
|
|
3
3
|
* Generated from `forge inspect SettlementRegistry abi` in fangorn-network/contracts
|
|
4
|
-
* (
|
|
4
|
+
* (src/SettlementRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
|
|
5
5
|
*/
|
|
6
6
|
declare const SETTLEMENT_REGISTRY_ABI: readonly [{
|
|
7
7
|
readonly type: "constructor";
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//#region src/contracts/settlement-registry/abi.ts
|
|
2
2
|
/**
|
|
3
3
|
* Generated from `forge inspect SettlementRegistry abi` in fangorn-network/contracts
|
|
4
|
-
* (
|
|
4
|
+
* (src/SettlementRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
|
|
5
5
|
*/
|
|
6
6
|
const SETTLEMENT_REGISTRY_ABI = [
|
|
7
7
|
{
|
package/lib/contracts/write.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Abi, Address, Hash, Hex, PublicClient, WalletClient } from "viem";
|
|
1
|
+
import { Abi, Address, Hash, Hex, PublicClient, TransactionReceipt, WalletClient } from "viem";
|
|
2
2
|
|
|
3
3
|
//#region src/contracts/write.d.ts
|
|
4
4
|
|
|
@@ -25,14 +25,38 @@ interface PreparedTx {
|
|
|
25
25
|
* Two deliberate choices, both about transactions that would otherwise silently
|
|
26
26
|
* fail on a live L2:
|
|
27
27
|
*
|
|
28
|
-
* - **30% gas headroom.** The estimate is taken against the
|
|
29
|
-
* time the transaction lands the state has moved.
|
|
30
|
-
*
|
|
28
|
+
* - **30% + APPEND_ALLOWANCE gas headroom.** The estimate is taken against the
|
|
29
|
+
* current state; by the time the transaction lands the state has moved. The
|
|
30
|
+
* fixed allowance covers the one jump the 30% can't: other updates landing
|
|
31
|
+
* first, so this one appends to the log at a length of 2^k − 1. Unused gas is
|
|
32
|
+
* refunded, so the headroom is free and running out of it is not.
|
|
31
33
|
* - **3x maxFeePerGas.** This is a ceiling, not a payment — you pay
|
|
32
34
|
* base + priority. Quoting it tightly is how a transaction gets stuck when the
|
|
33
35
|
* base fee ticks up between estimate and inclusion.
|
|
34
36
|
*/
|
|
37
|
+
/**
|
|
38
|
+
* The most DataRegistry._append can cost over an append estimated at any other
|
|
39
|
+
* log length: 63 merges (cold SLOAD + keccak, ~2.5k each) and a first write to
|
|
40
|
+
* peaks[63] (~20k). logLength is a uint64, so this is a hard bound, not a guess.
|
|
41
|
+
* The contracts repo pins it: test_append_worst_case_fits_sdk_allowance.
|
|
42
|
+
*/
|
|
43
|
+
declare const APPEND_ALLOWANCE = 200000n;
|
|
35
44
|
declare function sendWrite(publicClient: PublicClient, walletClient: WalletClient, address: Address, abi: Abi, functionName: string, args: readonly unknown[], value?: bigint): Promise<Hash>;
|
|
45
|
+
/**
|
|
46
|
+
* Wait for `hash` to be mined and throw unless it is what took effect.
|
|
47
|
+
*
|
|
48
|
+
* - A mined revert still yields a receipt; without the status check it reads as success.
|
|
49
|
+
* - viem resolves with the REPLACEMENT's receipt when another transaction takes the
|
|
50
|
+
* nonce (a second process on the same key, a wallet "cancel"). That receipt says
|
|
51
|
+
* nothing about this call, so only a reprice (same to, value and data: a wallet
|
|
52
|
+
* speed-up) counts.
|
|
53
|
+
* - A timeout is not a failure: the transaction may still land. Say so, so nobody
|
|
54
|
+
* resends blind (a push resent onto its own landed head reverts as stale).
|
|
55
|
+
*/
|
|
56
|
+
declare function confirmTx(publicClient: PublicClient, hash: Hash, what: string, gasLimit?: bigint): Promise<{
|
|
57
|
+
receipt: TransactionReceipt;
|
|
58
|
+
hash: Hash;
|
|
59
|
+
}>;
|
|
36
60
|
/** Guard for clients that accept a read-only construction. */
|
|
37
61
|
declare function requireWallet(walletClient: WalletClient | undefined, what: string): WalletClient;
|
|
38
62
|
/**
|
|
@@ -56,4 +80,4 @@ declare function prepareWrite(publicClient: PublicClient, from: Address, address
|
|
|
56
80
|
simulate?: boolean;
|
|
57
81
|
}): Promise<PreparedTx>;
|
|
58
82
|
//#endregion
|
|
59
|
-
export { PreparedTx, prepareWrite, requireWallet, sendWrite };
|
|
83
|
+
export { APPEND_ALLOWANCE, PreparedTx, confirmTx, prepareWrite, requireWallet, sendWrite };
|
package/lib/contracts/write.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { encodeFunctionData, toHex } from "viem";
|
|
1
|
+
import { WaitForTransactionReceiptTimeoutError, encodeFunctionData, toHex, zeroAddress } from "viem";
|
|
2
2
|
|
|
3
3
|
//#region src/contracts/write.ts
|
|
4
4
|
/**
|
|
@@ -12,40 +12,105 @@ import { encodeFunctionData, toHex } from "viem";
|
|
|
12
12
|
* Two deliberate choices, both about transactions that would otherwise silently
|
|
13
13
|
* fail on a live L2:
|
|
14
14
|
*
|
|
15
|
-
* - **30% gas headroom.** The estimate is taken against the
|
|
16
|
-
* time the transaction lands the state has moved.
|
|
17
|
-
*
|
|
15
|
+
* - **30% + APPEND_ALLOWANCE gas headroom.** The estimate is taken against the
|
|
16
|
+
* current state; by the time the transaction lands the state has moved. The
|
|
17
|
+
* fixed allowance covers the one jump the 30% can't: other updates landing
|
|
18
|
+
* first, so this one appends to the log at a length of 2^k − 1. Unused gas is
|
|
19
|
+
* refunded, so the headroom is free and running out of it is not.
|
|
18
20
|
* - **3x maxFeePerGas.** This is a ceiling, not a payment — you pay
|
|
19
21
|
* base + priority. Quoting it tightly is how a transaction gets stuck when the
|
|
20
22
|
* base fee ticks up between estimate and inclusion.
|
|
21
23
|
*/
|
|
24
|
+
/**
|
|
25
|
+
* The most DataRegistry._append can cost over an append estimated at any other
|
|
26
|
+
* log length: 63 merges (cold SLOAD + keccak, ~2.5k each) and a first write to
|
|
27
|
+
* peaks[63] (~20k). logLength is a uint64, so this is a hard bound, not a guess.
|
|
28
|
+
* The contracts repo pins it: test_append_worst_case_fits_sdk_allowance.
|
|
29
|
+
*/
|
|
30
|
+
const APPEND_ALLOWANCE = 200000n;
|
|
31
|
+
/**
|
|
32
|
+
* writeContract reads the nonce as the node's pending count. Two sends from one key
|
|
33
|
+
* that overlap both read it before either reaches the pool, take the same nonce, and
|
|
34
|
+
* the second is rejected as "replacement transaction underpriced". So sends from one
|
|
35
|
+
* account go one at a time, each only until the node has it (not until it is mined):
|
|
36
|
+
* the next then reads a count that includes it. A failed send leaves no gap, unlike
|
|
37
|
+
* viem's nonceManager, which never gives back a nonce it handed out.
|
|
38
|
+
*/
|
|
39
|
+
const sending = /* @__PURE__ */ new Map();
|
|
40
|
+
function oneAtATime(key, f) {
|
|
41
|
+
const run = (sending.get(key) ?? Promise.resolve()).then(f, f);
|
|
42
|
+
sending.set(key, run.catch(() => void 0));
|
|
43
|
+
return run;
|
|
44
|
+
}
|
|
22
45
|
async function sendWrite(publicClient, walletClient, address, abi, functionName, args, value) {
|
|
23
46
|
if (!walletClient.chain) throw new Error("Chain required");
|
|
24
47
|
if (!walletClient.account) throw new Error("Account required");
|
|
48
|
+
assertDeployed(address, functionName);
|
|
25
49
|
const { chain, account } = walletClient;
|
|
26
50
|
const fees = await publicClient.estimateFeesPerGas();
|
|
27
|
-
const
|
|
51
|
+
const limit = await publicClient.estimateContractGas({
|
|
28
52
|
address,
|
|
29
53
|
abi,
|
|
30
54
|
functionName,
|
|
31
55
|
args,
|
|
32
56
|
account,
|
|
33
57
|
value
|
|
34
|
-
});
|
|
35
|
-
|
|
58
|
+
}) * 130n / 100n + APPEND_ALLOWANCE;
|
|
59
|
+
return (await confirmTx(publicClient, await oneAtATime(`${account.address}.${String(chain.id)}`, () => walletClient.writeContract({
|
|
36
60
|
address,
|
|
37
61
|
abi,
|
|
38
62
|
functionName,
|
|
39
63
|
args,
|
|
40
64
|
chain,
|
|
41
65
|
account,
|
|
42
|
-
gas:
|
|
66
|
+
gas: limit,
|
|
43
67
|
maxFeePerGas: fees.maxFeePerGas * 3n,
|
|
44
68
|
maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
|
|
45
69
|
value
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
|
|
70
|
+
})), functionName, limit)).hash;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Wait for `hash` to be mined and throw unless it is what took effect.
|
|
74
|
+
*
|
|
75
|
+
* - A mined revert still yields a receipt; without the status check it reads as success.
|
|
76
|
+
* - viem resolves with the REPLACEMENT's receipt when another transaction takes the
|
|
77
|
+
* nonce (a second process on the same key, a wallet "cancel"). That receipt says
|
|
78
|
+
* nothing about this call, so only a reprice (same to, value and data: a wallet
|
|
79
|
+
* speed-up) counts.
|
|
80
|
+
* - A timeout is not a failure: the transaction may still land. Say so, so nobody
|
|
81
|
+
* resends blind (a push resent onto its own landed head reverts as stale).
|
|
82
|
+
*/
|
|
83
|
+
async function confirmTx(publicClient, hash, what, gasLimit) {
|
|
84
|
+
let replaced;
|
|
85
|
+
let receipt;
|
|
86
|
+
try {
|
|
87
|
+
receipt = await publicClient.waitForTransactionReceipt({
|
|
88
|
+
hash,
|
|
89
|
+
onReplaced: (r) => {
|
|
90
|
+
replaced = {
|
|
91
|
+
reason: r.reason,
|
|
92
|
+
hash: r.transactionReceipt.transactionHash
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
} catch (err) {
|
|
97
|
+
if (err instanceof WaitForTransactionReceiptTimeoutError) throw new Error(`${what}: tx ${hash} was not confirmed in time. It may still land — re-read the chain before retrying.`, { cause: err });
|
|
98
|
+
throw err;
|
|
99
|
+
}
|
|
100
|
+
if (replaced && replaced.reason !== "repriced") throw new Error(`${what}: tx ${hash} was ${replaced.reason} by tx ${replaced.hash} (another transaction took its nonce); it did not take effect`);
|
|
101
|
+
const mined = replaced?.hash ?? hash;
|
|
102
|
+
if (receipt.status !== "success") throw new Error(`${what} reverted in tx ${mined}` + (gasLimit === void 0 ? "" : ` (gasUsed ${String(receipt.gasUsed)} of ${String(gasLimit)})`));
|
|
103
|
+
return {
|
|
104
|
+
receipt,
|
|
105
|
+
hash: mined
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* A call to the zero address (an undeployed network's placeholder) runs no code, so
|
|
110
|
+
* it estimates, mines and reports success while doing nothing.
|
|
111
|
+
*/
|
|
112
|
+
function assertDeployed(address, functionName) {
|
|
113
|
+
if (address.toLowerCase() === zeroAddress) throw new Error(`${functionName}: the contract address is the zero address — this network's contract is not deployed (or not configured)`);
|
|
49
114
|
}
|
|
50
115
|
/** Guard for clients that accept a read-only construction. */
|
|
51
116
|
function requireWallet(walletClient, what) {
|
|
@@ -69,6 +134,7 @@ function requireWallet(walletClient, what) {
|
|
|
69
134
|
* approval); `fallbackGas` is then the gas, as it is when the RPC fails.
|
|
70
135
|
*/
|
|
71
136
|
async function prepareWrite(publicClient, from, address, abi, functionName, args, opts) {
|
|
137
|
+
assertDeployed(address, functionName);
|
|
72
138
|
const data = encodeFunctionData({
|
|
73
139
|
abi,
|
|
74
140
|
functionName,
|
|
@@ -99,4 +165,4 @@ async function prepareWrite(publicClient, from, address, abi, functionName, args
|
|
|
99
165
|
}
|
|
100
166
|
|
|
101
167
|
//#endregion
|
|
102
|
-
export { prepareWrite, requireWallet, sendWrite };
|
|
168
|
+
export { APPEND_ALLOWANCE, confirmTx, prepareWrite, requireWallet, sendWrite };
|
package/lib/crypto/encryption.js
CHANGED
|
@@ -41,6 +41,9 @@ function seal(plaintext, recipientPubkey, resourceId) {
|
|
|
41
41
|
/** Inverse of {@link seal}, with the recipient's secret and the same resourceId. */
|
|
42
42
|
function unseal(ciphertext, recipientSecret, resourceId) {
|
|
43
43
|
const ephPub = ciphertext.slice(0, X25519_PUBKEY_LENGTH);
|
|
44
|
+
let u = 0n;
|
|
45
|
+
for (let i = X25519_PUBKEY_LENGTH - 1; i >= 0; i--) u = u << 8n | BigInt(ephPub[i]);
|
|
46
|
+
if (u >= 2n ** 255n - 19n) throw new Error("non-canonical ephemeral public key");
|
|
44
47
|
const nonce = ciphertext.slice(X25519_PUBKEY_LENGTH, X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
|
|
45
48
|
const aesCt = ciphertext.slice(X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
|
|
46
49
|
return aesGcmDecrypt(hkdfSha256(x25519.getSharedSecret(recipientSecret, ephPub), void 0, sealInfo(resourceId), 32), aesCt, nonce);
|
package/lib/crypto/paid.d.ts
CHANGED
|
@@ -70,7 +70,7 @@ declare function sealField(p: {
|
|
|
70
70
|
/** `recordKey(id)` */
|
|
71
71
|
key: Hex;
|
|
72
72
|
field: string;
|
|
73
|
-
storage: Pick<MetadataStorage, "putFile"
|
|
73
|
+
storage: Pick<MetadataStorage, "putFile"> & Partial<Pick<MetadataStorage, "getRawBlock">>;
|
|
74
74
|
}): Promise<FieldHandle>;
|
|
75
75
|
/** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
|
|
76
76
|
declare const accessMessage: (stmt: Hex, key: Hex, readerKey: Hex, timestamp: number) => Hex;
|
package/lib/crypto/paid.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assertStoredFile } from "../providers/storage/types.js";
|
|
1
2
|
import { GCM_NONCE_LENGTH, aesGcmDecrypt, aesGcmEncrypt } from "./aes.js";
|
|
2
3
|
import { getRandomValues } from "./rand.js";
|
|
3
4
|
import { seal, unseal } from "./encryption.js";
|
|
@@ -77,11 +78,13 @@ function makeDeposit(p) {
|
|
|
77
78
|
async function sealField(p) {
|
|
78
79
|
const stmt = statement(p.scope);
|
|
79
80
|
const ct = encryptField(deriveRecordKey(p.kRepo, stmt, p.key), p.plaintext, stmt, p.key, p.field);
|
|
81
|
+
const cid = await p.storage.putFile(ct, `${p.key}.${p.field}`);
|
|
82
|
+
await assertStoredFile(cid, ct, p.storage);
|
|
80
83
|
return {
|
|
81
84
|
"@type": "handle",
|
|
82
85
|
gadget: GADGET_FIELD_V1,
|
|
83
86
|
generation: p.scope.generation.toString(),
|
|
84
|
-
cid
|
|
87
|
+
cid
|
|
85
88
|
};
|
|
86
89
|
}
|
|
87
90
|
/** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
|
package/lib/engine/index.d.ts
CHANGED
|
@@ -46,6 +46,11 @@ interface RepoDiff {
|
|
|
46
46
|
* rejecting garbage input early.
|
|
47
47
|
*/
|
|
48
48
|
declare const MAX_REPO_NAME_LENGTH = 256;
|
|
49
|
+
/**
|
|
50
|
+
* Every this many positions, a commit's CAR holds the whole state (see `checkpoint`), so a
|
|
51
|
+
* cold read walks back at most this many CARs (~2 fetches each: under Workers' 1000 subrequests).
|
|
52
|
+
*/
|
|
53
|
+
declare const CHECKPOINT_EVERY = 100;
|
|
49
54
|
/**
|
|
50
55
|
* The root of the graph, committed to IPFS, as hex
|
|
51
56
|
*/
|
|
@@ -63,7 +68,10 @@ interface SignedUpdate {
|
|
|
63
68
|
}
|
|
64
69
|
/** The CID a storage backend returned for a file, with or without an `ipfs://` prefix. */
|
|
65
70
|
declare function fileCid(uri: string): CID;
|
|
66
|
-
/**
|
|
71
|
+
/**
|
|
72
|
+
* Repos must be non-empty, well-formed strings whose length does not exceed MAX_REPO_NAME_LENGTH.
|
|
73
|
+
* Well-formed: a lone UTF-16 surrogate encodes as U+FFFD, so two such names would be one repo on chain.
|
|
74
|
+
*/
|
|
67
75
|
declare function assertValidRepoName(repo: RepoName): void;
|
|
68
76
|
/** One line of a commit's diff against its parent. */
|
|
69
77
|
interface CommitDiff {
|
|
@@ -93,6 +101,13 @@ interface CreateCommitOptions {
|
|
|
93
101
|
* deletes apply on top of the parent state.
|
|
94
102
|
*/
|
|
95
103
|
replace?: boolean;
|
|
104
|
+
/**
|
|
105
|
+
* Pack the whole state (every MST node and live record) into this commit's CAR, not just
|
|
106
|
+
* the delta. `getBlock` walks back one CAR per commit, so this caps how far it goes.
|
|
107
|
+
* ponytail: a full copy of the repo every CHECKPOINT_EVERY commits; a block → commit
|
|
108
|
+
* index would avoid it if big repos make that costly.
|
|
109
|
+
*/
|
|
110
|
+
checkpoint?: boolean;
|
|
96
111
|
}
|
|
97
112
|
declare class FangornEngine {
|
|
98
113
|
private storage;
|
|
@@ -202,7 +217,11 @@ declare class FangornEngine {
|
|
|
202
217
|
* chain or a commit from before diff events, it diffs the two trees (`diffMst`). Either way the
|
|
203
218
|
* result is the net delta an index builder needs: what to (re)embed, what to evict.
|
|
204
219
|
*/
|
|
205
|
-
repoDiff(oldRootHex: string | null, newRootHex: string
|
|
220
|
+
repoDiff(oldRootHex: string | null, newRootHex: string, {
|
|
221
|
+
useEventDiff
|
|
222
|
+
}?: {
|
|
223
|
+
useEventDiff?: boolean | undefined;
|
|
224
|
+
}): Promise<RepoDiff>;
|
|
206
225
|
/** Diff a commit against its parent: its event's diff, or two full states for an older commit. */
|
|
207
226
|
diffCommit(commitCid: CID): Promise<CommitDiff>;
|
|
208
227
|
/** A stitch to the current head of (publisher, repo), at `key` if given. One `getHead` read, no logs. */
|
|
@@ -268,9 +287,9 @@ declare class FangornEngine {
|
|
|
268
287
|
listAt(head: CID | null): Promise<RepoContents>;
|
|
269
288
|
/**
|
|
270
289
|
* Fetch the current version of one record by id — one MST path from the
|
|
271
|
-
* on-chain root, then the record block. Null if the repo has no such id.
|
|
290
|
+
* on-chain root, then the record block. Null if the repo has no such id, or no commits.
|
|
272
291
|
*/
|
|
273
292
|
readRecord(publisher: Address, repo: RepoName, id: string): Promise<StoredRecord | null>;
|
|
274
293
|
}
|
|
275
294
|
//#endregion
|
|
276
|
-
export { CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordType, type Ref, RepoContents, RepoDiff, RepoName, SignedUpdate, type Stitch, StoredRecord, assertValidRepoName, cidFromDigest, commitHead, commitUpdate, fileCid, rootHexFromCid };
|
|
295
|
+
export { CHECKPOINT_EVERY, CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordType, type Ref, RepoContents, RepoDiff, RepoName, SignedUpdate, type Stitch, StoredRecord, assertValidRepoName, cidFromDigest, commitHead, commitUpdate, fileCid, rootHexFromCid };
|