@arkiv-network/sdk 0.7.0-dev.1 → 0.8.0-advanced.2

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 (237) hide show
  1. package/README.md +71 -16
  2. package/dist/actions/advanced/index.cjs +13 -0
  3. package/dist/actions/advanced/index.d.cts +8 -0
  4. package/dist/actions/advanced/index.d.ts +9 -0
  5. package/dist/actions/advanced/index.js +9 -0
  6. package/dist/advanced-8ZPTmmaN.js +598 -0
  7. package/dist/advanced-8ZPTmmaN.js.map +1 -0
  8. package/dist/advanced-fPImL6lW.cjs +656 -0
  9. package/dist/arkivTransactions-D74gERHG.d.cts +571 -0
  10. package/dist/arkivTransactions-D74gERHG.d.cts.map +1 -0
  11. package/dist/arkivTransactions-NtGD6uk5.d.ts +571 -0
  12. package/dist/arkivTransactions-NtGD6uk5.d.ts.map +1 -0
  13. package/dist/attr/index.cjs +35 -0
  14. package/dist/attr/index.d.cts +2 -0
  15. package/dist/attr/index.d.ts +3 -0
  16. package/dist/attr/index.js +4 -0
  17. package/dist/attributes-BhY5DwJp.js +809 -0
  18. package/dist/attributes-BhY5DwJp.js.map +1 -0
  19. package/dist/attributes-Df9IsCVs.cjs +1029 -0
  20. package/dist/chains/index.cjs +2 -3
  21. package/dist/chains/index.d.cts +22 -60
  22. package/dist/chains/index.d.cts.map +1 -1
  23. package/dist/chains/index.d.ts +22 -60
  24. package/dist/chains/index.d.ts.map +1 -1
  25. package/dist/chains/index.js +2 -2
  26. package/dist/chains-BJrZs6sG.js +57 -0
  27. package/dist/chains-BJrZs6sG.js.map +1 -0
  28. package/dist/chains-BYRTTipa.cjs +73 -0
  29. package/dist/codec-Car3KkFF.d.ts +102 -0
  30. package/dist/codec-Car3KkFF.d.ts.map +1 -0
  31. package/dist/entity/index.cjs +20 -0
  32. package/dist/entity/index.d.cts +4 -0
  33. package/dist/entity/index.d.ts +5 -0
  34. package/dist/entity/index.js +7 -0
  35. package/dist/entity-B00Li04j.cjs +71 -0
  36. package/dist/entity-B7G8q_Eo.cjs +0 -0
  37. package/dist/entity-BYQR1uoe.js +67 -0
  38. package/dist/entity-BYQR1uoe.js.map +1 -0
  39. package/dist/entity-CD_qFF2M.js +0 -0
  40. package/dist/errors-BVbjKVMN.cjs +56 -0
  41. package/dist/errors-LTe7bOYS.js +33 -0
  42. package/dist/errors-LTe7bOYS.js.map +1 -0
  43. package/dist/expiry-BELY2Kpw.cjs +135 -0
  44. package/dist/expiry-BjpxZZQU.js +95 -0
  45. package/dist/expiry-BjpxZZQU.js.map +1 -0
  46. package/dist/expiry-DRV29F1r.d.cts +79 -0
  47. package/dist/expiry-DRV29F1r.d.cts.map +1 -0
  48. package/dist/expiry-nDbCgZX4.d.ts +79 -0
  49. package/dist/expiry-nDbCgZX4.d.ts.map +1 -0
  50. package/dist/flags-5dTNRnow.d.ts +41 -0
  51. package/dist/flags-5dTNRnow.d.ts.map +1 -0
  52. package/dist/flags-CRjPpoh3.d.cts +41 -0
  53. package/dist/flags-CRjPpoh3.d.cts.map +1 -0
  54. package/dist/flags-DFBs2J94.js +33 -0
  55. package/dist/flags-DFBs2J94.js.map +1 -0
  56. package/dist/flags-kr276q6i.cjs +43 -0
  57. package/dist/index-B5j76711.d.ts +184 -0
  58. package/dist/index-B5j76711.d.ts.map +1 -0
  59. package/dist/index-BF7Mq9Is.d.cts +280 -0
  60. package/dist/index-BF7Mq9Is.d.cts.map +1 -0
  61. package/dist/index-CA4V7Pdh.d.cts +167 -0
  62. package/dist/index-CA4V7Pdh.d.cts.map +1 -0
  63. package/dist/index-CV5zCdpa.d.cts +417 -0
  64. package/dist/index-CV5zCdpa.d.cts.map +1 -0
  65. package/dist/index-DHDud2hC.d.ts +280 -0
  66. package/dist/index-DHDud2hC.d.ts.map +1 -0
  67. package/dist/index-DvYvrkdk.d.ts +320 -0
  68. package/dist/index-DvYvrkdk.d.ts.map +1 -0
  69. package/dist/index-EeUO0nnJ.d.cts +184 -0
  70. package/dist/index-EeUO0nnJ.d.cts.map +1 -0
  71. package/dist/index-fX_XyqLp.d.ts +167 -0
  72. package/dist/index-fX_XyqLp.d.ts.map +1 -0
  73. package/dist/index.cjs +411 -405
  74. package/dist/index.d.cts +360 -209
  75. package/dist/index.d.cts.map +1 -1
  76. package/dist/index.d.ts +361 -209
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +342 -387
  79. package/dist/index.js.map +1 -1
  80. package/dist/key-D1Bh7MF0.js +70 -0
  81. package/dist/key-D1Bh7MF0.js.map +1 -0
  82. package/dist/key-WKhXnXuU.cjs +98 -0
  83. package/dist/logger-CVpvU8ik.js +153 -0
  84. package/dist/logger-CVpvU8ik.js.map +1 -0
  85. package/dist/logger-Cr15lPAQ.cjs +188 -0
  86. package/dist/payload-BNoud2KZ.d.cts +94 -0
  87. package/dist/payload-BNoud2KZ.d.cts.map +1 -0
  88. package/dist/payload-Bz6651ax.js +67 -0
  89. package/dist/payload-Bz6651ax.js.map +1 -0
  90. package/dist/payload-CcUj85ys.d.ts +94 -0
  91. package/dist/payload-CcUj85ys.d.ts.map +1 -0
  92. package/dist/payload-KC14SDlN.cjs +83 -0
  93. package/dist/query/index.cjs +26 -150
  94. package/dist/query/index.d.cts +5 -3
  95. package/dist/query/index.d.ts +6 -3
  96. package/dist/query/index.js +8 -138
  97. package/dist/queryBuilder-DM6AWCBa.js +820 -0
  98. package/dist/queryBuilder-DM6AWCBa.js.map +1 -0
  99. package/dist/queryBuilder-DbUMEZln.cjs +944 -0
  100. package/dist/selection-C4UhsMOO.d.ts +434 -0
  101. package/dist/selection-C4UhsMOO.d.ts.map +1 -0
  102. package/dist/selection-DPg0uyJf.d.cts +433 -0
  103. package/dist/selection-DPg0uyJf.d.cts.map +1 -0
  104. package/dist/types/index.cjs +3 -3
  105. package/dist/types/index.d.cts +7 -2
  106. package/dist/types/index.d.ts +8 -2
  107. package/dist/types/index.js +3 -3
  108. package/dist/types-Bu_ZwMbZ.js +0 -0
  109. package/dist/types-NRqymi6S.cjs +0 -0
  110. package/dist/utils/index.cjs +4 -17
  111. package/dist/utils/index.d.cts +3 -17
  112. package/dist/utils/index.d.ts +3 -17
  113. package/dist/utils/index.js +4 -18
  114. package/package.json +26 -5
  115. package/src/actions/advanced/advanced.test.ts +258 -0
  116. package/src/actions/advanced/buildMutation.ts +104 -0
  117. package/src/actions/advanced/getMutationResult.ts +112 -0
  118. package/src/actions/advanced/index.ts +21 -0
  119. package/src/actions/advanced/pingTransaction.ts +43 -0
  120. package/src/actions/advanced/sendMutation.ts +59 -0
  121. package/src/actions/public/getEntity.ts +27 -43
  122. package/src/actions/public/getEntityNonce.ts +30 -0
  123. package/src/actions/public/predictEntityKeys.test.ts +143 -0
  124. package/src/actions/public/predictEntityKeys.ts +138 -0
  125. package/src/actions/public/query.ts +35 -67
  126. package/src/actions/public/watchEntityEvents.test.ts +414 -0
  127. package/src/actions/public/watchEntityEvents.ts +225 -0
  128. package/src/actions/wallet/changeOwnership.ts +2 -2
  129. package/src/actions/wallet/createEntity.ts +99 -24
  130. package/src/actions/wallet/extendEntity.ts +37 -13
  131. package/src/actions/wallet/mutateEntities.test.ts +76 -0
  132. package/src/actions/wallet/mutateEntities.ts +16 -33
  133. package/src/actions/wallet/patchEntity.ts +90 -0
  134. package/src/attr/attributes.test.ts +120 -0
  135. package/src/attr/attributes.ts +190 -0
  136. package/src/attr/codec.test.ts +162 -0
  137. package/src/attr/codec.ts +220 -0
  138. package/src/attr/decimal.ts +86 -0
  139. package/src/attr/errors.ts +145 -0
  140. package/src/attr/index.ts +50 -0
  141. package/src/attr/names.ts +106 -0
  142. package/src/attr/types.ts +150 -0
  143. package/src/attr/values.test.ts +271 -0
  144. package/src/attr/values.ts +502 -0
  145. package/src/chains/cheesecake.ts +22 -0
  146. package/src/chains/index.ts +1 -2
  147. package/src/clients/createPublicClient.test.ts +3 -5
  148. package/src/clients/createPublicClient.ts +5 -4
  149. package/src/clients/createWalletClient.test.ts +2 -2
  150. package/src/clients/createWalletClient.ts +13 -7
  151. package/src/clients/decorators/arkivAdvanced.ts +144 -0
  152. package/src/clients/decorators/arkivPublic.ts +172 -139
  153. package/src/clients/decorators/arkivWallet.ts +101 -94
  154. package/src/entity/create.test.ts +184 -0
  155. package/src/entity/errors.ts +38 -0
  156. package/src/entity/events.ts +16 -0
  157. package/src/entity/expiry.test.ts +195 -0
  158. package/src/entity/expiry.ts +181 -0
  159. package/src/entity/flags.ts +65 -0
  160. package/src/entity/index.ts +15 -0
  161. package/src/entity/key.ts +68 -0
  162. package/src/entity/operations.ts +134 -0
  163. package/src/entity/params.ts +15 -0
  164. package/src/errors.ts +26 -49
  165. package/src/index.ts +19 -0
  166. package/src/query/engine.ts +68 -137
  167. package/src/query/errors.ts +151 -0
  168. package/src/query/expression.test.ts +286 -0
  169. package/src/query/expression.ts +493 -0
  170. package/src/query/index.ts +40 -4
  171. package/src/query/injection.test.ts +151 -0
  172. package/src/query/queryBuilder.test.ts +342 -637
  173. package/src/query/queryBuilder.ts +133 -359
  174. package/src/query/queryResult.ts +54 -51
  175. package/src/query/selection.test.ts +48 -98
  176. package/src/query/selection.ts +77 -65
  177. package/src/types/entity.test.ts +44 -155
  178. package/src/types/entity.ts +60 -52
  179. package/src/types/events.ts +59 -16
  180. package/src/types/index.ts +20 -17
  181. package/src/types/rpcSchema.ts +69 -37
  182. package/src/utils/arkivTransactions.test.ts +600 -155
  183. package/src/utils/arkivTransactions.ts +350 -219
  184. package/src/utils/chains.test.ts +21 -24
  185. package/src/utils/compression.ts +1 -1
  186. package/src/utils/entities.test.ts +62 -0
  187. package/src/utils/entities.ts +109 -37
  188. package/src/utils/expirationTime.ts +114 -10
  189. package/src/utils/logger.ts +2 -2
  190. package/src/utils/revert.test.ts +99 -0
  191. package/src/utils/revert.ts +145 -0
  192. package/dist/chains-BifaY04V.cjs +0 -108
  193. package/dist/chains-CrtkVbBh.js +0 -86
  194. package/dist/chains-CrtkVbBh.js.map +0 -1
  195. package/dist/consts-Bz0LZQZY.js +0 -7
  196. package/dist/consts-Bz0LZQZY.js.map +0 -1
  197. package/dist/consts-CxT1-RXU.cjs +0 -18
  198. package/dist/entity-BhSXaB23.cjs +0 -81
  199. package/dist/entity-CN41IOrq.d.cts +0 -401
  200. package/dist/entity-CN41IOrq.d.cts.map +0 -1
  201. package/dist/entity-DGfVyB-a.js +0 -71
  202. package/dist/entity-DGfVyB-a.js.map +0 -1
  203. package/dist/entity-NnEVlePN.d.ts +0 -401
  204. package/dist/entity-NnEVlePN.d.ts.map +0 -1
  205. package/dist/index-ClkpS6s_.d.ts +0 -481
  206. package/dist/index-ClkpS6s_.d.ts.map +0 -1
  207. package/dist/index-w4qop0Pe.d.cts +0 -481
  208. package/dist/index-w4qop0Pe.d.cts.map +0 -1
  209. package/dist/payload-BpNUPOnY.js +0 -13
  210. package/dist/payload-BpNUPOnY.js.map +0 -1
  211. package/dist/payload-C2KHOUoj.d.ts +0 -6
  212. package/dist/payload-C2KHOUoj.d.ts.map +0 -1
  213. package/dist/payload-CJN8fTvX.d.cts +0 -6
  214. package/dist/payload-CJN8fTvX.d.cts.map +0 -1
  215. package/dist/payload-D8YLKcJj.cjs +0 -23
  216. package/dist/query/index.js.map +0 -1
  217. package/dist/queryBuilder-BE_XhLLa.js +0 -735
  218. package/dist/queryBuilder-BE_XhLLa.js.map +0 -1
  219. package/dist/queryBuilder-J37buGCi.cjs +0 -865
  220. package/dist/utils/index.d.cts.map +0 -1
  221. package/dist/utils/index.d.ts.map +0 -1
  222. package/dist/utils/index.js.map +0 -1
  223. package/src/actions/public/buildQuery.ts +0 -10
  224. package/src/actions/public/subscribeEntityEvents.ts +0 -93
  225. package/src/actions/wallet/updateEntity.ts +0 -59
  226. package/src/chains/braga.ts +0 -26
  227. package/src/chains/kaolin.ts +0 -29
  228. package/src/query/engine.test.ts +0 -571
  229. package/src/query/predicate.test.ts +0 -461
  230. package/src/query/predicate.ts +0 -144
  231. package/src/query/queryResult.test.ts +0 -270
  232. package/src/query/selectQueryBuilder.test.ts +0 -213
  233. package/src/types/attributes.ts +0 -28
  234. package/src/utils/validation.test.ts +0 -106
  235. package/src/utils/validation.ts +0 -80
  236. /package/dist/{types-Ci4BRClw.js → attr-DlmErkvR.cjs} +0 -0
  237. /package/dist/{types-a8gm_IaQ.cjs → attr-GcQKatub.js} +0 -0
package/dist/index.js CHANGED
@@ -1,10 +1,19 @@
1
- import { t as chains_exports } from "./chains-CrtkVbBh.js";
2
- import { S as getLogger, _ as InvalidContentTypeError, b as NoEntityFoundError, c as isEntityKey, d as entityFromRpcResult, f as RpcAttributeValueType, g as InvalidAttributeKeyError, h as InvalidAttributeError, l as validateAttribute, m as EntityMutationError, n as QueryBuilder, p as DuplicateAttributeError, r as SelectQueryBuilder, u as validateExpiresIn, v as InvalidExpirationError, x as NoMoreResultsError, y as NoCursorOrLimitError } from "./queryBuilder-BE_XhLLa.js";
3
- import { n as BLOCK_TIME, t as ARKIV_ADDRESS } from "./consts-Bz0LZQZY.js";
4
- import { n as EntityOperationType } from "./entity-DGfVyB-a.js";
5
- import "./types-Ci4BRClw.js";
6
- import { n as stringToPayload, t as jsonToPayload } from "./payload-BpNUPOnY.js";
7
- import { ContractFunctionExecutionError, ContractFunctionRevertedError, TransactionExecutionError, bytesToHex, createClient, decodeEventLog, encodePacked, hexToBytes, keccak256, numberToHex, parseAbi, publicActions, stringToBytes, toBytes, toHex, walletActions } from "viem";
1
+ import { t as chains_exports } from "./chains-BJrZs6sG.js";
2
+ import { a as OperationType, i as MAX_EXPIRES_AT, n as resolveExpiry, o as ARKIV_ADDRESS, r as toBlocks, s as BLOCK_TIME } from "./expiry-BjpxZZQU.js";
3
+ import { a as buildMutation, c as mutationNeedsBlockNumber, i as getMutationResult, l as sendArkivTransaction, n as pingTransaction, o as buildEntityOperations, r as decodeMutationResult, s as collectMutationEvents, t as sendMutation, u as ENTITY_NONCE_ABI } from "./advanced-8ZPTmmaN.js";
4
+ import { A as DECIMAL_UNIT, C as str, E as u64, F as TooManyAttributesError, I as UnknownAttributeTypeError, L as UntypedValueError, M as InvalidAttributeNameError, N as InvalidValueError, O as isArkivValue, P as MissingValueError, S as key, T as u256, _ as bytes32, a as MAX_NAME_BYTES, b as decUnits, d as I32_MIN, f as MAX_STRING_BYTES, g as bool, h as addr, j as ConflictingMutationError, k as DECIMAL_SCALE, m as U64_MAX, n as MAX_PAYLOAD_BYTES, o as isValidAttributeName, p as U256_MAX, s as validateAttributeName, t as MAX_ATTRIBUTES, u as I32_MAX, v as dec, w as toValue, x as i32, y as decFromUnits } from "./attributes-BhY5DwJp.js";
5
+ import { a as ENTITY_EVENTS_ABI, i as validateSalt, n as predictEntityKey, r as randomSalt, t as MAX_SALT } from "./key-D1Bh7MF0.js";
6
+ import { i as NoRandomSourceError, n as InvalidExpiryError, r as InvalidSaltError, t as InvalidCreationFlagsError } from "./errors-LTe7bOYS.js";
7
+ import { n as encodeCreationFlags, t as decodeCreationFlags } from "./flags-DFBs2J94.js";
8
+ import { a as NoEntityFoundError, i as InvalidContentTypeError, n as EmptyPatchError, o as NoMoreResultsError, r as EntityMutationError, t as getLogger } from "./logger-CVpvU8ik.js";
9
+ import "./attr-GcQKatub.js";
10
+ import { t as Entity } from "./entity-BYQR1uoe.js";
11
+ import { a as eq, r as toRpcSelect, t as SelectQueryBuilder, v as runQuery } from "./queryBuilder-DM6AWCBa.js";
12
+ import "./entity-CD_qFF2M.js";
13
+ import "./types-Bu_ZwMbZ.js";
14
+ import { n as stringToPayload, r as ExpirationTime, t as jsonToPayload } from "./payload-Bz6651ax.js";
15
+ import { createClient, decodeEventLog, publicActions, walletActions } from "viem";
16
+ import { getChainId, readContract } from "viem/actions";
8
17
 
9
18
  //#region src/actions/public/getBlockTiming.ts
10
19
  const logger$8 = getLogger("actions:public:get-block-timing");
@@ -23,33 +32,26 @@ async function getBlockTiming(client) {
23
32
 
24
33
  //#endregion
25
34
  //#region src/actions/public/getEntity.ts
26
- async function getEntity(client, key) {
27
- let bytes;
28
- try {
29
- bytes = hexToBytes(key);
30
- } catch {
31
- throw new Error(`Invalid key format: ${key}. Key must be a valid hex string.`);
32
- }
33
- if (bytes.length !== 32) throw new Error(`Invalid key length: ${bytes.length} bytes. Key must be 32 bytes (64 hex characters) long.`);
34
- const hexKey = bytesToHex(bytes);
35
- const result = await client.request({
36
- method: "arkiv_query",
37
- params: [`$key = ${hexKey}`, { includeData: {
38
- key: true,
39
- attributes: true,
40
- payload: true,
41
- contentType: true,
42
- expiration: true,
43
- owner: true,
44
- creator: true,
45
- createdAtBlock: true,
46
- lastModifiedAtBlock: true,
47
- transactionIndexInBlock: true,
48
- operationIndexInTransaction: true
49
- } }]
35
+ /**
36
+ * Reads one entity by key, with every field selected.
37
+ *
38
+ * Returns a {@link FullEntity} rather than an {@link Entity}: the selection is fixed at `"*"`, so
39
+ * every field is populated and none of them needs a `?` at the call site. The bare `Entity` type
40
+ * has every field optional because a `select()` result carries only what it asked for.
41
+ *
42
+ * @throws {InvalidValueError} If the key is not 32 bytes.
43
+ * @throws {NoEntityFoundError} If no live entity has that key — it never existed, or it was
44
+ * deleted or has expired.
45
+ */
46
+ async function getEntity(client, entityKey) {
47
+ const { entities } = await runQuery(client, {
48
+ query: eq("$key", key(entityKey)).toString(),
49
+ select: toRpcSelect("*"),
50
+ limit: 1
50
51
  });
51
- if (!result.data.length) throw new NoEntityFoundError();
52
- return await entityFromRpcResult(result.data[0]);
52
+ const entity = entities[0];
53
+ if (entity === void 0) throw new NoEntityFoundError(entityKey);
54
+ return entity;
53
55
  }
54
56
 
55
57
  //#endregion
@@ -62,355 +64,294 @@ async function getEntityCount(client) {
62
64
  }
63
65
 
64
66
  //#endregion
65
- //#region src/actions/public/query.ts
66
- async function query(client, query$1, queryOptions) {
67
- const rpcQueryOptions = {
68
- includeData: {
69
- key: true,
70
- payload: queryOptions?.includeData?.payload ?? true,
71
- attributes: queryOptions?.includeData?.attributes ?? false,
72
- contentType: queryOptions?.includeData?.metadata ?? false,
73
- expiration: queryOptions?.includeData?.metadata ?? false,
74
- owner: queryOptions?.includeData?.metadata ?? false,
75
- creator: queryOptions?.includeData?.metadata ?? false,
76
- createdAtBlock: queryOptions?.includeData?.metadata ?? false,
77
- lastModifiedAtBlock: queryOptions?.includeData?.metadata ?? false,
78
- transactionIndexInBlock: queryOptions?.includeData?.metadata ?? false,
79
- operationIndexInTransaction: queryOptions?.includeData?.metadata ?? false
80
- },
81
- ...queryOptions?.atBlock !== void 0 && { atBlock: numberToHex(queryOptions.atBlock) },
82
- ...queryOptions?.orderBy && { orderBy: queryOptions?.orderBy.map((order) => ({
83
- name: order.name,
84
- type: order.type,
85
- desc: order.desc === "desc"
86
- })) },
87
- ...queryOptions?.resultsPerPage !== void 0 && { resultsPerPage: numberToHex(queryOptions.resultsPerPage) },
88
- ...queryOptions?.cursor !== void 0 && { cursor: queryOptions?.cursor }
89
- };
90
- const result = await client.request({
91
- method: "arkiv_query",
92
- params: [query$1, rpcQueryOptions]
67
+ //#region src/actions/public/getEntityNonce.ts
68
+ const logger$7 = getLogger("actions:public:get-entity-nonce");
69
+ /**
70
+ * Reads an owner's entity-minting nonce — how many entities that account has created.
71
+ *
72
+ * This is not the account's transaction nonce. The engine keeps a separate counter per creator and
73
+ * mixes it into every key it mints, which is what makes two identical creates from one account land
74
+ * on different keys.
75
+ *
76
+ * @param owner - The account whose nonce to read.
77
+ * @returns The number of entities `owner` has created so far, which is the nonce its next create
78
+ * will use.
79
+ */
80
+ async function getEntityNonce(client, owner) {
81
+ const nonce = await readContract(client, {
82
+ address: ARKIV_ADDRESS,
83
+ abi: ENTITY_NONCE_ABI,
84
+ functionName: "entityNonce",
85
+ args: [owner]
93
86
  });
94
- return {
95
- entities: await Promise.all(result.data.map((entity) => entityFromRpcResult(entity))),
96
- cursor: result.cursor,
97
- blockNumber: BigInt(result.blockNumber)
98
- };
87
+ logger$7("entity nonce of %s is %s", owner, nonce);
88
+ return nonce;
99
89
  }
100
90
 
101
91
  //#endregion
102
- //#region src/utils/arkivTransactions.ts
103
- const logger$7 = getLogger("utils:arkiv-transactions");
104
- const MIME_REGEX = /^[a-z][a-z0-9!#$&\-^_]*\/[a-z0-9][a-z0-9!#$&\-^_.+]*$/;
105
- function validateContentType(contentType) {
106
- if (!MIME_REGEX.test(contentType)) throw new InvalidContentTypeError(contentType);
107
- }
108
- const ENTITY_EXECUTE_ABI = parseAbi(["function execute((uint8 operationType, bytes32 entityKey, bytes payload, (bytes32[4] data) contentType, (bytes32 name, uint8 valueType, bytes32[4] value)[] attributes, uint32 expiresIn, address newOwner)[] ops) external"]);
109
- const ENTITY_OPERATION_EVENT_ABI = parseAbi(["event EntityOperation(bytes32 indexed entityKey, uint8 indexed operationType, address indexed owner, uint32 expiresAt, bytes32 entityHash)"]);
110
- const ENTITY_ERRORS_ABI = parseAbi([
111
- "error EmptyBatch()",
112
- "error AttributesNotSorted()",
113
- "error InvalidValueType(bytes32 name, uint8 valueType)",
114
- "error InvalidOpType(uint8 operationType)",
115
- "error ExpiryInPast(uint32 expiresAt, uint32 currentBlock)",
116
- "error TooManyAttributes(uint256 count, uint256 maxCount)",
117
- "error EntityNotFound(bytes32 entityKey)",
118
- "error NotOwner(bytes32 entityKey, address caller, address owner)",
119
- "error EntityExpired(bytes32 entityKey, uint32 expiresAt)",
120
- "error ExpiryNotExtended(bytes32 entityKey, uint32 newExpiresAt, uint32 currentExpiresAt)",
121
- "error TransferToZeroAddress(bytes32 entityKey)",
122
- "error TransferToSelf(bytes32 entityKey)",
123
- "error EntityNotExpired(bytes32 entityKey, uint32 expiresAt)",
124
- "error Ident32Empty()",
125
- "error Ident32TooLong(uint256 length)",
126
- "error Ident32InvalidByte(uint256 position, bytes1 value)",
127
- "error MimeEmpty()",
128
- "error MimeTooLong(uint256 length, uint256 maxLength)",
129
- "error MimeInvalidByte(uint256 position, bytes1 value)",
130
- "error MimeIncomplete()"
131
- ]);
132
- const EXECUTE_ABI = [...ENTITY_EXECUTE_ABI, ...ENTITY_ERRORS_ABI];
133
- const ENTITY_NONCE_ABI = parseAbi(["function nonces(address owner) view returns (uint32)"]);
134
- const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
135
- const ZERO_32 = `0x${"00".repeat(32)}`;
136
- const EMPTY_BYTES128 = [
137
- ZERO_32,
138
- ZERO_32,
139
- ZERO_32,
140
- ZERO_32
141
- ];
142
- function encodeBytes128(data) {
143
- const padded = new Uint8Array(128);
144
- padded.set(data.slice(0, 128));
145
- return [
146
- toHex(padded.slice(0, 32)),
147
- toHex(padded.slice(32, 64)),
148
- toHex(padded.slice(64, 96)),
149
- toHex(padded.slice(96, 128))
150
- ];
151
- }
152
- function encodeMime128(contentType) {
153
- return { data: contentType ? encodeBytes128(stringToBytes(contentType)) : EMPTY_BYTES128 };
92
+ //#region src/actions/public/predictEntityKeys.ts
93
+ /**
94
+ * Works out the keys an account's next creates will be given, before sending them.
95
+ *
96
+ * A key is `keccak256(chainId ++ registry ++ owner ++ nonce ++ salt)`. Everything but the nonce is
97
+ * known to the caller, and the nonce is read here — so a batch can reference a key it is about to
98
+ * mint, storing it as a `key` attribute on a sibling entity created in the same transaction.
99
+ *
100
+ * Each key arrives paired with its salt, and the create must be given that salt: a create left to
101
+ * pick its own salt picks a random one, which mints a different key.
102
+ *
103
+ * The prediction is valid only while nothing else from this owner is in flight. Every create that
104
+ * lands first takes the nonce with it and moves these keys. For a key you can rely on
105
+ * unconditionally, read it back from the create instead — `createEntity` and `mutateEntities`
106
+ * report the keys the engine actually minted.
107
+ *
108
+ * @param parameters - Owner, and either a count or the salts. {@link PredictEntityKeysParameters}
109
+ * @returns One `{ key, salt }` pair per create, in batch order. {@link PredictEntityKeysReturnType}
110
+ *
111
+ * @example A batch whose second entity points at its first.
112
+ * import { key } from "@arkiv-network/sdk/attr"
113
+ *
114
+ * const [parent, child] = await client.predictEntityKeys({ owner: account.address, count: 2 })
115
+ * await wallet.mutateEntities({
116
+ * creates: [
117
+ * { payload, contentType, expires, salt: parent.salt },
118
+ * {
119
+ * payload,
120
+ * contentType,
121
+ * expires,
122
+ * salt: child.salt,
123
+ * attributes: { parent: key(parent.key) },
124
+ * },
125
+ * ],
126
+ * })
127
+ */
128
+ async function predictEntityKeys(client, { owner, count, salts }) {
129
+ const resolvedSalts = resolveSalts(count, salts);
130
+ const chainId = client.chain?.id ?? await getChainId(client);
131
+ const nonce = await getEntityNonce(client, owner);
132
+ return resolvedSalts.map((salt, index) => ({
133
+ key: predictEntityKey({
134
+ owner,
135
+ nonce: nonce + BigInt(index),
136
+ salt,
137
+ chainId
138
+ }),
139
+ salt
140
+ }));
154
141
  }
155
- function encodeAttribute(attr) {
156
- validateAttribute(attr);
157
- const name = toHex(attr.key, { size: 32 });
158
- if (typeof attr.value === "string") {
159
- if (isEntityKey(attr.value)) return {
160
- name,
161
- valueType: RpcAttributeValueType.EntityKey,
162
- value: [
163
- toHex(toBytes(attr.value), { size: 32 }),
164
- ZERO_32,
165
- ZERO_32,
166
- ZERO_32
167
- ]
168
- };
169
- return {
170
- name,
171
- valueType: RpcAttributeValueType.String,
172
- value: encodeBytes128(stringToBytes(attr.value))
173
- };
142
+ /** The salts to derive from: the ones given, or `count` fresh random ones. */
143
+ function resolveSalts(count, salts) {
144
+ if (salts !== void 0) {
145
+ if (salts.length === 0) throw new Error("predictEntityKeys: `salts` is empty — there is nothing to predict");
146
+ return salts.map(validateSalt);
174
147
  }
175
- return {
176
- name,
177
- valueType: RpcAttributeValueType.Uint,
178
- value: [
179
- toHex(BigInt(attr.value), { size: 32 }),
180
- ZERO_32,
181
- ZERO_32,
182
- ZERO_32
183
- ]
184
- };
185
- }
186
- function encodeAttributes(attrs) {
187
- const encoded = attrs.map((attr) => ({
188
- key: attr.key,
189
- ...encodeAttribute(attr)
190
- })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
191
- for (let i = 1; i < encoded.length; i++) if (encoded[i].name === encoded[i - 1].name) throw new DuplicateAttributeError(encoded[i].key);
192
- return encoded.map(({ key: _,...attr }) => attr);
148
+ if (count === void 0) throw new Error("predictEntityKeys: pass either `count` or `salts`");
149
+ if (!Number.isInteger(count) || count <= 0) throw new Error(`predictEntityKeys: \`count\` must be a positive whole number, got ${count}`);
150
+ return Array.from({ length: count }, () => randomSalt());
193
151
  }
194
- function toBTL(expiresIn) {
195
- validateExpiresIn(expiresIn);
196
- return Math.ceil(expiresIn / BLOCK_TIME);
197
- }
198
- function deriveEntityKey(chainId, owner, nonce) {
199
- return keccak256(encodePacked([
200
- "uint256",
201
- "address",
202
- "address",
203
- "uint32"
204
- ], [
205
- BigInt(chainId),
206
- ARKIV_ADDRESS,
207
- owner,
208
- Number(nonce)
209
- ]));
210
- }
211
- async function sendArkivTransaction(client, ops, txParams) {
212
- if (!client.account) throw new Error("Account required");
213
- if (!client.chain) throw new Error("Chain required");
214
- const walletClient = client;
215
- const { creates, updates, deletes, extensions, ownershipChanges } = ops;
216
- const owner = client.account.address;
217
- const ownerNonce = creates?.length ? BigInt(await walletClient.readContract({
218
- address: ARKIV_ADDRESS,
219
- abi: ENTITY_NONCE_ABI,
220
- functionName: "nonces",
221
- args: [owner]
222
- })) : 0n;
223
- const createdEntityKeys = (creates ?? []).map((_, i) => deriveEntityKey(client.chain.id, owner, ownerNonce + BigInt(i)));
224
- for (const item of creates ?? []) validateContentType(item.contentType);
225
- for (const item of updates ?? []) validateContentType(item.contentType);
226
- const operations = [
227
- ...(creates ?? []).map((item, i) => ({
228
- operationType: EntityOperationType.Create,
229
- entityKey: createdEntityKeys[i],
230
- payload: toHex(item.payload),
231
- contentType: encodeMime128(item.contentType),
232
- attributes: encodeAttributes(item.attributes),
233
- expiresIn: toBTL(item.expiresIn),
234
- newOwner: ZERO_ADDRESS
235
- })),
236
- ...(updates ?? []).map((item) => ({
237
- operationType: EntityOperationType.Update,
238
- entityKey: item.entityKey,
239
- payload: toHex(item.payload),
240
- contentType: encodeMime128(item.contentType),
241
- attributes: encodeAttributes(item.attributes),
242
- expiresIn: 0,
243
- newOwner: ZERO_ADDRESS
244
- })),
245
- ...(deletes ?? []).map((item) => ({
246
- operationType: EntityOperationType.Delete,
247
- entityKey: item.entityKey,
248
- payload: "0x",
249
- contentType: encodeMime128(""),
250
- attributes: [],
251
- expiresIn: 0,
252
- newOwner: ZERO_ADDRESS
253
- })),
254
- ...(extensions ?? []).map((item) => ({
255
- operationType: EntityOperationType.Extend,
256
- entityKey: item.entityKey,
257
- payload: "0x",
258
- contentType: encodeMime128(""),
259
- attributes: [],
260
- expiresIn: toBTL(item.expiresIn),
261
- newOwner: ZERO_ADDRESS
262
- })),
263
- ...(ownershipChanges ?? []).map((item) => ({
264
- operationType: EntityOperationType.Transfer,
265
- entityKey: item.entityKey,
266
- payload: "0x",
267
- contentType: encodeMime128(""),
268
- attributes: [],
269
- expiresIn: 0,
270
- newOwner: item.newOwner
271
- }))
272
- ];
273
- logger$7("Sending execute with %d operations %s", operations.length, JSON.stringify(operations));
274
- try {
275
- const txHash = await walletClient.writeContract({
276
- address: ARKIV_ADDRESS,
277
- abi: EXECUTE_ABI,
278
- functionName: "execute",
279
- args: [operations],
280
- account: client.account,
281
- chain: client.chain,
282
- ...txParams
283
- });
284
- const receipt = await walletClient.waitForTransactionReceipt({ hash: txHash });
285
- logger$7("Tx receipt %o", receipt);
286
- if (receipt.status === "reverted") {
287
- try {
288
- await walletClient.simulateContract({
289
- address: ARKIV_ADDRESS,
290
- abi: EXECUTE_ABI,
291
- functionName: "execute",
292
- args: [operations],
293
- account: client.account,
294
- chain: client.chain
295
- });
296
- } catch (err) {
297
- const error = err;
298
- const reason = error.shortMessage ?? error.cause?.details ?? "No reason provided by backend.";
299
- throw new EntityMutationError(`Transaction ${receipt.transactionHash} reverted. Reason: ${reason}`);
300
- }
301
- throw new EntityMutationError(`Transaction ${receipt.transactionHash} reverted. No reason provided by backend.`);
302
- }
303
- return {
304
- receipt,
305
- createdEntityKeys
306
- };
307
- } catch (error) {
308
- let message = "Transaction failed";
309
- if (error instanceof TransactionExecutionError) message += `: ${error.details}`;
310
- else if (error instanceof ContractFunctionExecutionError) {
311
- logger$7("Contract function execution error data:", error.shortMessage);
312
- if (error.cause instanceof ContractFunctionRevertedError) message += `: ${error.cause.message}`;
313
- else message += ": Execution error without revert data";
314
- } else if (error instanceof EntityMutationError) throw error;
315
- throw new EntityMutationError(message);
316
- }
152
+
153
+ //#endregion
154
+ //#region src/actions/public/query.ts
155
+ /**
156
+ * Runs a single query and returns one page, with no builder in between.
157
+ *
158
+ * Takes either an {@link Expression} or a raw query string. The string form is an escape hatch for
159
+ * a query built elsewhere — it goes to the node exactly as written, with none of the name, type or
160
+ * operator checks the expression combinators apply.
161
+ *
162
+ * @throws {QueryError} If the node rejects the query.
163
+ */
164
+ function query(client, query$1, options = {}) {
165
+ return runQuery(client, {
166
+ query: query$1.toString(),
167
+ select: toRpcSelect(options.select),
168
+ limit: options.limit,
169
+ cursor: options.cursor,
170
+ atBlock: options.atBlock
171
+ });
317
172
  }
318
173
 
319
174
  //#endregion
320
- //#region src/actions/public/subscribeEntityEvents.ts
321
- const logger$6 = getLogger("actions:public:subscribe-entity-events");
322
- const arkivABI = ENTITY_OPERATION_EVENT_ABI;
323
- async function subscribeEntityEvents(client, { onError, onEntityCreated, onEntityUpdated, onEntityDeleted, onEntityExpired, onEntityExpiresInExtended, onEntityOwnerChanged }, pollingInterval, fromBlock) {
324
- return client.watchEvent({
325
- pollingInterval: pollingInterval ?? 1e3,
326
- fromBlock,
327
- events: arkivABI,
175
+ //#region src/actions/public/watchEntityEvents.ts
176
+ const logger$6 = getLogger("actions:public:watch-entity-events");
177
+ /**
178
+ * How often to poll, when the caller does not say.
179
+ *
180
+ * Half a block: fast enough that an event is never a whole block stale, slow enough not to hammer
181
+ * the node. viem's own default is derived from a 12-second Ethereum block and is far too slow here.
182
+ */
183
+ const DEFAULT_POLLING_INTERVAL = BLOCK_TIME * 1e3 / 2;
184
+ /**
185
+ * Watches entity events, calling the handlers you pass as they arrive.
186
+ *
187
+ * Every event here is decoded from a log the Arkiv operation address emitted, and carries the
188
+ * block, transaction and log index it came from — so consuming them in order replays exactly what
189
+ * the engine did.
190
+ *
191
+ * @param parameters - Handlers and options. {@link WatchEntityEventsParameters}
192
+ * @returns A function that stops the watcher.
193
+ *
194
+ *
195
+ * @example
196
+ * import { createPublicClient } from "@arkiv-network/sdk"
197
+ * import { cheesecake } from "@arkiv-network/sdk/chains"
198
+ * import { http } from "viem"
199
+ *
200
+ * const client = createPublicClient({ chain: cheesecake, transport: http() })
201
+ *
202
+ * const unwatch = client.watchEntityEvents({
203
+ * onEntityCreated: ({ entityKey, owner, expiresAt }) =>
204
+ * console.log("created", entityKey, "by", owner, "until block", expiresAt),
205
+ * onEntityDeleted: ({ entityKey }) => console.log("deleted", entityKey),
206
+ * onError: (error) => console.error(error),
207
+ * })
208
+ *
209
+ * unwatch()
210
+ */
211
+ function watchEntityEvents(client, parameters) {
212
+ const { onEntityCreated, onEntityPatched, onExpiryExtended, onOwnershipTransferred, onEntityDeleted, onEvent, onError, fromBlock, pollingInterval = DEFAULT_POLLING_INTERVAL } = parameters;
213
+ const publicClient = client;
214
+ const reportError = onError ?? logToConsole;
215
+ function emit(event) {
216
+ deliver(onEvent, event);
217
+ switch (event.type) {
218
+ case "EntityCreated":
219
+ deliver(onEntityCreated, event);
220
+ break;
221
+ case "EntityPatched":
222
+ deliver(onEntityPatched, event);
223
+ break;
224
+ case "ExpiryExtended":
225
+ deliver(onExpiryExtended, event);
226
+ break;
227
+ case "OwnershipTransferred":
228
+ deliver(onOwnershipTransferred, event);
229
+ break;
230
+ case "EntityDeleted":
231
+ deliver(onEntityDeleted, event);
232
+ break;
233
+ }
234
+ }
235
+ /**
236
+ * Runs one handler, keeping its failure to itself.
237
+ *
238
+ * A handler that throws is the consumer's problem, not the watcher's: letting it escape would
239
+ * reject the poll, drop the rest of the batch, and take down every other handler with it.
240
+ */
241
+ function deliver(handler, event) {
242
+ if (handler === void 0) return;
243
+ try {
244
+ handler(event);
245
+ } catch (error) {
246
+ reportError(asError(error));
247
+ }
248
+ }
249
+ return publicClient.watchEvent({
250
+ address: ARKIV_ADDRESS,
251
+ events: ENTITY_EVENTS_ABI,
252
+ pollingInterval,
253
+ ...fromBlock !== void 0 && { fromBlock },
328
254
  onLogs: (logs) => {
329
- logger$6("logs from subscribeEntityEvents %o", logs);
255
+ logger$6("logs %o", logs);
330
256
  for (const log of logs) {
331
- const event = decodeEventLog({
332
- abi: arkivABI,
333
- topics: log.topics,
334
- data: log.data
335
- });
336
- logger$6("event from subscribeEntityEvents %o", event);
337
- if (event.eventName !== "EntityOperation") continue;
338
- const entityKey = event.args.entityKey;
339
- const owner = event.args.owner;
340
- const expiresAt = event.args.expiresAt;
341
- const entityHash = event.args.entityHash;
342
- switch (Number(event.args.operationType)) {
343
- case EntityOperationType.Create:
344
- onEntityCreated?.({
345
- entityKey,
346
- owner,
347
- expiresAt,
348
- entityHash
349
- });
350
- break;
351
- case EntityOperationType.Update:
352
- onEntityUpdated?.({
353
- entityKey,
354
- owner,
355
- expiresAt,
356
- entityHash
357
- });
358
- break;
359
- case EntityOperationType.Extend:
360
- onEntityExpiresInExtended?.({
361
- entityKey,
362
- owner,
363
- expiresAt,
364
- entityHash
365
- });
366
- break;
367
- case EntityOperationType.Transfer:
368
- onEntityOwnerChanged?.({
369
- entityKey,
370
- owner,
371
- entityHash
372
- });
373
- break;
374
- case EntityOperationType.Delete:
375
- onEntityDeleted?.({
376
- entityKey,
377
- owner
378
- });
379
- break;
380
- default:
381
- onEntityExpired?.({
382
- entityKey,
383
- owner
384
- });
385
- break;
257
+ if (log.blockNumber === null || log.transactionHash === null || log.logIndex === null) continue;
258
+ const context = {
259
+ blockNumber: log.blockNumber,
260
+ transactionHash: log.transactionHash,
261
+ logIndex: log.logIndex
262
+ };
263
+ let event;
264
+ try {
265
+ event = toEntityEvent(log.topics, log.data, context);
266
+ } catch (error) {
267
+ reportError(asError(error));
268
+ continue;
386
269
  }
270
+ emit(event);
387
271
  }
388
272
  },
389
- onError: (error) => {
390
- console.error("error from subscribeEntityEvents", error);
391
- onError?.(error);
392
- }
273
+ onError: (error) => reportError(error)
393
274
  });
394
275
  }
276
+ /** The fallback when no `onError` was given — see {@link WatchEntityEventsParameters.onError}. */
277
+ function logToConsole(error) {
278
+ console.error("watchEntityEvents error", error);
279
+ }
280
+ /** Handlers take an `Error`, and a `throw` can be anything. */
281
+ function asError(error) {
282
+ return error instanceof Error ? error : new Error(String(error));
283
+ }
284
+ /**
285
+ * Decodes one log into the {@link EntityEvent} it carries.
286
+ *
287
+ * @throws If the log does not decode against {@link ENTITY_EVENTS_ABI}.
288
+ */
289
+ function toEntityEvent(topics, data, context) {
290
+ const decoded = decodeEventLog({
291
+ abi: ENTITY_EVENTS_ABI,
292
+ topics,
293
+ data
294
+ });
295
+ switch (decoded.eventName) {
296
+ case "EntityCreated": return {
297
+ type: "EntityCreated",
298
+ ...context,
299
+ ...decoded.args,
300
+ creationFlags: decodeCreationFlags(decoded.args.creationFlags)
301
+ };
302
+ case "EntityPatched": return {
303
+ type: "EntityPatched",
304
+ ...context,
305
+ ...decoded.args
306
+ };
307
+ case "ExpiryExtended": return {
308
+ type: "ExpiryExtended",
309
+ ...context,
310
+ ...decoded.args
311
+ };
312
+ case "OwnershipTransferred": return {
313
+ type: "OwnershipTransferred",
314
+ ...context,
315
+ ...decoded.args
316
+ };
317
+ case "EntityDeleted": return {
318
+ type: "EntityDeleted",
319
+ ...context,
320
+ ...decoded.args
321
+ };
322
+ }
323
+ }
324
+
325
+ //#endregion
326
+ //#region src/clients/decorators/arkivAdvanced.ts
327
+ function publicAdvancedActions(client) {
328
+ return {
329
+ pingTransaction: (txHash) => pingTransaction(client, txHash),
330
+ getMutationResult: (txHash) => getMutationResult(client, txHash),
331
+ decodeMutationResult: (receipt) => decodeMutationResult(receipt)
332
+ };
333
+ }
334
+ function walletAdvancedActions(client) {
335
+ return {
336
+ ...publicAdvancedActions(client),
337
+ buildMutation: (data, options) => buildMutation(client, data, options),
338
+ sendMutation: (data, options) => sendMutation(client, data, options)
339
+ };
340
+ }
395
341
 
396
342
  //#endregion
397
343
  //#region src/clients/decorators/arkivPublic.ts
398
344
  function publicArkivActions(client) {
399
345
  return {
400
- getEntity: (key) => getEntity(client, key),
346
+ getEntity: (key$1) => getEntity(client, key$1),
401
347
  query: (rawQuery, queryOptions) => query(client, rawQuery, queryOptions),
402
- buildQuery: () => new QueryBuilder(client),
403
348
  select: (selection) => new SelectQueryBuilder(client, selection),
404
349
  getBlockTiming: () => getBlockTiming(client),
405
350
  getEntityCount: () => getEntityCount(client),
406
- subscribeEntityEvents: ({ onError, onEntityCreated, onEntityUpdated, onEntityDeleted, onEntityExpired, onEntityExpiresInExtended }, pollingInterval, fromBlock) => subscribeEntityEvents(client, {
407
- onError,
408
- onEntityCreated,
409
- onEntityUpdated,
410
- onEntityDeleted,
411
- onEntityExpired,
412
- onEntityExpiresInExtended
413
- }, pollingInterval, fromBlock)
351
+ getEntityNonce: (owner) => getEntityNonce(client, owner),
352
+ predictEntityKeys: (parameters) => predictEntityKeys(client, parameters),
353
+ watchEntityEvents: (parameters) => watchEntityEvents(client, parameters),
354
+ advanced: publicAdvancedActions(client)
414
355
  };
415
356
  }
416
357
 
@@ -421,25 +362,26 @@ function publicArkivActions(client) {
421
362
  *
422
363
  * - Docs: https://docs.arkiv.network/ts-sdk/clients/public
423
364
  *
424
- * A Public Client is an interface to "public" [Ethereum JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/), [Arkiv JSON-RPC API](https://docs.arkiv.network/json-rpc/), and [Braga JSON-RPC API](https://braga.holesky.arkiv.network/rpc) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).
365
+ * A Public Client is an interface to "public" [Ethereum JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/), [Arkiv JSON-RPC API](https://docs.arkiv.network/json-rpc/), and [Cheesecake JSON-RPC API](https://rpc.cheesecake.db-chain.devnet.gobas.me) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).
425
366
  *
426
367
  * @param parameters - Configuration object for the public client (chain, transport, etc.)
427
368
  * @returns A Arkiv Public Client. {@link PublicArkivClient}
428
369
  *
429
370
  * @example
430
- * import { createPublicClient, http } from 'arkiv'
431
- * import { braga } from 'arkiv/chains'
371
+ * import { createPublicClient } from "@arkiv-network/sdk"
372
+ * import { cheesecake } from "@arkiv-network/sdk/chains"
373
+ * import { http } from "viem"
432
374
  *
433
375
  * const client = createPublicClient({
434
- * chain: braga,
376
+ * chain: cheesecake,
435
377
  * transport: http(),
436
378
  * })
437
379
  */
438
380
  function createPublicClient(parameters) {
439
- const { key = "public", name = "Public Client" } = parameters;
381
+ const { key: key$1 = "public", name = "Public Client" } = parameters;
440
382
  return createClient({
441
383
  ...parameters,
442
- key,
384
+ key: key$1,
443
385
  name
444
386
  }).extend(publicActions).extend(publicArkivActions);
445
387
  }
@@ -462,11 +404,15 @@ async function changeOwnership(client, data, txParams) {
462
404
  const logger$4 = getLogger("actions:wallet:create-entity");
463
405
  async function createEntity(client, data, txParams) {
464
406
  logger$4("createEntity %o", data);
465
- const { receipt, createdEntityKeys } = await sendArkivTransaction(client, { creates: [data] }, txParams);
407
+ const { receipt, createdEntityKeys, createdExpiries } = await sendArkivTransaction(client, { creates: [data] }, txParams);
466
408
  logger$4("Receipt from createEntity %o", receipt);
409
+ const [entityKey] = createdEntityKeys;
410
+ const [expiresAt] = createdExpiries;
411
+ if (entityKey === void 0 || expiresAt === void 0) throw new EntityMutationError(`Transaction ${receipt.transactionHash} succeeded, but the receipt did not carry the expected entity key or expiry.`);
467
412
  return {
468
413
  txHash: receipt.transactionHash,
469
- entityKey: createdEntityKeys[0]
414
+ entityKey,
415
+ expiresAt
470
416
  };
471
417
  }
472
418
 
@@ -488,11 +434,14 @@ async function deleteEntity(client, data, txParams) {
488
434
  const logger$2 = getLogger("actions:wallet:extend-entity");
489
435
  async function extendEntity(client, data, txParams) {
490
436
  logger$2("extendEntity %o", data);
491
- const { receipt } = await sendArkivTransaction(client, { extensions: [data] }, txParams);
437
+ const { receipt, extendedExpiries } = await sendArkivTransaction(client, { extensions: [data] }, txParams);
492
438
  logger$2("Receipt from extendEntity %o", receipt);
439
+ const [expiresAt] = extendedExpiries;
440
+ if (expiresAt === void 0) throw new EntityMutationError(`Transaction ${receipt.transactionHash} succeeded, but the receipt did not carry the expected entity expiry.`);
493
441
  return {
494
442
  txHash: receipt.transactionHash,
495
- entityKey: data.entityKey
443
+ entityKey: data.entityKey,
444
+ expiresAt
496
445
  };
497
446
  }
498
447
 
@@ -500,13 +449,12 @@ async function extendEntity(client, data, txParams) {
500
449
  //#region src/actions/wallet/mutateEntities.ts
501
450
  const logger$1 = getLogger("actions:wallet:mutate-entities");
502
451
  async function mutateEntities(client, data, txParams) {
503
- if (!data.creates && !data.updates && !data.deletes && !data.extensions) throw new Error("No operations to perform");
504
452
  const { receipt, createdEntityKeys } = await sendArkivTransaction(client, data, txParams);
505
453
  logger$1("Receipt from mutateEntities %o", receipt);
506
454
  return {
507
455
  txHash: receipt.transactionHash,
508
456
  createdEntities: createdEntityKeys,
509
- updatedEntities: (data.updates ?? []).map((u) => u.entityKey),
457
+ patchedEntities: (data.patches ?? []).map((p) => p.entityKey),
510
458
  deletedEntities: (data.deletes ?? []).map((d) => d.entityKey),
511
459
  extendedEntities: (data.extensions ?? []).map((e) => e.entityKey),
512
460
  ownershipChanges: (data.ownershipChanges ?? []).map((o) => o.entityKey)
@@ -514,12 +462,12 @@ async function mutateEntities(client, data, txParams) {
514
462
  }
515
463
 
516
464
  //#endregion
517
- //#region src/actions/wallet/updateEntity.ts
518
- const logger = getLogger("actions:wallet:update-entity");
519
- async function updateEntity(client, data, txParams) {
520
- logger("updateEntity %o", data);
521
- const { receipt } = await sendArkivTransaction(client, { updates: [data] }, txParams);
522
- logger("Receipt from updateEntity %o", receipt);
465
+ //#region src/actions/wallet/patchEntity.ts
466
+ const logger = getLogger("actions:wallet:patch-entity");
467
+ async function patchEntity(client, data, txParams) {
468
+ logger("patchEntity %o", data);
469
+ const { receipt } = await sendArkivTransaction(client, { patches: [data] }, txParams);
470
+ logger("Receipt from patchEntity %o", receipt);
523
471
  return {
524
472
  txHash: receipt.transactionHash,
525
473
  entityKey: data.entityKey
@@ -531,47 +479,54 @@ async function updateEntity(client, data, txParams) {
531
479
  function walletArkivActions(client) {
532
480
  return {
533
481
  createEntity: (data, txParams) => createEntity(client, data, txParams),
534
- updateEntity: (data, txParams) => updateEntity(client, data, txParams),
482
+ patchEntity: (data, txParams) => patchEntity(client, data, txParams),
535
483
  deleteEntity: (data, txParams) => deleteEntity(client, data, txParams),
536
484
  extendEntity: (data, txParams) => extendEntity(client, data, txParams),
537
485
  changeOwnership: (data, txParams) => changeOwnership(client, data, txParams),
538
- mutateEntities: (data, txParams) => mutateEntities(client, data, txParams)
486
+ mutateEntities: (data, txParams) => mutateEntities(client, data, txParams),
487
+ advanced: walletAdvancedActions(client)
539
488
  };
540
489
  }
541
490
 
542
491
  //#endregion
543
492
  //#region src/clients/createWalletClient.ts
544
493
  /**
545
- * Creates a Public Client with a given [Transport](https://viem.sh/docs/clients/intro) configured for a [Chain](https://viem.sh/docs/clients/chains).
494
+ * Creates a Wallet Client with a given [Transport](https://viem.sh/docs/clients/intro) configured
495
+ * for a [Chain](https://viem.sh/docs/clients/chains) and an account.
546
496
  *
547
- * - Docs: https://docs.arkiv.network/ts-sdk/clients/public
497
+ * - Docs: https://docs.arkiv.network/ts-sdk/clients/wallet
548
498
  *
549
- * A Public Client is an interface to "public" [Ethereum JSON-RPC API](https://ethereum.org/en/developers/docs/apis/json-rpc/), [Arkiv JSON-RPC API](https://docs.arkiv.network/json-rpc/), and [Braga JSON-RPC API](https://braga.holesky.arkiv.network/rpc) methods such as retrieving block numbers, transactions, reading from smart contracts, etc through [Public Actions](/docs/actions/public/introduction).
499
+ * A Wallet Client signs and sends transactions, so it carries an `account` and exposes everything
500
+ * that mutates state — `createEntity`, `patchEntity`, `deleteEntity`, `extendEntity`,
501
+ * `changeOwnership` and `mutateEntities` — on top of the read actions a Public Client has.
550
502
  *
551
503
  * @param parameters - Configuration object for the wallet client (chain, transport, account, etc.)
552
504
  * @returns A Arkiv Wallet Client. {@link WalletArkivClient}
553
505
  *
554
506
  * @example
555
- * import { createPublicClient, http } from 'arkiv'
556
- * import { braga } from 'arkiv/chains'
507
+ * import { createWalletClient } from "@arkiv-network/sdk"
508
+ * import { cheesecake } from "@arkiv-network/sdk/chains"
509
+ * import { http } from "viem"
510
+ * import { privateKeyToAccount } from "viem/accounts"
557
511
  *
558
- * const client = createPublicClient({
559
- * chain: braga,
512
+ * const client = createWalletClient({
513
+ * chain: cheesecake,
560
514
  * transport: http(),
515
+ * account: privateKeyToAccount("0x..."),
561
516
  * })
562
517
  */
563
518
  function createWalletClient(parameters) {
564
- const { key = "wallet", name = "Wallet Client" } = parameters;
519
+ const { key: key$1 = "wallet", name = "Wallet Client" } = parameters;
565
520
  return createClient({
566
521
  ...parameters,
567
- key,
522
+ key: key$1,
568
523
  name
569
524
  }).extend(publicActions).extend(walletActions).extend(walletArkivActions);
570
525
  }
571
526
 
572
527
  //#endregion
573
528
  //#region src/utils/chains.ts
574
- const chainMap = new Map(Object.entries(chains_exports).map(([key, value]) => [key.toLowerCase(), value]));
529
+ const chainMap = new Map(Object.entries(chains_exports).map(([key$1, value]) => [key$1.toLowerCase(), value]));
575
530
  /**
576
531
  * Get a chain from its name
577
532
  * @param name - The name of the chain, case insensitive
@@ -585,5 +540,5 @@ function chainFromName(name) {
585
540
  }
586
541
 
587
542
  //#endregion
588
- export { DuplicateAttributeError, EntityMutationError, EntityOperationType, InvalidAttributeError, InvalidAttributeKeyError, InvalidContentTypeError, InvalidExpirationError, NoCursorOrLimitError, NoEntityFoundError, NoMoreResultsError, chainFromName, createPublicClient, createWalletClient, jsonToPayload, stringToPayload };
543
+ export { ConflictingMutationError, DECIMAL_SCALE, DECIMAL_UNIT, ENTITY_EVENTS_ABI, EmptyPatchError, Entity, EntityMutationError, ExpirationTime, I32_MAX, I32_MIN, InvalidAttributeNameError, InvalidContentTypeError, InvalidCreationFlagsError, InvalidExpiryError, InvalidSaltError, InvalidValueError, MAX_ATTRIBUTES, MAX_EXPIRES_AT, MAX_NAME_BYTES, MAX_PAYLOAD_BYTES, MAX_SALT, MAX_STRING_BYTES, MissingValueError, NoEntityFoundError, NoMoreResultsError, NoRandomSourceError, OperationType, TooManyAttributesError, U256_MAX, U64_MAX, UnknownAttributeTypeError, UntypedValueError, addr, bool, buildEntityOperations, buildMutation, bytes32, chainFromName, collectMutationEvents, createPublicClient, createWalletClient, dec, decFromUnits, decUnits, decodeCreationFlags, decodeMutationResult, encodeCreationFlags, getMutationResult, i32, isArkivValue, isValidAttributeName, jsonToPayload, key, mutationNeedsBlockNumber, pingTransaction, predictEntityKey, randomSalt, resolveExpiry, sendMutation, str, stringToPayload, toBlocks, toValue, u256, u64, validateAttributeName };
589
544
  //# sourceMappingURL=index.js.map