@latticexyz/world 2.2.22-26d2e3acd8fc0a0852f530e8e1574a68d2baa3d2 → 2.2.22-60085734145ea8db0b43084034bec9f8ea474dc4

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 (74) hide show
  1. package/dist/internal.d.ts +16 -2
  2. package/dist/internal.js +113 -45
  3. package/dist/internal.js.map +1 -1
  4. package/dist/node.js +61 -41
  5. package/dist/node.js.map +1 -1
  6. package/out/AccessManagementSystem.sol/AccessManagementSystem.json +1 -1
  7. package/out/AccessManagementSystemLib.sol/AccessManagementSystemLib.json +1 -1
  8. package/out/AccessManagementSystemLib.sol/_grantAccess_ResourceId_address.json +1 -1
  9. package/out/AccessManagementSystemLib.sol/_renounceOwnership_ResourceId.json +1 -1
  10. package/out/AccessManagementSystemLib.sol/_revokeAccess_ResourceId_address.json +1 -1
  11. package/out/AccessManagementSystemLib.sol/_transferOwnership_ResourceId_address.json +1 -1
  12. package/out/BalanceTransferSystem.sol/BalanceTransferSystem.json +1 -1
  13. package/out/BalanceTransferSystemLib.sol/BalanceTransferSystemLib.json +1 -1
  14. package/out/BalanceTransferSystemLib.sol/_transferBalanceToAddress_ResourceId_address_uint256.json +1 -1
  15. package/out/BalanceTransferSystemLib.sol/_transferBalanceToNamespace_ResourceId_ResourceId_uint256.json +1 -1
  16. package/out/BatchCall.t.sol/BatchCallTest.json +1 -1
  17. package/out/BatchCall.t.sol/TestSystem.json +1 -1
  18. package/out/BatchCallSystem.sol/BatchCallSystem.json +1 -1
  19. package/out/BatchCallSystemLib.sol/BatchCallSystemLib.json +1 -1
  20. package/out/BatchCallSystemLib.sol/_batchCallFrom_SystemCallFromDataArray.json +1 -1
  21. package/out/BatchCallSystemLib.sol/_batchCall_SystemCallDataArray.json +1 -1
  22. package/out/DelegationControl.sol/DelegationControl.json +1 -1
  23. package/out/DelegationControlMock.sol/DelegationControlMock.json +1 -1
  24. package/out/Factories.t.sol/FactoriesTest.json +1 -1
  25. package/out/IBaseWorld.sol/IBaseWorld.json +1 -1
  26. package/out/IWorldRegistrationSystem.sol/IWorldRegistrationSystem.json +1 -1
  27. package/out/InitModule.sol/InitModule.json +1 -1
  28. package/out/InitModule.t.sol/InitModuleTest.json +1 -1
  29. package/out/InitModule.t.sol/WorldMock.json +1 -1
  30. package/out/InitSystems.t.sol/LimitedCallContextTest.json +1 -1
  31. package/out/ModuleInstallationSystem.sol/ModuleInstallationSystem.json +1 -1
  32. package/out/ModuleInstallationSystemLib.sol/ModuleInstallationSystemLib.json +1 -1
  33. package/out/ModuleInstallationSystemLib.sol/_installModule_IModule_bytes.json +1 -1
  34. package/out/RegistrationSystem.sol/RegistrationSystem.json +1 -1
  35. package/out/RegistrationSystemLib.sol/RegistrationSystemLib.json +1 -1
  36. package/out/StoreRegistrationSystem.sol/StoreRegistrationSystem.json +1 -1
  37. package/out/StoreRegistrationSystemLib.sol/StoreRegistrationSystemLib.json +1 -1
  38. package/out/StoreRegistrationSystemLib.sol/_registerStoreHook_ResourceId_IStoreHook_uint8.json +1 -1
  39. package/out/StoreRegistrationSystemLib.sol/_registerTable_ResourceId_FieldLayout_Schema_Schema_stringArray_stringArray.json +1 -1
  40. package/out/StoreRegistrationSystemLib.sol/_unregisterStoreHook_ResourceId_IStoreHook.json +1 -1
  41. package/out/System.sol/System.json +1 -1
  42. package/out/System.t.sol/SystemTest.json +1 -1
  43. package/out/System.t.sol/TestSystem.json +1 -1
  44. package/out/Utils.t.sol/UtilsTest.json +1 -1
  45. package/out/Utils.t.sol/UtilsTestSystem.json +1 -1
  46. package/out/World.t.sol/EchoSystemHook.json +1 -1
  47. package/out/World.t.sol/IWorldTestSystem.json +1 -1
  48. package/out/World.t.sol/PayableFallbackSystem.json +1 -1
  49. package/out/World.t.sol/RevertSystemHook.json +1 -1
  50. package/out/World.t.sol/WorldTest.json +1 -1
  51. package/out/World.t.sol/WorldTestSystem.json +1 -1
  52. package/out/WorldBalance.t.sol/WorldBalanceTest.json +1 -1
  53. package/out/WorldBalance.t.sol/WorldBalanceTestSystem.json +1 -1
  54. package/out/WorldDynamicUpdate.t.sol/UpdateInDynamicFieldTest.json +1 -1
  55. package/out/WorldFactory.sol/WorldFactory.json +1 -1
  56. package/out/WorldProxy.sol/WorldProxy.json +1 -1
  57. package/out/WorldProxy.t.sol/WorldProxyTest.json +1 -1
  58. package/out/WorldProxyFactory.sol/WorldProxyFactory.json +1 -1
  59. package/out/WorldProxyFactory.t.sol/WorldProxyFactoryTest.json +1 -1
  60. package/out/WorldRegistrationSystem.sol/WorldRegistrationSystem.json +1 -1
  61. package/out/WorldRegistrationSystemLib.sol/WorldRegistrationSystemLib.json +1 -1
  62. package/out/WorldRegistrationSystemLib.sol/_registerDelegation_address_ResourceId_bytes.json +1 -1
  63. package/out/WorldRegistrationSystemLib.sol/_registerFunctionSelector_ResourceId_string.json +1 -1
  64. package/out/WorldRegistrationSystemLib.sol/_registerNamespaceDelegation_ResourceId_ResourceId_bytes.json +1 -1
  65. package/out/WorldRegistrationSystemLib.sol/_registerNamespace_ResourceId.json +1 -1
  66. package/out/WorldRegistrationSystemLib.sol/_registerRootFunctionSelector_ResourceId_string_string.json +1 -1
  67. package/out/WorldRegistrationSystemLib.sol/_registerSystemHook_ResourceId_ISystemHook_uint8.json +1 -1
  68. package/out/WorldRegistrationSystemLib.sol/_registerSystem_ResourceId_System_bool.json +1 -1
  69. package/out/WorldRegistrationSystemLib.sol/_unregisterDelegation_address.json +1 -1
  70. package/out/WorldRegistrationSystemLib.sol/_unregisterNamespaceDelegation_ResourceId.json +1 -1
  71. package/out/WorldRegistrationSystemLib.sol/_unregisterSystemHook_ResourceId_ISystemHook.json +1 -1
  72. package/out/build-info/{6366a746548e984842b93ef762b76b99.json → bf27acd14b2b959864c0abf4ffaa7965.json} +1 -1
  73. package/package.json +9 -9
  74. package/src/System.sol +1 -1
@@ -1,5 +1,6 @@
1
1
  import { Abi, ContractFunctionName, Hex, EncodeFunctionDataParameters, Address, Chain, Account, Client, Transport, WalletActions } from 'viem';
2
2
  import { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from 'abitype';
3
+ import { SmartAccount, BundlerActions } from 'viem/account-abstraction';
3
4
  export { C as CODEGEN_DEFAULTS, b as CONFIG_DEFAULTS, k as CodegenInput, D as DEPLOY_DEFAULTS, j as DeployInput, M as MODULE_DEFAULTS, i as ModuleInput, N as NamespaceInput, h as NamespacesInput, a as SYSTEM_DEFAULTS, S as SYSTEM_DEPLOY_DEFAULTS, e as SystemDeployInput, f as SystemInput, g as SystemsInput, V as ValidateSystemOptions, W as WorldInput, o as defineNamespaces, t as defineSystem, d as defineWorld, p as requiredSystemKey, r as resolveCodegen, c as resolveDeploy, l as resolveNamespace, y as resolveNamespaceMode, n as resolveNamespaces, s as resolveSystem, w as resolveSystems, z as resolveWorld, v as validateNamespace, m as validateNamespaces, q as validateSystem, u as validateSystems, x as validateWorld } from './world-NqdA4pfW.js';
4
5
  export { C as Codegen, f as Deploy, D as DynamicResolution, M as Module, N as Namespace, e as Namespaces, c as System, S as SystemDeploy, d as Systems, V as ValueWithType, W as World, i as isDynamicResolution, a as isValueWithType, r as resolveTableId, b as resolveWithContext } from './dynamicResolution-Bul4y_B0.js';
5
6
  import '@ark/util';
@@ -159,6 +160,19 @@ declare function encodeSystemCalls<abis extends readonly Abi[]>(systemCalls: Sys
159
160
  /** Encode system calls to be passed as arguments into `World.batchCallFrom` */
160
161
  declare function encodeSystemCallsFrom<abis extends readonly Abi[]>(from: Address, systemCalls: SystemCalls<abis>): AbiParametersToPrimitiveTypes<ExtractAbiFunction<worldCallAbi, "batchCallFrom">["inputs"]>;
161
162
 
163
+ type SystemFunction$1 = {
164
+ systemId: Hex;
165
+ systemFunctionSelector: Hex;
166
+ };
167
+
168
+ type CallFromParameters$1 = {
169
+ worldAddress: Hex;
170
+ delegatorAddress: Hex;
171
+ worldFunctionToSystemFunction?: (worldFunctionSelector: Hex) => Promise<SystemFunction$1>;
172
+ publicClient?: Client;
173
+ };
174
+ declare function callFrom(params: CallFromParameters$1): <chain extends Chain, account extends Account | undefined>(client: Client<Transport, chain, account>) => Pick<WalletActions<chain, account>, "writeContract">;
175
+
162
176
  type CallFromParameters = {
163
177
  worldAddress: Hex;
164
178
  delegatorAddress: Hex;
@@ -169,6 +183,6 @@ type SystemFunction = {
169
183
  systemId: Hex;
170
184
  systemFunctionSelector: Hex;
171
185
  };
172
- declare function callFrom(params: CallFromParameters): <chain extends Chain, account extends Account | undefined>(client: Client<Transport, chain, account>) => Pick<WalletActions<chain, account>, "writeContract">;
186
+ declare function sendUserOperationFrom(params: CallFromParameters): <chain extends Chain, account extends SmartAccount | undefined>(client: Client<Transport, chain, account>) => Pick<BundlerActions<account>, "sendUserOperation">;
173
187
 
174
- export { type SystemCall, type SystemCallFrom, type SystemCalls, callFrom, encodeSystemCall, encodeSystemCallFrom, encodeSystemCalls, encodeSystemCallsFrom };
188
+ export { type SystemCall, type SystemCallFrom, type SystemCalls, callFrom, encodeSystemCall, encodeSystemCallFrom, encodeSystemCalls, encodeSystemCallsFrom, sendUserOperationFrom };
package/dist/internal.js CHANGED
@@ -119,57 +119,23 @@ function encodeSystemCallsFrom(from, systemCalls) {
119
119
  // ts/actions/callFrom.ts
120
120
  import {
121
121
  slice,
122
- concat
122
+ concat as concat2
123
123
  } from "viem";
124
- import { getAction, encodeFunctionData as encodeFunctionData5 } from "viem/utils";
125
- import { readContract, writeContract as viem_writeContract } from "viem/actions";
124
+ import { getAction as getAction2, encodeFunctionData as encodeFunctionData5 } from "viem/utils";
125
+ import { writeContract as viem_writeContract } from "viem/actions";
126
126
  import { readHex } from "@latticexyz/common";
127
+
128
+ // ts/worldFunctionToSystemFunction.ts
127
129
  import {
130
+ getSchemaTypes,
128
131
  getKeySchema,
129
132
  getValueSchema,
130
- getSchemaTypes,
131
- decodeValueArgs,
132
- encodeKey
133
+ encodeKey,
134
+ decodeValueArgs
133
135
  } from "@latticexyz/protocol-parser/internal";
134
- function callFrom(params) {
135
- return (client) => ({
136
- async writeContract(writeArgs) {
137
- const _writeContract = getAction(client, viem_writeContract, "writeContract");
138
- if (writeArgs.address !== params.worldAddress || writeArgs.functionName === "call" || writeArgs.functionName === "callFrom" || writeArgs.functionName === "batchCallFrom" || writeArgs.functionName === "callWithSignature") {
139
- return _writeContract(writeArgs);
140
- }
141
- if (writeArgs.functionName === "batchCall") {
142
- const batchCallArgs = writeArgs;
143
- const [systemCalls] = batchCallArgs.args;
144
- if (!systemCalls.length) {
145
- throw new Error("`batchCall` should have at least one system call.");
146
- }
147
- return _writeContract({
148
- ...batchCallArgs,
149
- functionName: "batchCallFrom",
150
- args: [systemCalls.map((systemCall) => ({ from: params.delegatorAddress, ...systemCall }))]
151
- });
152
- }
153
- const worldCalldata = encodeFunctionData5({
154
- abi: writeArgs.abi,
155
- functionName: writeArgs.functionName,
156
- args: writeArgs.args
157
- });
158
- const worldFunctionSelector = slice(worldCalldata, 0, 4);
159
- const { systemId, systemFunctionSelector } = await worldFunctionToSystemFunction({
160
- ...params,
161
- publicClient: params.publicClient ?? client,
162
- worldFunctionSelector
163
- });
164
- const systemCalldata = concat([systemFunctionSelector, readHex(worldCalldata, 4)]);
165
- return _writeContract({
166
- ...writeArgs,
167
- functionName: "callFrom",
168
- args: [params.delegatorAddress, systemId, systemCalldata]
169
- });
170
- }
171
- });
172
- }
136
+ import { concat } from "viem";
137
+ import { readContract } from "viem/actions";
138
+ import { getAction } from "viem/utils";
173
139
  var systemFunctionCache = /* @__PURE__ */ new Map();
174
140
  async function worldFunctionToSystemFunction(params) {
175
141
  const cacheKey = concat([params.worldAddress, params.worldFunctionSelector]);
@@ -233,6 +199,107 @@ async function retrieveSystemFunctionFromContract(publicClient, worldAddress, wo
233
199
  return systemFunction;
234
200
  }
235
201
 
202
+ // ts/actions/callFrom.ts
203
+ function callFrom(params) {
204
+ return (client) => ({
205
+ async writeContract(writeArgs) {
206
+ const _writeContract = getAction2(client, viem_writeContract, "writeContract");
207
+ if (writeArgs.address !== params.worldAddress || writeArgs.functionName === "call" || writeArgs.functionName === "callFrom" || writeArgs.functionName === "batchCallFrom" || writeArgs.functionName === "callWithSignature") {
208
+ return _writeContract(writeArgs);
209
+ }
210
+ if (writeArgs.functionName === "batchCall") {
211
+ const batchCallArgs = writeArgs;
212
+ const [systemCalls] = batchCallArgs.args;
213
+ if (!systemCalls.length) {
214
+ throw new Error("`batchCall` should have at least one system call.");
215
+ }
216
+ return _writeContract({
217
+ ...batchCallArgs,
218
+ functionName: "batchCallFrom",
219
+ args: [systemCalls.map((systemCall) => ({ from: params.delegatorAddress, ...systemCall }))]
220
+ });
221
+ }
222
+ const worldCalldata = encodeFunctionData5({
223
+ abi: writeArgs.abi,
224
+ functionName: writeArgs.functionName,
225
+ args: writeArgs.args
226
+ });
227
+ const worldFunctionSelector = slice(worldCalldata, 0, 4);
228
+ const { systemId, systemFunctionSelector } = await worldFunctionToSystemFunction({
229
+ ...params,
230
+ publicClient: params.publicClient ?? client,
231
+ worldFunctionSelector
232
+ });
233
+ const systemCalldata = concat2([systemFunctionSelector, readHex(worldCalldata, 4)]);
234
+ return _writeContract({
235
+ ...writeArgs,
236
+ functionName: "callFrom",
237
+ args: [params.delegatorAddress, systemId, systemCalldata]
238
+ });
239
+ }
240
+ });
241
+ }
242
+
243
+ // ts/actions/sendUserOperationFrom.ts
244
+ import {
245
+ slice as slice2,
246
+ concat as concat3
247
+ } from "viem";
248
+ import { getAction as getAction3, encodeFunctionData as encodeFunctionData6 } from "viem/utils";
249
+ import { readHex as readHex2 } from "@latticexyz/common";
250
+ import { sendUserOperation as viem_sendUserOperation } from "viem/account-abstraction";
251
+ function sendUserOperationFrom(params) {
252
+ return (client) => ({
253
+ async sendUserOperation(args) {
254
+ const _sendUserOperation = getAction3(client, viem_sendUserOperation, "sendUserOperation");
255
+ if (args.callData) {
256
+ return _sendUserOperation(args);
257
+ }
258
+ const calls = await Promise.all(
259
+ args.calls.map(async (call) => {
260
+ if (!isDecodedCall(call)) return call;
261
+ if (call.to !== params.worldAddress || call.functionName === "call" || call.functionName === "callFrom" || call.functionName === "batchCallFrom" || call.functionName === "callWithSignature") {
262
+ return call;
263
+ }
264
+ if (call.functionName === "batchCall") {
265
+ const batchCallArgs = call.args;
266
+ const [systemCalls] = batchCallArgs.args;
267
+ if (!systemCalls.length) {
268
+ throw new Error("`batchCall` should have at least one system call.");
269
+ }
270
+ return {
271
+ ...call,
272
+ functionName: "batchCallFrom",
273
+ args: [systemCalls.map((systemCall) => ({ from: params.delegatorAddress, ...systemCall }))]
274
+ };
275
+ }
276
+ const worldCalldata = encodeFunctionData6({
277
+ abi: call.abi,
278
+ functionName: call.functionName,
279
+ args: call.args
280
+ });
281
+ const worldFunctionSelector = slice2(worldCalldata, 0, 4);
282
+ const { systemId, systemFunctionSelector } = await worldFunctionToSystemFunction({
283
+ ...params,
284
+ publicClient: params.publicClient ?? client,
285
+ worldFunctionSelector
286
+ });
287
+ const systemCalldata = concat3([systemFunctionSelector, readHex2(worldCalldata, 4)]);
288
+ return {
289
+ ...call,
290
+ functionName: "callFrom",
291
+ args: [params.delegatorAddress, systemId, systemCalldata]
292
+ };
293
+ })
294
+ );
295
+ return _sendUserOperation({ ...args, calls });
296
+ }
297
+ });
298
+ }
299
+ function isDecodedCall(call) {
300
+ return typeof call === "object" && call != null && "functionName" in call && "args" in call && "to" in call;
301
+ }
302
+
236
303
  // ts/config/v2/dynamicResolution.ts
237
304
  function resolveTableId(tableName) {
238
305
  return {
@@ -294,6 +361,7 @@ export {
294
361
  resolveTableId,
295
362
  resolveWithContext,
296
363
  resolveWorld,
364
+ sendUserOperationFrom,
297
365
  validateNamespace,
298
366
  validateNamespaces,
299
367
  validateSystem,
@@ -1 +1 @@
1
- {"version":3,"sources":["../ts/encodeSystemCall.ts","../ts/normalizeSystemFunctionName.ts","../ts/encodeSystemCallFrom.ts","../ts/encodeSystemCalls.ts","../ts/encodeSystemCallsFrom.ts","../ts/actions/callFrom.ts","../ts/config/v2/dynamicResolution.ts"],"sourcesContent":["import { Abi, EncodeFunctionDataParameters, Hex, encodeFunctionData, type ContractFunctionName } from \"viem\";\nimport type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from \"abitype\";\nimport { worldCallAbi } from \"./worldCallAbi\";\nimport { internal_normalizeSystemFunctionName } from \"./normalizeSystemFunctionName\";\n\nexport type SystemCall<abi extends Abi, functionName extends ContractFunctionName<abi>> = {\n [k in ContractFunctionName<abi>]: {\n /**\n * System's resource ID\n */\n readonly systemId: Hex;\n /**\n * System ABI\n */\n readonly abi: abi;\n /**\n * System function name to call\n */\n readonly functionName: k;\n } & Pick<EncodeFunctionDataParameters<abi, k>, \"args\">;\n}[functionName];\n\n/** Encode a system call to be passed as arguments into `World.call` */\nexport function encodeSystemCall<abi extends Abi, functionName extends ContractFunctionName<abi>>({\n abi,\n systemId,\n functionName,\n args,\n}: SystemCall<abi, functionName>): AbiParametersToPrimitiveTypes<ExtractAbiFunction<worldCallAbi, \"call\">[\"inputs\"]> {\n return [\n systemId,\n encodeFunctionData<abi, functionName>({\n abi,\n functionName: internal_normalizeSystemFunctionName(systemId, functionName),\n args,\n } as EncodeFunctionDataParameters<abi, functionName>),\n ];\n}\n","import { hexToResource, resourceToLabel } from \"@latticexyz/common\";\nimport { Hex } from \"viem\";\n\n/** @internal */\nexport function internal_normalizeSystemFunctionName(systemId: Hex, functionName: string) {\n const resource = hexToResource(systemId);\n const worldFunctionPrefix = resource.namespace !== \"\" ? `${resource.namespace}__` : null;\n if (worldFunctionPrefix != null && functionName.startsWith(worldFunctionPrefix)) {\n console.warn(\n // eslint-disable-next-line max-len\n `Detected world function name \"${functionName}\" used in call to system \"${resourceToLabel(resource)}\".\\n\\nIt's recommended to use a system ABI and system function name with these methods instead.`,\n );\n return functionName.slice(worldFunctionPrefix.length);\n }\n return functionName;\n}\n","import { Abi, EncodeFunctionDataParameters, encodeFunctionData, Address, type ContractFunctionName } from \"viem\";\nimport type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from \"abitype\";\nimport { SystemCall } from \"./encodeSystemCall\";\nimport { worldCallAbi } from \"./worldCallAbi\";\nimport { internal_normalizeSystemFunctionName } from \"./normalizeSystemFunctionName\";\n\nexport type SystemCallFrom<abi extends Abi, functionName extends ContractFunctionName<abi>> = SystemCall<\n abi,\n functionName\n> & {\n readonly from: Address;\n};\n\n/** Encode a system call to be passed as arguments into `World.callFrom` */\nexport function encodeSystemCallFrom<abi extends Abi, functionName extends ContractFunctionName<abi>>({\n abi,\n from,\n systemId,\n functionName,\n args,\n}: SystemCallFrom<abi, functionName>): AbiParametersToPrimitiveTypes<\n ExtractAbiFunction<worldCallAbi, \"callFrom\">[\"inputs\"]\n> {\n return [\n from,\n systemId,\n encodeFunctionData<abi, functionName>({\n abi,\n functionName: internal_normalizeSystemFunctionName(systemId, functionName),\n args,\n } as EncodeFunctionDataParameters<abi, functionName>),\n ];\n}\n","import { Abi, encodeFunctionData, type ContractFunctionName } from \"viem\";\nimport { SystemCall } from \"./encodeSystemCall\";\nimport type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from \"abitype\";\nimport { worldCallAbi } from \"./worldCallAbi\";\nimport { internal_normalizeSystemFunctionName } from \"./normalizeSystemFunctionName\";\n\nexport type SystemCalls<abis extends readonly Abi[]> = {\n [k in keyof abis]: SystemCall<abis[k], ContractFunctionName<abis[k]>>;\n};\n\n/** Encode system calls to be passed as arguments into `World.batchCall` */\nexport function encodeSystemCalls<abis extends readonly Abi[]>(\n systemCalls: SystemCalls<abis>,\n): AbiParametersToPrimitiveTypes<ExtractAbiFunction<worldCallAbi, \"batchCall\">[\"inputs\"]> {\n return [\n systemCalls.map(({ abi, systemId, functionName, args }) => ({\n systemId,\n callData: encodeFunctionData({\n abi,\n functionName: internal_normalizeSystemFunctionName(systemId, functionName),\n args,\n }),\n })),\n ];\n}\n","import { Abi, Address, encodeFunctionData } from \"viem\";\nimport type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from \"abitype\";\nimport { worldCallAbi } from \"./worldCallAbi\";\nimport { internal_normalizeSystemFunctionName } from \"./normalizeSystemFunctionName\";\nimport { SystemCalls } from \"./encodeSystemCalls\";\n\n/** Encode system calls to be passed as arguments into `World.batchCallFrom` */\nexport function encodeSystemCallsFrom<abis extends readonly Abi[]>(\n from: Address,\n systemCalls: SystemCalls<abis>,\n): AbiParametersToPrimitiveTypes<ExtractAbiFunction<worldCallAbi, \"batchCallFrom\">[\"inputs\"]> {\n return [\n systemCalls.map(({ abi, systemId, functionName, args }) => ({\n from,\n systemId,\n callData: encodeFunctionData({\n abi,\n functionName: internal_normalizeSystemFunctionName(systemId, functionName),\n args,\n }),\n })),\n ];\n}\n","import {\n slice,\n concat,\n type Transport,\n type Chain,\n type Account,\n type Hex,\n type WalletActions,\n type Client,\n type PublicActions,\n type WriteContractParameters,\n type EncodeFunctionDataParameters,\n} from \"viem\";\nimport { getAction, encodeFunctionData } from \"viem/utils\";\nimport { readContract, writeContract as viem_writeContract } from \"viem/actions\";\nimport { readHex } from \"@latticexyz/common\";\nimport {\n getKeySchema,\n getValueSchema,\n getSchemaTypes,\n decodeValueArgs,\n encodeKey,\n} from \"@latticexyz/protocol-parser/internal\";\nimport worldConfig from \"../../mud.config\";\nimport { worldCallAbi } from \"../worldCallAbi\";\n\ntype CallFromParameters = {\n worldAddress: Hex;\n delegatorAddress: Hex;\n worldFunctionToSystemFunction?: (worldFunctionSelector: Hex) => Promise<SystemFunction>;\n publicClient?: Client;\n};\n\ntype SystemFunction = { systemId: Hex; systemFunctionSelector: Hex };\n\n// By extending viem clients with this function after delegation, the delegation is automatically applied to World contract writes.\n// This means that these writes are made on behalf of the delegator.\n// Internally, it transforms the write arguments to use `callFrom`.\n//\n// Accepts either `worldFunctionToSystemFunction` or `publicClient` as an argument.\n// `worldFunctionToSystemFunction` allows manually providing the mapping function, thus users can utilize their client store for the lookup.\n// If `publicClient` is provided instead, this function retrieves the corresponding system function from the World contract.\n//\n// The function mapping is cached to avoid redundant retrievals for the same World function.\nexport function callFrom(\n params: CallFromParameters,\n): <chain extends Chain, account extends Account | undefined>(\n client: Client<Transport, chain, account>,\n) => Pick<WalletActions<chain, account>, \"writeContract\"> {\n return (client) => ({\n async writeContract(writeArgs) {\n const _writeContract = getAction(client, viem_writeContract, \"writeContract\");\n\n // Skip if the contract isn't the World or the function called should not be redirected through `callFrom`.\n if (\n writeArgs.address !== params.worldAddress ||\n writeArgs.functionName === \"call\" ||\n writeArgs.functionName === \"callFrom\" ||\n writeArgs.functionName === \"batchCallFrom\" ||\n writeArgs.functionName === \"callWithSignature\"\n ) {\n return _writeContract(writeArgs);\n }\n\n // Wrap system calls from `batchCall` with delegator for a `batchCallFrom`\n // TODO: remove this specific workaround once https://github.com/latticexyz/mud/pull/3506 lands\n if (writeArgs.functionName === \"batchCall\") {\n const batchCallArgs = writeArgs as unknown as WriteContractParameters<worldCallAbi, \"batchCall\">;\n const [systemCalls] = batchCallArgs.args;\n if (!systemCalls.length) {\n throw new Error(\"`batchCall` should have at least one system call.\");\n }\n\n return _writeContract({\n ...batchCallArgs,\n functionName: \"batchCallFrom\",\n args: [systemCalls.map((systemCall) => ({ from: params.delegatorAddress, ...systemCall }))],\n });\n }\n\n // Encode the World's calldata (which includes the World's function selector).\n const worldCalldata = encodeFunctionData({\n abi: writeArgs.abi,\n functionName: writeArgs.functionName,\n args: writeArgs.args,\n } as unknown as EncodeFunctionDataParameters);\n\n // The first 4 bytes of calldata represent the function selector.\n const worldFunctionSelector = slice(worldCalldata, 0, 4);\n\n // Get the systemId and System's function selector.\n const { systemId, systemFunctionSelector } = await worldFunctionToSystemFunction({\n ...params,\n publicClient: params.publicClient ?? client,\n worldFunctionSelector,\n });\n\n // Construct the System's calldata by replacing the World's function selector with the System's.\n // Use `readHex` instead of `slice` to prevent out-of-bounds errors with calldata that has no args.\n const systemCalldata = concat([systemFunctionSelector, readHex(worldCalldata, 4)]);\n\n // Call `writeContract` with the new args.\n return _writeContract({\n ...(writeArgs as unknown as WriteContractParameters<worldCallAbi, \"callFrom\">),\n functionName: \"callFrom\",\n args: [params.delegatorAddress, systemId, systemCalldata],\n });\n },\n });\n}\n\nconst systemFunctionCache = new Map<Hex, SystemFunction>();\n\nasync function worldFunctionToSystemFunction(params: {\n worldAddress: Hex;\n delegatorAddress: Hex;\n worldFunctionSelector: Hex;\n worldFunctionToSystemFunction?: (worldFunctionSelector: Hex) => Promise<SystemFunction>;\n publicClient: Client;\n}): Promise<SystemFunction> {\n const cacheKey = concat([params.worldAddress, params.worldFunctionSelector]);\n\n // Use cache if the function has been called previously.\n const cached = systemFunctionCache.get(cacheKey);\n if (cached) return cached;\n\n // If a mapping function is provided, use it. Otherwise, call the World contract.\n const systemFunction = params.worldFunctionToSystemFunction\n ? await params.worldFunctionToSystemFunction(params.worldFunctionSelector)\n : await retrieveSystemFunctionFromContract(params.publicClient, params.worldAddress, params.worldFunctionSelector);\n\n systemFunctionCache.set(cacheKey, systemFunction);\n\n return systemFunction;\n}\n\nasync function retrieveSystemFunctionFromContract(\n publicClient: Client,\n worldAddress: Hex,\n worldFunctionSelector: Hex,\n): Promise<SystemFunction> {\n const table = worldConfig.tables.world__FunctionSelectors;\n\n const keySchema = getSchemaTypes(getKeySchema(table));\n const valueSchema = getSchemaTypes(getValueSchema(table));\n\n const _readContract = getAction(publicClient, readContract, \"readContract\") as PublicActions[\"readContract\"];\n\n const [staticData, encodedLengths, dynamicData] = await _readContract({\n address: worldAddress,\n abi: [\n {\n type: \"function\",\n name: \"getRecord\",\n inputs: [\n {\n name: \"tableId\",\n type: \"bytes32\",\n internalType: \"ResourceId\",\n },\n {\n name: \"keyTuple\",\n type: \"bytes32[]\",\n internalType: \"bytes32[]\",\n },\n ],\n outputs: [\n {\n name: \"staticData\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"encodedLengths\",\n type: \"bytes32\",\n internalType: \"EncodedLengths\",\n },\n {\n name: \"dynamicData\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n stateMutability: \"view\",\n },\n ],\n functionName: \"getRecord\",\n args: [table.tableId, encodeKey(keySchema, { worldFunctionSelector })],\n });\n\n const decoded = decodeValueArgs(valueSchema, { staticData, encodedLengths, dynamicData });\n\n const systemFunction: SystemFunction = {\n systemId: decoded.systemId,\n systemFunctionSelector: decoded.systemFunctionSelector,\n };\n\n return systemFunction;\n}\n","import { World } from \"./output\";\n\nexport type DynamicResolution = {\n // TODO: add systemAddress support\n type: \"tableId\";\n input: string;\n};\n\nexport type ValueWithType = {\n value: string | number | Uint8Array;\n type: string;\n};\n\n/**\n * Dynamically resolve a table name to a table id at deploy time\n */\nexport function resolveTableId(tableName: string) {\n return {\n type: \"tableId\",\n input: tableName,\n } as const;\n}\n\n/** Type guard for DynamicResolution */\nexport function isDynamicResolution(value: unknown): value is DynamicResolution {\n return typeof value === \"object\" && value !== null && \"type\" in value && \"input\" in value;\n}\n\n/** Type guard for ValueWithType */\nexport function isValueWithType(value: unknown): value is ValueWithType {\n return typeof value === \"object\" && value !== null && \"type\" in value && \"value\" in value;\n}\n\n/**\n * Turn a DynamicResolution object into a ValueWithType based on the provided context\n */\nexport function resolveWithContext(\n input: unknown,\n context: { config: World; systemAddresses?: Record<string, Promise<string>> },\n): ValueWithType {\n if (isValueWithType(input)) return input;\n\n if (isDynamicResolution(input)) {\n if (input.type === \"tableId\") {\n const tableEntries = Object.entries(context.config.tables).filter(\n ([tableName, table]) => tableName === input.input || table.name === input.input,\n );\n\n if (tableEntries.length > 1) {\n throw new Error(\n `Found more than one table with name \"${input.input}\". Try using one of the following table names instead: ${tableEntries.map(([tableName]) => tableName).join(\", \")}`,\n );\n }\n\n if (tableEntries.length === 1) {\n const [entry] = tableEntries;\n const [, table] = entry;\n return { type: \"bytes32\", value: table.tableId };\n }\n }\n }\n\n throw new Error(`Could not resolve dynamic resolution:\\n${JSON.stringify(input, null, 2)}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAiD,0BAAqD;;;ACAtG,SA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C,CAAC,SAAS,MAAM,SAAS,EAAE,KAAK,IAAI,CAAC;AAAA,QACtK;AAAA,MACF;AAEA,UAAI,aAAa,WAAW,GAAG;AAC7B,cAAM,CAAC,KAAK,IAAI;AAChB,cAAM,CAAC,EAAE,KAAK,IAAI;AAClB,eAAO,EAAE,MAAM,WAAW,OAAO,MAAM,QAAQ;AAAA,MACjD;AAAA,IACF;AAAA,EACF;AAEA,QAAM,IAAI,MAAM;AAAA,EAA0C,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC,EAAE;AAC5F;","names":["encodeFunctionData","encodeFunctionData","encodeFunctionData","encodeFunctionData","encodeFunctionData","encodeFunctionData","encodeFunctionData","encodeFunctionData"]}
1
+ {"version":3,"sources":["../ts/encodeSystemCall.ts","../ts/normalizeSystemFunctionName.ts","../ts/encodeSystemCallFrom.ts","../ts/encodeSystemCalls.ts","../ts/encodeSystemCallsFrom.ts","../ts/actions/callFrom.ts","../ts/worldFunctionToSystemFunction.ts","../ts/actions/sendUserOperationFrom.ts","../ts/config/v2/dynamicResolution.ts"],"sourcesContent":["import { Abi, EncodeFunctionDataParameters, Hex, encodeFunctionData, type ContractFunctionName } from \"viem\";\nimport type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from \"abitype\";\nimport { worldCallAbi } from \"./worldCallAbi\";\nimport { internal_normalizeSystemFunctionName } from \"./normalizeSystemFunctionName\";\n\nexport type SystemCall<abi extends Abi, functionName extends ContractFunctionName<abi>> = {\n [k in ContractFunctionName<abi>]: {\n /**\n * System's resource ID\n */\n readonly systemId: Hex;\n /**\n * System ABI\n */\n readonly abi: abi;\n /**\n * System function name to call\n */\n readonly functionName: k;\n } & Pick<EncodeFunctionDataParameters<abi, k>, \"args\">;\n}[functionName];\n\n/** Encode a system call to be passed as arguments into `World.call` */\nexport function encodeSystemCall<abi extends Abi, functionName extends ContractFunctionName<abi>>({\n abi,\n systemId,\n functionName,\n args,\n}: SystemCall<abi, functionName>): AbiParametersToPrimitiveTypes<ExtractAbiFunction<worldCallAbi, \"call\">[\"inputs\"]> {\n return [\n systemId,\n encodeFunctionData<abi, functionName>({\n abi,\n functionName: internal_normalizeSystemFunctionName(systemId, functionName),\n args,\n } as EncodeFunctionDataParameters<abi, functionName>),\n ];\n}\n","import { hexToResource, resourceToLabel } from \"@latticexyz/common\";\nimport { Hex } from \"viem\";\n\n/** @internal */\nexport function internal_normalizeSystemFunctionName(systemId: Hex, functionName: string) {\n const resource = hexToResource(systemId);\n const worldFunctionPrefix = resource.namespace !== \"\" ? `${resource.namespace}__` : null;\n if (worldFunctionPrefix != null && functionName.startsWith(worldFunctionPrefix)) {\n console.warn(\n // eslint-disable-next-line max-len\n `Detected world function name \"${functionName}\" used in call to system \"${resourceToLabel(resource)}\".\\n\\nIt's recommended to use a system ABI and system function name with these methods instead.`,\n );\n return functionName.slice(worldFunctionPrefix.length);\n }\n return functionName;\n}\n","import { Abi, EncodeFunctionDataParameters, encodeFunctionData, Address, type ContractFunctionName } from \"viem\";\nimport type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from \"abitype\";\nimport { SystemCall } from \"./encodeSystemCall\";\nimport { worldCallAbi } from \"./worldCallAbi\";\nimport { internal_normalizeSystemFunctionName } from \"./normalizeSystemFunctionName\";\n\nexport type SystemCallFrom<abi extends Abi, functionName extends ContractFunctionName<abi>> = SystemCall<\n abi,\n functionName\n> & {\n readonly from: Address;\n};\n\n/** Encode a system call to be passed as arguments into `World.callFrom` */\nexport function encodeSystemCallFrom<abi extends Abi, functionName extends ContractFunctionName<abi>>({\n abi,\n from,\n systemId,\n functionName,\n args,\n}: SystemCallFrom<abi, functionName>): AbiParametersToPrimitiveTypes<\n ExtractAbiFunction<worldCallAbi, \"callFrom\">[\"inputs\"]\n> {\n return [\n from,\n systemId,\n encodeFunctionData<abi, functionName>({\n abi,\n functionName: internal_normalizeSystemFunctionName(systemId, functionName),\n args,\n } as EncodeFunctionDataParameters<abi, functionName>),\n ];\n}\n","import { Abi, encodeFunctionData, type ContractFunctionName } from \"viem\";\nimport { SystemCall } from \"./encodeSystemCall\";\nimport type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from \"abitype\";\nimport { worldCallAbi } from \"./worldCallAbi\";\nimport { internal_normalizeSystemFunctionName } from \"./normalizeSystemFunctionName\";\n\nexport type SystemCalls<abis extends readonly Abi[]> = {\n [k in keyof abis]: SystemCall<abis[k], ContractFunctionName<abis[k]>>;\n};\n\n/** Encode system calls to be passed as arguments into `World.batchCall` */\nexport function encodeSystemCalls<abis extends readonly Abi[]>(\n systemCalls: SystemCalls<abis>,\n): AbiParametersToPrimitiveTypes<ExtractAbiFunction<worldCallAbi, \"batchCall\">[\"inputs\"]> {\n return [\n systemCalls.map(({ abi, systemId, functionName, args }) => ({\n systemId,\n callData: encodeFunctionData({\n abi,\n functionName: internal_normalizeSystemFunctionName(systemId, functionName),\n args,\n }),\n })),\n ];\n}\n","import { Abi, Address, encodeFunctionData } from \"viem\";\nimport type { AbiParametersToPrimitiveTypes, ExtractAbiFunction } from \"abitype\";\nimport { worldCallAbi } from \"./worldCallAbi\";\nimport { internal_normalizeSystemFunctionName } from \"./normalizeSystemFunctionName\";\nimport { SystemCalls } from \"./encodeSystemCalls\";\n\n/** Encode system calls to be passed as arguments into `World.batchCallFrom` */\nexport function encodeSystemCallsFrom<abis extends readonly Abi[]>(\n from: Address,\n systemCalls: SystemCalls<abis>,\n): AbiParametersToPrimitiveTypes<ExtractAbiFunction<worldCallAbi, \"batchCallFrom\">[\"inputs\"]> {\n return [\n systemCalls.map(({ abi, systemId, functionName, args }) => ({\n from,\n systemId,\n callData: encodeFunctionData({\n abi,\n functionName: internal_normalizeSystemFunctionName(systemId, functionName),\n args,\n }),\n })),\n ];\n}\n","import {\n slice,\n concat,\n type Transport,\n type Chain,\n type Account,\n type Hex,\n type WalletActions,\n type Client,\n type WriteContractParameters,\n type EncodeFunctionDataParameters,\n} from \"viem\";\nimport { getAction, encodeFunctionData } from \"viem/utils\";\nimport { writeContract as viem_writeContract } from \"viem/actions\";\nimport { readHex } from \"@latticexyz/common\";\nimport { worldCallAbi } from \"../worldCallAbi\";\nimport { SystemFunction, worldFunctionToSystemFunction } from \"../worldFunctionToSystemFunction\";\n\ntype CallFromParameters = {\n worldAddress: Hex;\n delegatorAddress: Hex;\n worldFunctionToSystemFunction?: (worldFunctionSelector: Hex) => Promise<SystemFunction>;\n publicClient?: Client;\n};\n\n// By extending viem clients with this function after delegation, the delegation is automatically applied to World contract writes.\n// This means that these writes are made on behalf of the delegator.\n// Internally, it transforms the write arguments to use `callFrom`.\n//\n// Accepts either `worldFunctionToSystemFunction` or `publicClient` as an argument.\n// `worldFunctionToSystemFunction` allows manually providing the mapping function, thus users can utilize their client store for the lookup.\n// If `publicClient` is provided instead, this function retrieves the corresponding system function from the World contract.\n//\n// The function mapping is cached to avoid redundant retrievals for the same World function.\nexport function callFrom(\n params: CallFromParameters,\n): <chain extends Chain, account extends Account | undefined>(\n client: Client<Transport, chain, account>,\n) => Pick<WalletActions<chain, account>, \"writeContract\"> {\n return (client) => ({\n async writeContract(writeArgs) {\n const _writeContract = getAction(client, viem_writeContract, \"writeContract\");\n\n // Skip if the contract isn't the World or the function called should not be redirected through `callFrom`.\n if (\n writeArgs.address !== params.worldAddress ||\n writeArgs.functionName === \"call\" ||\n writeArgs.functionName === \"callFrom\" ||\n writeArgs.functionName === \"batchCallFrom\" ||\n writeArgs.functionName === \"callWithSignature\"\n ) {\n return _writeContract(writeArgs);\n }\n\n // Wrap system calls from `batchCall` with delegator for a `batchCallFrom`\n // TODO: remove this specific workaround once https://github.com/latticexyz/mud/pull/3506 lands\n if (writeArgs.functionName === \"batchCall\") {\n const batchCallArgs = writeArgs as unknown as WriteContractParameters<worldCallAbi, \"batchCall\">;\n const [systemCalls] = batchCallArgs.args;\n if (!systemCalls.length) {\n throw new Error(\"`batchCall` should have at least one system call.\");\n }\n\n return _writeContract({\n ...batchCallArgs,\n functionName: \"batchCallFrom\",\n args: [systemCalls.map((systemCall) => ({ from: params.delegatorAddress, ...systemCall }))],\n });\n }\n\n // Encode the World's calldata (which includes the World's function selector).\n const worldCalldata = encodeFunctionData({\n abi: writeArgs.abi,\n functionName: writeArgs.functionName,\n args: writeArgs.args,\n } as unknown as EncodeFunctionDataParameters);\n\n // The first 4 bytes of calldata represent the function selector.\n const worldFunctionSelector = slice(worldCalldata, 0, 4);\n\n // Get the systemId and System's function selector.\n const { systemId, systemFunctionSelector } = await worldFunctionToSystemFunction({\n ...params,\n publicClient: params.publicClient ?? client,\n worldFunctionSelector,\n });\n\n // Construct the System's calldata by replacing the World's function selector with the System's.\n // Use `readHex` instead of `slice` to prevent out-of-bounds errors with calldata that has no args.\n const systemCalldata = concat([systemFunctionSelector, readHex(worldCalldata, 4)]);\n\n // Call `writeContract` with the new args.\n return _writeContract({\n ...(writeArgs as unknown as WriteContractParameters<worldCallAbi, \"callFrom\">),\n functionName: \"callFrom\",\n args: [params.delegatorAddress, systemId, systemCalldata],\n });\n },\n });\n}\n","import {\n getSchemaTypes,\n getKeySchema,\n getValueSchema,\n encodeKey,\n decodeValueArgs,\n} from \"@latticexyz/protocol-parser/internal\";\nimport { Client, concat, Hex, PublicActions } from \"viem\";\nimport { readContract } from \"viem/actions\";\nimport { getAction } from \"viem/utils\";\nimport worldConfig from \"../mud.config\";\n\nexport type SystemFunction = { systemId: Hex; systemFunctionSelector: Hex };\n\nconst systemFunctionCache = new Map<Hex, SystemFunction>();\n\nexport async function worldFunctionToSystemFunction(params: {\n worldAddress: Hex;\n delegatorAddress: Hex;\n worldFunctionSelector: Hex;\n worldFunctionToSystemFunction?: (worldFunctionSelector: Hex) => Promise<SystemFunction>;\n publicClient: Client;\n}): Promise<SystemFunction> {\n const cacheKey = concat([params.worldAddress, params.worldFunctionSelector]);\n\n // Use cache if the function has been called previously.\n const cached = systemFunctionCache.get(cacheKey);\n if (cached) return cached;\n\n // If a mapping function is provided, use it. Otherwise, call the World contract.\n const systemFunction = params.worldFunctionToSystemFunction\n ? await params.worldFunctionToSystemFunction(params.worldFunctionSelector)\n : await retrieveSystemFunctionFromContract(params.publicClient, params.worldAddress, params.worldFunctionSelector);\n\n systemFunctionCache.set(cacheKey, systemFunction);\n\n return systemFunction;\n}\n\nasync function retrieveSystemFunctionFromContract(\n publicClient: Client,\n worldAddress: Hex,\n worldFunctionSelector: Hex,\n): Promise<SystemFunction> {\n const table = worldConfig.tables.world__FunctionSelectors;\n\n const keySchema = getSchemaTypes(getKeySchema(table));\n const valueSchema = getSchemaTypes(getValueSchema(table));\n\n const _readContract = getAction(publicClient, readContract, \"readContract\") as PublicActions[\"readContract\"];\n\n const [staticData, encodedLengths, dynamicData] = await _readContract({\n address: worldAddress,\n abi: [\n {\n type: \"function\",\n name: \"getRecord\",\n inputs: [\n {\n name: \"tableId\",\n type: \"bytes32\",\n internalType: \"ResourceId\",\n },\n {\n name: \"keyTuple\",\n type: \"bytes32[]\",\n internalType: \"bytes32[]\",\n },\n ],\n outputs: [\n {\n name: \"staticData\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"encodedLengths\",\n type: \"bytes32\",\n internalType: \"EncodedLengths\",\n },\n {\n name: \"dynamicData\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n stateMutability: \"view\",\n },\n ],\n functionName: \"getRecord\",\n args: [table.tableId, encodeKey(keySchema, { worldFunctionSelector })],\n });\n\n const decoded = decodeValueArgs(valueSchema, { staticData, encodedLengths, dynamicData });\n\n const systemFunction: SystemFunction = {\n systemId: decoded.systemId,\n systemFunctionSelector: decoded.systemFunctionSelector,\n };\n\n return systemFunction;\n}\n","import {\n slice,\n concat,\n type Transport,\n type Chain,\n type Hex,\n type Client,\n type EncodeFunctionDataParameters,\n Abi,\n WriteContractParameters,\n} from \"viem\";\nimport { getAction, encodeFunctionData } from \"viem/utils\";\nimport { readHex } from \"@latticexyz/common\";\nimport { BundlerActions, sendUserOperation as viem_sendUserOperation, SmartAccount } from \"viem/account-abstraction\";\nimport { worldFunctionToSystemFunction } from \"../worldFunctionToSystemFunction\";\nimport { worldCallAbi } from \"../worldCallAbi\";\n\ntype CallFromParameters = {\n worldAddress: Hex;\n delegatorAddress: Hex;\n worldFunctionToSystemFunction?: (worldFunctionSelector: Hex) => Promise<SystemFunction>;\n publicClient?: Client;\n};\n\ntype SystemFunction = { systemId: Hex; systemFunctionSelector: Hex };\n\n// By extending viem clients with this function after delegation, the delegation is automatically applied to World contract writes.\n// This means that these writes are made on behalf of the delegator.\n// Internally, it transforms the write arguments to use `callFrom`.\n//\n// Accepts either `worldFunctionToSystemFunction` or `publicClient` as an argument.\n// `worldFunctionToSystemFunction` allows manually providing the mapping function, thus users can utilize their client store for the lookup.\n// If `publicClient` is provided instead, this function retrieves the corresponding system function from the World contract.\n//\n// The function mapping is cached to avoid redundant retrievals for the same World function.\nexport function sendUserOperationFrom(\n params: CallFromParameters,\n): <chain extends Chain, account extends SmartAccount | undefined>(\n client: Client<Transport, chain, account>,\n) => Pick<BundlerActions<account>, \"sendUserOperation\"> {\n return (client) => ({\n async sendUserOperation(args) {\n const _sendUserOperation = getAction(client, viem_sendUserOperation, \"sendUserOperation\");\n\n if (args.callData) {\n return _sendUserOperation(args as never); // TODO: fix type issue\n }\n\n const calls = await Promise.all(\n args.calls.map(async (call) => {\n // Skip if the call doesn't match the decoded format (`functionName`, `args`, `to`)\n if (!isDecodedCall(call)) return call;\n\n // Skip if the contract isn't the World or the function called should not be redirected through `callFrom`.\n if (\n call.to !== params.worldAddress ||\n call.functionName === \"call\" ||\n call.functionName === \"callFrom\" ||\n call.functionName === \"batchCallFrom\" ||\n call.functionName === \"callWithSignature\"\n ) {\n return call;\n }\n\n // Wrap system calls from `batchCall` with delegator for a `batchCallFrom`\n // TODO: remove this specific workaround once https://github.com/latticexyz/mud/pull/3506 lands\n if (call.functionName === \"batchCall\") {\n const batchCallArgs = call.args as unknown as WriteContractParameters<worldCallAbi, \"batchCall\">;\n const [systemCalls] = batchCallArgs.args;\n if (!systemCalls.length) {\n throw new Error(\"`batchCall` should have at least one system call.\");\n }\n\n return {\n ...call,\n functionName: \"batchCallFrom\",\n args: [systemCalls.map((systemCall) => ({ from: params.delegatorAddress, ...systemCall }))],\n };\n }\n\n // Encode the World's calldata (which includes the World's function selector).\n const worldCalldata = encodeFunctionData({\n abi: call.abi,\n functionName: call.functionName,\n args: call.args,\n } as unknown as EncodeFunctionDataParameters);\n\n // The first 4 bytes of calldata represent the function selector.\n const worldFunctionSelector = slice(worldCalldata, 0, 4);\n\n // Get the systemId and System's function selector.\n const { systemId, systemFunctionSelector } = await worldFunctionToSystemFunction({\n ...params,\n publicClient: params.publicClient ?? client,\n worldFunctionSelector,\n });\n\n // Construct the System's calldata by replacing the World's function selector with the System's.\n // Use `readHex` instead of `slice` to prevent out-of-bounds errors with calldata that has no args.\n const systemCalldata = concat([systemFunctionSelector, readHex(worldCalldata, 4)]);\n\n return {\n ...call,\n functionName: \"callFrom\",\n args: [params.delegatorAddress, systemId, systemCalldata],\n };\n }),\n );\n\n // Call `sendUserOperation` with the new args.\n return _sendUserOperation({ ...args, calls } as never); // TODO: fix type issue\n },\n });\n}\n\n// Matching https://github.com/wevm/viem/blob/26e4bcafb3be976510b4d8170ef29bb69e014263/src/types/calls.ts#L6-L23 (not exported)\ntype DecodedCall = {\n abi: Abi;\n functionName: string;\n args: unknown[];\n to: Hex;\n};\n\nfunction isDecodedCall(call: unknown): call is DecodedCall {\n return typeof call === \"object\" && call != null && \"functionName\" in call && \"args\" in call && \"to\" in call;\n}\n","import { World } from \"./output\";\n\nexport type DynamicResolution = {\n // TODO: add systemAddress support\n type: \"tableId\";\n input: string;\n};\n\nexport type ValueWithType = {\n value: string | number | Uint8Array;\n type: string;\n};\n\n/**\n * Dynamically resolve a table name to a table id at deploy time\n */\nexport function resolveTableId(tableName: string) {\n return {\n type: \"tableId\",\n input: tableName,\n } as const;\n}\n\n/** Type guard for DynamicResolution */\nexport function isDynamicResolution(value: unknown): value is DynamicResolution {\n return typeof value === \"object\" && value !== null && \"type\" in value && \"input\" in value;\n}\n\n/** Type guard for ValueWithType */\nexport function isValueWithType(value: unknown): value is ValueWithType {\n return typeof value === \"object\" && value !== null && \"type\" in value && \"value\" in value;\n}\n\n/**\n * Turn a DynamicResolution object into a ValueWithType based on the provided context\n */\nexport function resolveWithContext(\n input: unknown,\n context: { config: World; systemAddresses?: Record<string, Promise<string>> },\n): ValueWithType {\n if (isValueWithType(input)) return input;\n\n if (isDynamicResolution(input)) {\n if (input.type === \"tableId\") {\n const tableEntries = Object.entries(context.config.tables).filter(\n ([tableName, table]) => tableName === input.input || table.name === input.input,\n );\n\n if (tableEntries.length > 1) {\n throw new Error(\n `Found more than one table with name \"${input.input}\". Try using one of the following table names instead: ${tableEntries.map(([tableName]) => tableName).join(\", \")}`,\n );\n }\n\n if (tableEntries.length === 1) {\n const [entry] = tableEntries;\n const [, table] = entry;\n return { type: \"bytes32\", value: table.tableId };\n }\n }\n }\n\n throw new Error(`Could not resolve dynamic resolution:\\n${JSON.stringify(input, null, 2)}`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAiD,0BAAqD;;;ACAtG,SAAS,eAAe,uBAAuB;AAIxC,SAAS,qCAAqC,UAAe,cAAsB;AACxF,QAAM,WAAW,cAAc,QAAQ;AACvC,QAAM,sBAAsB,SAAS,cAAc,KAAK,GAAG,SAAS,SAAS,OAAO;AACpF,MAAI,uBAAuB,QAAQ,aAAa,WAAW,mBAAmB,GAAG;AAC/E,YAAQ;AAAA;AAAA,MAEN,iCAAiC,YAAY,6BAA6B,gBAAgB,QAAQ,CAAC;AAAA;AAAA;AAAA,IACrG;AACA,WAAO,aAAa,MAAM,oBAAoB,MAAM;AAAA,EACtD;AACA,SAAO;AACT;;;ADQO,SAAS,iBAAkF;AAAA,EAChG;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAAqH;AACnH,SAAO;AAAA,IACL;AAAA,IACA,mBAAsC;AAAA,MACpC;AAAA,MACA,cAAc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,CAAC,CAAC,SAAS,MAAM,SAAS,EAAE,KAAK,IAAI,CAAC;AAAA,QACtK;AAAA,MACF;AAEA,UAAI,aAAa,WAAW,GAAG;AAC7B,cAAM,CAAC,KAAK,IAAI;AAChB,cAAM,CAAC,EAAE,KAAK,IAAI;AAClB,eAAO,EAAE,MAAM,WAAW,OAAO,MAAM,QAAQ;AAAA,MACjD;AAAA,IACF;AAAA,EACF;AAEA,QAAM,IAAI,MAAM;AAAA,EAA0C,KAAK,UAAU,OAAO,MAAM,CAAC,CAAC,EAAE;AAC5F;","names":["encodeFunctionData","encodeFunctionData","encodeFunctionData","encodeFunctionData","encodeFunctionData","encodeFunctionData","concat","getAction","encodeFunctionData","getAction","encodeFunctionData","concat","slice","concat","getAction","encodeFunctionData","readHex","getAction","encodeFunctionData","slice","concat","readHex"]}
package/dist/node.js CHANGED
@@ -273,6 +273,9 @@ function renderSystemLibrary(options) {
273
273
  } = options;
274
274
  const functions = functionsInput.map((func) => ({
275
275
  ...func,
276
+ // Format parameters (add auxiliary argument names, replace calldata location)
277
+ parameters: formatParams(func.parameters),
278
+ // Remove `payable` from stateMutability for library functions
276
279
  stateMutability: func.stateMutability.replace("payable", "")
277
280
  }));
278
281
  const imports = [
@@ -394,7 +397,7 @@ function renderErrors(errors) {
394
397
  }
395
398
  function renderUserTypeFunction(contractFunction, userTypeName) {
396
399
  const { name, parameters, stateMutability, returnParameters } = contractFunction;
397
- const args = [`${userTypeName} self`, ...parameters].map((arg) => arg.replace(/ calldata /, " memory "));
400
+ const args = [`${userTypeName} self`, ...parameters];
398
401
  const functionSignature = `
399
402
  function ${name}(
400
403
  ${renderArguments2(args)}
@@ -411,7 +414,7 @@ function renderUserTypeFunction(contractFunction, userTypeName) {
411
414
  }
412
415
  function renderCallWrapperFunction(contractFunction, callingFromRootSystemErrorName) {
413
416
  const { name, parameters, stateMutability, returnParameters } = contractFunction;
414
- const args = [`CallWrapper memory self`, ...parameters].map((arg) => arg.replace(/ calldata /, " memory "));
417
+ const args = [`CallWrapper memory self`, ...parameters];
415
418
  const functionSignature = `
416
419
  function ${name}(
417
420
  ${renderArguments2(args)}
@@ -455,7 +458,7 @@ function renderRootCallWrapperFunction(contractFunction, namespace) {
455
458
  if (namespace === "" && stateMutability != "") {
456
459
  return "";
457
460
  }
458
- const args = ["RootCallWrapper memory self", ...parameters].map((arg) => arg.replace(/ calldata /, " memory "));
461
+ const args = ["RootCallWrapper memory self", ...parameters];
459
462
  const functionSignature = `
460
463
  function ${name}(
461
464
  ${renderArguments2(args)}
@@ -516,6 +519,14 @@ function renderReturnParameters2(returnParameters) {
516
519
  if (returnParameters.length == 0) return "";
517
520
  return `returns (${renderArguments2(returnParameters)})`;
518
521
  }
522
+ function formatParams(params) {
523
+ let auxCount = 0;
524
+ return params.map((arg) => arg.replace(/ calldata /, " memory ")).map((arg) => {
525
+ const items = arg.split(" ");
526
+ const needsAux = items.length === 1 || items.length === 2 && items[1] === "memory";
527
+ return needsAux ? `${arg} __aux${auxCount++}` : arg;
528
+ });
529
+ }
519
530
 
520
531
  // ts/node/render-solidity/renderWorldInterface.ts
521
532
  import { renderArguments as renderArguments3, renderedSolidityHeader as renderedSolidityHeader3, renderImports as renderImports3 } from "@latticexyz/common/codegen";
@@ -557,7 +568,7 @@ function renderWorldInterface({
557
568
  }
558
569
 
559
570
  // ts/node/render-solidity/worldgen.ts
560
- import fs from "node:fs/promises";
571
+ import fs2 from "node:fs/promises";
561
572
  import path4 from "node:path";
562
573
  import { formatAndWriteSolidity, contractToInterface } from "@latticexyz/common/codegen";
563
574
 
@@ -566,6 +577,7 @@ import { isHex } from "viem";
566
577
 
567
578
  // ts/node/getSystemContracts.ts
568
579
  import path3 from "node:path";
580
+ import fs from "node:fs/promises";
569
581
 
570
582
  // ts/node/findSolidityFiles.ts
571
583
  import path2 from "node:path";
@@ -5274,8 +5286,8 @@ var PathScurryBase = class {
5274
5286
  *
5275
5287
  * @internal
5276
5288
  */
5277
- constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs3 = defaultFS } = {}) {
5278
- this.#fs = fsFromOption(fs3);
5289
+ constructor(cwd = process.cwd(), pathImpl, sep2, { nocase, childrenCacheSize = 16 * 1024, fs: fs4 = defaultFS } = {}) {
5290
+ this.#fs = fsFromOption(fs4);
5279
5291
  if (cwd instanceof URL || cwd.startsWith("file://")) {
5280
5292
  cwd = fileURLToPath(cwd);
5281
5293
  }
@@ -5833,8 +5845,8 @@ var PathScurryWin32 = class extends PathScurryBase {
5833
5845
  /**
5834
5846
  * @internal
5835
5847
  */
5836
- newRoot(fs3) {
5837
- return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5848
+ newRoot(fs4) {
5849
+ return new PathWin32(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs4 });
5838
5850
  }
5839
5851
  /**
5840
5852
  * Return true if the provided path string is an absolute path
@@ -5862,8 +5874,8 @@ var PathScurryPosix = class extends PathScurryBase {
5862
5874
  /**
5863
5875
  * @internal
5864
5876
  */
5865
- newRoot(fs3) {
5866
- return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs3 });
5877
+ newRoot(fs4) {
5878
+ return new PathPosix(this.rootPath, IFDIR, void 0, this.roots, this.nocase, this.childrenCache(), { fs: fs4 });
5867
5879
  }
5868
5880
  /**
5869
5881
  * Return true if the provided path string is an absolute path
@@ -6951,19 +6963,25 @@ async function findSolidityFiles({ cwd, pattern = "**" }) {
6951
6963
  }
6952
6964
 
6953
6965
  // ts/node/getSystemContracts.ts
6966
+ import { parseSystem } from "@latticexyz/common/codegen";
6967
+ import { isDefined } from "@latticexyz/common/utils";
6954
6968
  async function getSystemContracts({
6955
6969
  rootDir,
6956
6970
  config
6957
6971
  }) {
6958
- const solidityFiles = await findSolidityFiles({
6972
+ const filePaths = await findSolidityFiles({
6959
6973
  cwd: rootDir,
6960
6974
  pattern: path3.join(config.sourceDirectory, "**")
6961
6975
  });
6962
- return solidityFiles.filter(
6963
- (file) => file.basename.endsWith("System") && // exclude the base System contract
6964
- file.basename !== "System" && // exclude interfaces
6965
- !/^I[A-Z]/.test(file.basename)
6966
- ).map((file) => {
6976
+ const files = await Promise.all(
6977
+ filePaths.map(async (file) => {
6978
+ const source = await fs.readFile(path3.join(rootDir, file.filename), "utf-8");
6979
+ return { ...file, source };
6980
+ })
6981
+ );
6982
+ return files.map((file) => {
6983
+ const parsedSystem = parseSystem(file.source, file.basename);
6984
+ if (!parsedSystem) return;
6967
6985
  const namespaceLabel = (() => {
6968
6986
  if (!config.multipleNamespaces && config.namespace != null) return config.namespace;
6969
6987
  const relativePath = path3.relative(path3.join(rootDir, config.sourceDirectory), file.filename);
@@ -6980,7 +6998,7 @@ async function getSystemContracts({
6980
6998
  namespaceLabel,
6981
6999
  systemLabel: file.basename
6982
7000
  };
6983
- });
7001
+ }).filter(isDefined);
6984
7002
  }
6985
7003
 
6986
7004
  // ts/node/resolveSystems.ts
@@ -7038,7 +7056,7 @@ async function worldgen({
7038
7056
  config.codegen.outputDirectory,
7039
7057
  config.codegen.worldgenDirectory
7040
7058
  );
7041
- const systems = (await resolveSystems({ rootDir, config })).filter((system) => system.deploy.registerWorldFunctions).map((system) => {
7059
+ const systems = (await resolveSystems({ rootDir, config })).filter((system) => system.deploy.registerWorldFunctions || config.codegen.generateSystemLibraries).map((system) => {
7042
7060
  const interfaceName = `I${system.label}`;
7043
7061
  const libraryName = `${system.label}Lib`;
7044
7062
  const sourceDir = config.multipleNamespaces ? path4.join(config.sourceDirectory, "namespaces", system.namespaceLabel) : config.sourceDirectory;
@@ -7058,12 +7076,12 @@ async function worldgen({
7058
7076
  if (clean) {
7059
7077
  const libraryDirs = [...new Set(systems.map(({ libraryPath }) => path4.dirname(libraryPath)))];
7060
7078
  await Promise.all([
7061
- fs.rm(worldgenOutDir, { recursive: true, force: true }),
7062
- ...libraryDirs.map((dir) => fs.rm(dir, { recursive: true, force: true }))
7079
+ fs2.rm(worldgenOutDir, { recursive: true, force: true }),
7080
+ ...libraryDirs.map((dir) => fs2.rm(dir, { recursive: true, force: true }))
7063
7081
  ]);
7064
7082
  }
7065
7083
  const outputPath = path4.join(worldgenOutDir, config.codegen.worldInterfaceName + ".sol");
7066
- const worldImports = systems.map(
7084
+ const worldImports = systems.filter((system) => system.deploy.registerWorldFunctions).map(
7067
7085
  (system) => ({
7068
7086
  symbol: system.interfaceName,
7069
7087
  path: "./" + path4.relative(path4.dirname(outputPath), system.interfacePath)
@@ -7073,22 +7091,24 @@ async function worldgen({
7073
7091
  const worldImportPath = config.codegen.worldImportPath.startsWith(".") ? "./" + path4.relative(path4.dirname(outputPath), path4.join(rootDir, config.codegen.worldImportPath)) : config.codegen.worldImportPath;
7074
7092
  await Promise.all(
7075
7093
  systems.map(async (system) => {
7076
- const source = await fs.readFile(path4.join(rootDir, system.sourcePath), "utf8");
7094
+ const source = await fs2.readFile(path4.join(rootDir, system.sourcePath), "utf8");
7077
7095
  const { functions, errors, symbolImports } = contractToInterface(source, system.label);
7078
- const interfaceImports = symbolImports.map(
7079
- ({ symbol, path: importPath }) => ({
7080
- symbol,
7081
- path: importPath.startsWith(".") ? "./" + path4.relative(worldgenOutDir, path4.join(rootDir, path4.dirname(system.sourcePath), importPath)) : importPath
7082
- })
7083
- );
7084
- const systemInterface = renderSystemInterface({
7085
- name: system.interfaceName,
7086
- functionPrefix: system.namespace === "" ? "" : `${system.namespace}__`,
7087
- functions,
7088
- errors,
7089
- imports: interfaceImports
7090
- });
7091
- await formatAndWriteSolidity(systemInterface, system.interfacePath, "Generated system interface");
7096
+ if (system.deploy.registerWorldFunctions) {
7097
+ const interfaceImports = symbolImports.map(
7098
+ ({ symbol, path: importPath }) => ({
7099
+ symbol,
7100
+ path: importPath.startsWith(".") ? "./" + path4.relative(worldgenOutDir, path4.join(rootDir, path4.dirname(system.sourcePath), importPath)) : importPath
7101
+ })
7102
+ );
7103
+ const systemInterface = renderSystemInterface({
7104
+ name: system.interfaceName,
7105
+ functionPrefix: system.namespace === "" ? "" : `${system.namespace}__`,
7106
+ functions,
7107
+ errors,
7108
+ imports: interfaceImports
7109
+ });
7110
+ await formatAndWriteSolidity(systemInterface, system.interfacePath, "Generated system interface");
7111
+ }
7092
7112
  if (config.codegen.generateSystemLibraries) {
7093
7113
  const systemImport = {
7094
7114
  symbol: system.label,
@@ -7133,7 +7153,7 @@ async function worldgen({
7133
7153
  import path5 from "node:path";
7134
7154
  import { readFile } from "node:fs/promises";
7135
7155
  import { type as type2 } from "arktype";
7136
- import { indent, isDefined } from "@latticexyz/common/utils";
7156
+ import { indent, isDefined as isDefined2 } from "@latticexyz/common/utils";
7137
7157
  import { size, sliceHex } from "viem";
7138
7158
 
7139
7159
  // ts/node/common.ts
@@ -7211,7 +7231,7 @@ ${indent(artifact.message)}`);
7211
7231
  return;
7212
7232
  }
7213
7233
  return artifact;
7214
- }).filter(isDefined).filter(hasMetadata).map((artifact) => {
7234
+ }).filter(isDefined2).filter(hasMetadata).map((artifact) => {
7215
7235
  artifact;
7216
7236
  const sourcePath = Object.keys(artifact.metadata.settings.compilationTarget)[0];
7217
7237
  const name = artifact.metadata.settings.compilationTarget[sourcePath];
@@ -7320,7 +7340,7 @@ async function buildSystemsManifest(opts) {
7320
7340
  }
7321
7341
 
7322
7342
  // ts/node/loadSystemsManifest.ts
7323
- import fs2 from "node:fs/promises";
7343
+ import fs3 from "node:fs/promises";
7324
7344
  import path7 from "node:path";
7325
7345
  import { type as type4 } from "arktype";
7326
7346
  import { indent as indent2 } from "@latticexyz/common/utils";
@@ -7328,13 +7348,13 @@ var parseManifest = type4("string").pipe.try((s) => JSON.parse(s), SystemsManife
7328
7348
  async function loadSystemsManifest(opts) {
7329
7349
  const outFile = path7.join(opts.rootDir, systemsManifestFilename);
7330
7350
  try {
7331
- await fs2.access(outFile, fs2.constants.F_OK | fs2.constants.R_OK);
7351
+ await fs3.access(outFile, fs3.constants.F_OK | fs3.constants.R_OK);
7332
7352
  } catch (error2) {
7333
7353
  throw new Error(
7334
7354
  `Systems manifest at "${systemsManifestFilename}" not found or not readable. Run \`mud build\` before trying again.`
7335
7355
  );
7336
7356
  }
7337
- const json = await fs2.readFile(outFile, "utf8");
7357
+ const json = await fs3.readFile(outFile, "utf8");
7338
7358
  const manifest = parseManifest(json);
7339
7359
  if (manifest instanceof type4.errors) {
7340
7360
  throw new Error(