@latticexyz/cli 2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27 → 2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mud.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import*as i from"dotenv";i.config();async function l(){let{default:r}=await import("yargs"),{default:o}=await import("chalk"),{hideBin:e}=await import("yargs/helpers"),{logError:s}=await import("./errors-JCLK7DZO.js"),{commands:t}=await import("./commands-TAUKPNBI.js");r(e(process.argv)).scriptName("mud").command(t).strict().fail((a,n)=>{console.error(o.red(a)),a.includes("Missing required argument")&&console.log(o.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),n!=null&&(s(n),console.log("")),process.exit(1)}).alias({h:"help"}).argv}l();
2
+ import*as i from"dotenv";i.config();async function l(){let{default:r}=await import("yargs"),{default:o}=await import("chalk"),{hideBin:e}=await import("yargs/helpers"),{logError:s}=await import("./errors-JCLK7DZO.js"),{commands:t}=await import("./commands-YIWKPUKZ.js");r(e(process.argv)).scriptName("mud").command(t).strict().fail((a,n)=>{console.error(o.red(a)),a.includes("Missing required argument")&&console.log(o.yellow(`Run 'pnpm mud ${process.argv[2]} --help' for a list of available and required arguments.`)),console.log(""),n!=null&&(s(n),console.log("")),process.exit(1)}).alias({h:"help"}).argv}l();
3
3
  //# sourceMappingURL=mud.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@latticexyz/cli",
3
- "version": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
3
+ "version": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
4
4
  "description": "Command line interface for mud",
5
5
  "repository": {
6
6
  "type": "git",
@@ -50,17 +50,17 @@
50
50
  "yargs": "^17.7.1",
51
51
  "zod": "3.23.8",
52
52
  "zod-validation-error": "^1.3.0",
53
- "@latticexyz/abi-ts": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
54
- "@latticexyz/block-logs-stream": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
55
- "@latticexyz/common": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
56
- "@latticexyz/config": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
57
- "@latticexyz/gas-report": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
58
- "@latticexyz/protocol-parser": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
59
- "@latticexyz/schema-type": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
60
- "@latticexyz/store": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
61
- "@latticexyz/utils": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
62
- "@latticexyz/world": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27",
63
- "@latticexyz/world-module-metadata": "2.2.15-main-2be543f7f0936f5dc94c13613da679d8634dfc27"
53
+ "@latticexyz/abi-ts": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
54
+ "@latticexyz/block-logs-stream": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
55
+ "@latticexyz/common": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
56
+ "@latticexyz/config": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
57
+ "@latticexyz/gas-report": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
58
+ "@latticexyz/protocol-parser": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
59
+ "@latticexyz/schema-type": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
60
+ "@latticexyz/store": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
61
+ "@latticexyz/utils": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
62
+ "@latticexyz/world": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4",
63
+ "@latticexyz/world-module-metadata": "2.2.15-main-d9efd2b57d234f6be5627c09835a7da8345e3fd4"
64
64
  },
65
65
  "devDependencies": {
66
66
  "@types/debug": "^4.1.7",
@@ -1,54 +0,0 @@
1
- import{a as se}from"./chunk-JXC4VYGI.js";import{command as pi}from"@latticexyz/gas-report/internal";import{command as fi}from"@latticexyz/abi-ts/internal";import{loadConfig as kt,resolveConfigPath as Pt}from"@latticexyz/config/node";import{tablegen as At}from"@latticexyz/store/codegen";import{buildSystemsManifest as St,worldgen as vt}from"@latticexyz/world/node";import{forge as Dt}from"@latticexyz/common/foundry";import{execa as Tt}from"execa";async function F({rootDir:e,config:o,foundryProfile:t=process.env.FOUNDRY_PROFILE}){await Promise.all([At({rootDir:e,config:o}),vt({rootDir:e,config:o})]),await Dt(["build"],{profile:t}),await St({rootDir:e,config:o}),await Tt("mud",["abi-ts"],{stdio:"inherit"})}import Mt from"node:path";var Bt={command:"build",describe:"Build contracts and generate MUD artifacts (table libraries, world interface, ABI)",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"},profile:{type:"string",desc:"The foundry profile to use"}})},async handler(e){let o=await Pt(e.configPath),t=await kt(o);await F({rootDir:Mt.dirname(o),config:t,foundryProfile:e.profile}),process.exit(0)}},Ue=Bt;import{rmSync as Ot}from"fs";import{homedir as It}from"os";import Ht from"path";import{execa as Wt}from"execa";var Rt={command:"devnode",describe:"Start a local Ethereum node for development",builder(e){return e.options({blocktime:{type:"number",default:1,decs:"Interval in which new blocks are produced"}})},async handler({blocktime:e}){console.log("Clearing devnode history");let o=It();Ot(Ht.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let t=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${t.join(" ")}`);let r=Wt("anvil",t,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
2
- gracefully shutting down from SIGINT (Crtl-C)`),r.kill(),process.exit()}),await r}},Ve=Rt;var jt={command:"hello <name>",describe:"Greet <name> with Hello",builder(e){return e.options({upper:{type:"boolean"}}).positional("name",{type:"string",demandOption:!0})},handler({name:e}){let o=`Gm, ${e}!`;console.log(o),process.exit(0)}},_e=jt;import{loadConfig as $t,resolveConfigPath as Et}from"@latticexyz/config/node";import{tablegen as Lt}from"@latticexyz/store/codegen";import Ft from"node:path";var zt={command:"tablegen",describe:"Autogenerate MUD Store table libraries based on the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"}})},async handler(e){let o=await Et(e.configPath),t=await $t(o);await Lt({rootDir:Ft.dirname(o),config:t}),process.exit(0)}},Ke=zt;import Ce from"node:path";import{existsSync as hs,mkdirSync as ws,readFileSync as xs,writeFileSync as We}from"node:fs";import{stringToHex as Fn}from"viem";import{getBalance as Jt,sendRawTransaction as qt,sendTransaction as qe,waitForTransactionReceipt as Ye}from"viem/actions";var P={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c",creationCode:"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3"};import Je from"debug";var O=Je("mud:cli"),Ut=Je("mud:cli");O.log=console.debug.bind(console);Ut.log=console.error.bind(console);var f=O.extend("deploy"),Vt=O.extend("deploy");f.log=console.debug.bind(console);Vt.log=console.error.bind(console);import{sliceHex as _t}from"viem";import{getBytecode as Kt}from"viem/actions";var ae=`0x${P.address}`;async function ie(e){let o=await Kt(e,{address:ae});if(o)return f("found CREATE2 deployer at",ae),o!==_t(`0x${P.creationCode}`,14)&&console.warn(`
3
- \u26A0\uFE0F Bytecode for deployer at ${ae} did not match the expected CREATE2 bytecode. You may have unexpected results.
4
- `),ae}var Te=`0x${P.address}`;async function Ge(e){let o=await ie(e);if(o!==void 0)return o;let t=BigInt(P.gasLimit)*BigInt(P.gasPrice),r=await Jt(e,{address:`0x${P.signerAddress}`}),n=t-r;if(n>0){f("sending gas for CREATE2 deployer to signer at",P.signerAddress);let i=await qe(e,{chain:e.chain??null,to:`0x${P.signerAddress}`,value:n}),d=await Ye(e,{hash:i});if(d.status!=="success")throw console.error("failed to send gas to deployer signer",d),new Error("failed to send gas to deployer signer")}f("deploying CREATE2 deployer at",Te);let s=await qt(e,{serializedTransaction:`0x${P.transaction}`}).catch(i=>{if(String(i).includes("only replay-protected (EIP-155) transactions allowed over RPC"))return console.warn(`
5
- \u26A0\uFE0F Your chain or RPC does not allow for non EIP-155 signed transactions, so your deploys will not be determinstic and contract addresses may change between deploys.
6
-
7
- We recommend running your chain's node with \`--rpc.allow-unprotected-txs\` to enable determinstic deployments.
8
- `),f("deploying CREATE2 deployer"),qe(e,{chain:e.chain??null,data:`0x${P.creationCode}`});throw i}),a=await Ye(e,{hash:s});if(!a.contractAddress)throw new Error("Deploy receipt did not have contract address, was the deployer not deployed?");return a.contractAddress!==Te&&console.warn(`
9
- \u26A0\uFE0F CREATE2 deployer created at ${a.contractAddress} does not match the CREATE2 determinstic deployer we expected (${Te})`),a.contractAddress}import{waitForTransactionReceipt as xr}from"viem/actions";import{concatHex as Xt,getCreate2Address as er}from"viem";import{getBytecode as or}from"viem/actions";import{padHex as Yt}from"viem";import Gt from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{helloStoreEvent as Qt}from"@latticexyz/store";import{helloWorldEvent as Zt}from"@latticexyz/world";var D=Yt("0x",{size:32}),Z=parseInt("6000",16),de=[Qt,Zt],T=Gt,Qe=["2.0.0","2.0.1","2.0.2"],Ze=["2.0.0","2.0.1","2.0.2"];import{sendTransaction as tr}from"@latticexyz/common";import rr from"p-retry";async function Xe({client:e,deployerAddress:o,bytecode:t,deployedBytecodeSize:r,debugLabel:n="contract"}){if(t.includes("__$"))throw new Error(`Found unlinked public library in ${n} bytecode`);let s=er({from:o,salt:D,bytecode:t});return await or(e,{address:s,blockTag:"pending"})?(f("found",n,"at",s),[]):(r!=null&&(r>Z?console.warn(`
10
- Bytecode for ${n} (${r} bytes) is over the contract size limit (${Z} bytes). Run \`forge build --sizes\` for more info.
11
- `):r>Z*.95&&console.warn(`
12
- Bytecode for ${n} (${r} bytes) is almost over the contract size limit (${Z} bytes). Run \`forge build --sizes\` for more info.
13
- `)),f("deploying",n,"at",s),[await rr(()=>tr(e,{chain:e.chain??null,to:o,data:Xt([D,t])}),{retries:3,onFailedAttempt:()=>f(`failed to deploy ${n}, retrying...`)})])}import{uniqueBy as sr}from"@latticexyz/common/utils";import{waitForTransactionReceipt as nr}from"viem/actions";async function B({client:e,hashes:o,debugLabel:t="transactions"}){if(o.length){f(`waiting for ${t} to confirm`);for(let r of o)if((await nr(e,{hash:r})).status==="reverted")throw new Error(`Transaction reverted: ${r}`)}}async function M({client:e,deployerAddress:o,contracts:t}){let r=sr(t,s=>s.bytecode),n=(await Promise.all(r.map(s=>Xe({client:e,deployerAddress:o,...s})))).flat();return await B({client:e,hashes:n,debugLabel:"contract deploys"}),n}import so from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import dr from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{getCreate2Address as lr,encodeDeployData as cr,size as mr}from"viem";import eo from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import oo from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import to from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import ro from"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json"assert{type:"json"};import no from"@latticexyz/world/out/InitModule.sol/InitModule.json"assert{type:"json"};import ar from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{getCreate2Address as X,encodeDeployData as ir,size as ee}from"viem";function z(e){let o=ee(eo.deployedBytecode.object),t=eo.bytecode.object,r=X({from:e,bytecode:t,salt:D}),n=ee(oo.deployedBytecode.object),s=oo.bytecode.object,a=X({from:e,bytecode:s,salt:D}),i=ee(to.deployedBytecode.object),d=to.bytecode.object,l=X({from:e,bytecode:d,salt:D}),m=ee(ro.deployedBytecode.object),p=ro.bytecode.object,g=X({from:e,bytecode:p,salt:D}),C=ee(no.deployedBytecode.object),u=ir({bytecode:no.bytecode.object,abi:ar,args:[r,a,l,g]}),x=X({from:e,bytecode:u,salt:D});return{AccessManagementSystem:{bytecode:t,deployedBytecodeSize:o,debugLabel:"access management system",address:r},BalanceTransferSystem:{bytecode:s,deployedBytecodeSize:n,debugLabel:"balance transfer system",address:a},BatchCallSystem:{bytecode:d,deployedBytecodeSize:i,debugLabel:"batch call system",address:l},RegistrationSystem:{bytecode:p,deployedBytecodeSize:m,debugLabel:"core registration system",address:g},InitModule:{bytecode:u,deployedBytecodeSize:C,debugLabel:"core module",address:x}}}function le(e){let o=z(e),t=mr(so.deployedBytecode.object),r=cr({bytecode:so.bytecode.object,abi:dr,args:[o.InitModule.address]}),n=lr({from:e,bytecode:r,salt:D});return{...o,WorldFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world factory",address:n}}}import ao from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.json"assert{type:"json"};import pr from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json"assert{type:"json"};import{getCreate2Address as fr,encodeDeployData as yr,size as ur}from"viem";function ce(e){let o=z(e),t=ur(ao.deployedBytecode.object),r=yr({bytecode:ao.bytecode.object,abi:pr,args:[o.InitModule.address]}),n=fr({from:e,bytecode:r,salt:D});return{...o,WorldProxyFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world proxy factory",address:n}}}async function io(e,o,t){if(t){let n=ce(o);return await M({client:e,deployerAddress:o,contracts:Object.values(n)}),n.WorldProxyFactory.address}let r=le(o);return await M({client:e,deployerAddress:o,contracts:Object.values(r)}),r.WorldFactory.address}import Cr from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as Ar}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as gr,decodeEventLog as br,hexToString as lo,parseAbi as hr}from"viem";import{isDefined as wr}from"@latticexyz/common/utils";function N(e){let o=e.map(a=>{try{return{...a,...br({strict:!0,abi:hr(de),topics:a.topics,data:a.data})}}catch(i){if(i instanceof gr)return;throw i}}).filter(wr),{address:t,deployBlock:r,worldVersion:n,storeVersion:s}=o.reduce((a,i)=>({...a,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:lo(i.args.worldVersion).replace(/\0+$/,"")}:null,...i.eventName==="HelloStore"?{storeVersion:lo(i.args.storeVersion).replace(/\0+$/,"")}:null}),{});if(t==null)throw new Error("could not find world address");if(r==null)throw new Error("could not find world deploy block number");if(n==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:t,deployBlock:r,worldVersion:n,storeVersion:s}}async function co(e,o,t,r){let n=await io(e,o,r);f("deploying world");let s=await Ar(e,{chain:e.chain??null,address:n,abi:Cr,functionName:"deployWorld",args:[t]});f("waiting for world deploy");let a=await xr(e,{hash:s});if(a.status!=="success")throw console.error("world deploy failed",a),new Error("world deploy failed");let i=N(a.logs);return f("deployed world to",i.address,"at block",i.deployBlock),{...i,stateBlock:i.deployBlock}}import{resourceToLabel as pe,writeContract as Or}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as Ir,keySchemaToHex as uo,valueSchemaToHex as go,getSchemaTypes as U,getValueSchema as bo,getKeySchema as ho}from"@latticexyz/protocol-parser/internal";import{decodeAbiParameters as mo,parseAbiParameters as po}from"viem";import{hexToResource as Sr}from"@latticexyz/common";import{decodeKey as vr,decodeValueArgs as Dr,getKeySchema as Tr,getSchemaTypes as fo,getValueSchema as kr,hexToSchema as yo}from"@latticexyz/protocol-parser/internal";import ke from"@latticexyz/store/mud.config";import{fetchBlockLogs as Pr}from"@latticexyz/block-logs-stream";import{flattenStoreLogs as Mr,getStoreLogs as Br}from"@latticexyz/store/internal";async function me({client:e,worldDeploy:o}){f("looking up tables for",o.address);let t=await Pr({fromBlock:o.deployBlock,toBlock:o.stateBlock,maxBlockRange:100000n,async getLogs({fromBlock:s,toBlock:a}){return Br(e,{address:o.address,fromBlock:s,toBlock:a,tableId:ke.namespaces.store.tables.Tables.tableId})}}),n=Mr(t.flatMap(s=>s.logs)).map(s=>{let{tableId:a}=vr(fo(Tr(ke.namespaces.store.tables.Tables)),s.args.keyTuple),{type:i,namespace:d,name:l}=Sr(a),m=Dr(fo(kr(ke.namespaces.store.tables.Tables)),s.args),p=m.keySchema,g=m.valueSchema,C=yo(p),u=yo(g),x=mo(po("string[]"),m.abiEncodedKeyNames)[0],S=mo(po("string[]"),m.abiEncodedFieldNames)[0],b=[...u.staticFields,...u.dynamicFields],w=Object.fromEntries(C.staticFields.map((y,A)=>[x[A],{type:y,internalType:y}])),c=Object.fromEntries(b.map((y,A)=>[S[A],{type:y,internalType:y}]));return{type:i,namespace:d,name:l,tableId:a,schema:{...w,...c},key:Object.keys(w),keySchema:w,keySchemaHex:p,valueSchema:c,valueSchemaHex:g}});return f("found",n.length,"tables for",o.address),n}import Hr from"p-retry";import{isDefined as Wr}from"@latticexyz/common/utils";async function wo({client:e,worldDeploy:o,tables:t}){let r=new Map(t.map(d=>{let l=U(ho(d)),m=U(bo(d)),p=uo(l),g=go(m);return[d.tableId,{...d,keySchema:l,keySchemaHex:p,valueSchema:m,valueSchemaHex:g}]})),s=(await me({client:e,worldDeploy:o})).filter(({tableId:d})=>r.has(d));if(s.length){f("existing tables:",s.map(pe).join(", "));let d=s.map(l=>{let m=r.get(l.tableId);if(l.keySchemaHex!==m.keySchemaHex||l.valueSchemaHex!==m.valueSchemaHex)return[`"${pe(l)}" table:`,` Registered schema: ${JSON.stringify({schema:U(l.schema),key:l.key})}`,` Config schema: ${JSON.stringify({schema:U(m.schema),key:m.key})}`].join(`
14
- `)}).filter(Wr);if(d.length)throw new Error(["Table schemas are immutable, but found registered tables with a different schema than what you have configured.",...d,"You can either update your config with the registered schema or change the table name to register a new table."].join(`
15
-
16
- `)+`
17
- `)}let a=new Set(s.map(({tableId:d})=>d)),i=t.filter(d=>!a.has(d.tableId));return i.length?(f("registering tables:",i.map(pe).join(", ")),await Promise.all(i.map(d=>{let l=U(ho(d)),m=U(bo(d));return Hr(()=>Or(e,{chain:e.chain??null,address:o.address,abi:T,functionName:"registerTable",args:[d.tableId,Ir(m),uo(l),go(m),Object.keys(l),Object.keys(m)]}),{retries:3,onFailedAttempt:()=>f(`failed to register table ${pe(d)}, retrying...`)})}))):[]}import{getAddress as R}from"viem";import{writeContract as Me,resourceToLabel as oe}from"@latticexyz/common";import{hexToResource as Qr,resourceToLabel as Zr}from"@latticexyz/common";import{getFunctions as Xr}from"@latticexyz/world/internal";import{flattenStoreLogs as Rr,getStoreLogs as jr}from"@latticexyz/store/internal";import $r from"@latticexyz/store/mud.config";import{fetchBlockLogs as Er}from"@latticexyz/block-logs-stream";async function V({client:e,worldDeploy:o}){f("looking up resource IDs for",o.address);let t=await Er({fromBlock:o.deployBlock,toBlock:o.stateBlock,maxBlockRange:100000n,async getLogs({fromBlock:s,toBlock:a}){return jr(e,{address:o.address,fromBlock:s,toBlock:a,tableId:$r.namespaces.store.tables.ResourceIds.tableId})}}),n=Rr(t.flatMap(s=>s.logs)).map(s=>s.args.keyTuple[0]);return f("found",n.length,"resource IDs for",o.address),n}import{decodeValueArgs as Lr,encodeKey as Fr,getKeySchema as zr,getSchemaTypes as xo,getValueSchema as Nr}from"@latticexyz/protocol-parser/internal";import{readContract as Ur}from"viem/actions";async function _({client:e,worldDeploy:o,table:t,key:r}){let[n,s,a]=await Ur(e,{blockNumber:o.stateBlock,address:o.address,abi:T,functionName:"getRecord",args:[t.tableId,Fr(xo(zr(t)),r)]});return Lr(xo(Nr(t)),{staticData:n,encodedLengths:s,dynamicData:a})}import{getAddress as Vr}from"viem";import{decodeKey as _r,getKeySchema as Kr,getSchemaTypes as Jr}from"@latticexyz/protocol-parser/internal";import Pe from"@latticexyz/world/mud.config";import{fetchBlockLogs as qr}from"@latticexyz/block-logs-stream";import{flattenStoreLogs as Yr,getStoreLogs as Gr}from"@latticexyz/store/internal";async function fe({client:e,worldDeploy:o}){f("looking up resource access for",o.address);let t=await qr({fromBlock:o.deployBlock,toBlock:o.stateBlock,maxBlockRange:100000n,async getLogs({fromBlock:a,toBlock:i}){return Gr(e,{address:o.address,fromBlock:a,toBlock:i,tableId:Pe.namespaces.world.tables.ResourceAccess.tableId})}}),n=Yr(t.flatMap(a=>a.logs)).map(a=>_r(Jr(Kr(Pe.namespaces.world.tables.ResourceAccess)),a.args.keyTuple)),s=(await Promise.all(n.map(async a=>[a,await _({client:e,worldDeploy:o,table:Pe.namespaces.world.tables.ResourceAccess,key:a})]))).filter(([,a])=>a.access).map(([a])=>({resourceId:a.resourceId,address:Vr(a.caller)}));return f("found",s.length,"resource<>address access pairs"),s}import en from"@latticexyz/world/mud.config";async function Co({client:e,worldDeploy:o}){let[t,r,n]=await Promise.all([V({client:e,worldDeploy:o}),Xr({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock}),fe({client:e,worldDeploy:o})]),s=t.map(Qr).filter(a=>a.type==="system");return f("looking up systems:",s.map(Zr).join(", ")),await Promise.all(s.map(async a=>{let{system:i,publicAccess:d}=await _({client:e,worldDeploy:o,table:en.namespaces.world.tables.Systems,key:{systemId:a.resourceId}}),l=r.filter(m=>m.systemId===a.resourceId);return{address:i,namespace:a.namespace,name:a.name,systemId:a.resourceId,allowAll:d,allowedAddresses:n.filter(({resourceId:m})=>m===a.resourceId).map(({address:m})=>m),worldFunctions:l}}))}import Be from"p-retry";async function Ao({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,systems:n}){let[s,a]=await Promise.all([Co({client:e,worldDeploy:r}),fe({client:e,worldDeploy:r})]),i=n.filter(c=>s.some(y=>y.systemId===c.systemId&&R(y.address)===R(c.prepareDeploy(o,t).address)));i.length&&f("existing systems:",i.map(oe).join(", "));let d=i.map(c=>c.systemId),l=n.filter(c=>!d.includes(c.systemId));if(!l.length)return[];let m=l.filter(c=>s.some(y=>y.systemId===c.systemId&&R(y.address)!==R(c.prepareDeploy(o,t).address)));m.length&&f("upgrading systems:",m.map(oe).join(", "));let p=l.filter(c=>!s.some(y=>y.systemId===c.systemId));p.length&&f("registering new systems:",p.map(oe).join(", ")),await M({client:e,deployerAddress:o,contracts:l.map(c=>({bytecode:c.prepareDeploy(o,t).bytecode,deployedBytecodeSize:c.deployedBytecodeSize,debugLabel:`${oe(c)} system`}))});let g=await Promise.all(l.map(c=>Be(()=>Me(e,{chain:e.chain??null,address:r.address,abi:T,functionName:"registerSystem",args:[c.systemId,c.prepareDeploy(o,t).address,c.allowAll]}),{retries:3,onFailedAttempt:()=>f(`failed to register system ${oe(c)}, retrying...`)}))),C=n.map(c=>c.systemId),u=a.filter(({resourceId:c})=>C.includes(c)),x=[...n.flatMap(c=>c.allowedAddresses.map(y=>({resourceId:c.systemId,address:y}))),...n.flatMap(c=>c.allowedSystemIds.map(y=>({resourceId:c.systemId,address:s.find(A=>A.systemId===y)?.address??n.find(A=>A.systemId===y)?.prepareDeploy(o,t).address})).filter(y=>y.address!=null))],S=x.filter(c=>!u.some(({resourceId:y,address:A})=>y===c.resourceId&&R(A)===R(c.address))),b=u.filter(c=>!x.some(({resourceId:y,address:A})=>y===c.resourceId&&R(A)===R(c.address)));b.length&&f("revoking",b.length,"access grants"),S.length&&f("adding",S.length,"access grants");let w=await Promise.all([...b.map(c=>Be(()=>Me(e,{chain:e.chain??null,address:r.address,abi:T,functionName:"revokeAccess",args:[c.resourceId,c.address]}),{retries:3,onFailedAttempt:()=>f("failed to revoke access, retrying...")})),...S.map(c=>Be(()=>Me(e,{chain:e.chain??null,address:r.address,abi:T,functionName:"grantAccess",args:[c.resourceId,c.address]}),{retries:3,onFailedAttempt:()=>f("failed to grant access, retrying...")}))]);return[...g,...w]}import{getAddress as on,parseAbi as tn}from"viem";import{getBlock as Oe}from"viem/actions";import{fetchBlockLogs as rn}from"@latticexyz/block-logs-stream";var So=new Map;async function ye(e,o){let t=on(o),r=So.get(t);if(r!=null)return{...r,stateBlock:(await Oe(e,{blockTag:"latest"})).number};f("looking up world deploy for",t);let[n,s]=await Promise.all([Oe(e,{blockTag:"earliest"}),Oe(e,{blockTag:"latest"})]),a=await rn({publicClient:e,address:t,events:tn(de),fromBlock:n.number,toBlock:s.number,maxBlockRange:100000n});return r={...N(a.flatMap(i=>i.logs)),stateBlock:s.number},So.set(t,r),f("found world deploy for",t,"at block",r.deployBlock),r}import{hexToResource as nn,writeContract as sn}from"@latticexyz/common";import{getFunctions as an}from"@latticexyz/world/internal";import dn from"p-retry";async function vo({client:e,worldDeploy:o,functions:t}){let r=await an({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock}),n=Object.fromEntries(r.map(i=>[i.selector,i])),s=t.filter(i=>n[i.selector]),a=t.filter(i=>!s.includes(i));if(s.length){f("functions already registered:",s.map(d=>d.signature).join(", "));let i=s.filter(d=>d.systemId!==n[d.selector]?.systemId);i.length&&console.warn("found",i.length,"functions already registered but pointing at a different system ID:",i.map(d=>d.signature).join(", "))}return a.length?(f("registering functions:",a.map(i=>i.signature).join(", ")),Promise.all(a.map(i=>{let{namespace:d}=nn(i.systemId),l=d===""?{functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSignature]}:{functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]};return dn(()=>sn(e,{chain:e.chain??null,address:o.address,abi:T,...l}),{retries:3,onFailedAttempt:()=>f(`failed to register function ${i.signature}, retrying...`)})}))):[]}import{BaseError as ln}from"viem";import{writeContract as cn}from"@latticexyz/common";import{isDefined as mn}from"@latticexyz/common/utils";import pn from"p-retry";async function ue({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,modules:n}){return n.length?(await M({client:e,deployerAddress:o,contracts:n.map(s=>({bytecode:s.prepareDeploy(o,t).bytecode,deployedBytecodeSize:s.deployedBytecodeSize,debugLabel:`${s.name} module`}))}),f("installing modules:",n.map(s=>s.name).join(", ")),(await Promise.all(n.map(s=>pn(async()=>{try{let a=[...T,...s.abi],i=s.prepareDeploy(o,t).address,d=s.installAsRoot?{functionName:"installRootModule",args:[i,s.installData]}:{functionName:"installModule",args:[i,s.installData]};return await cn(e,{chain:e.chain??null,address:r.address,abi:a,...d})}catch(a){if(a instanceof ln&&a.message.includes("Module_AlreadyInstalled")){f(`module ${s.name} already installed`);return}if(s.optional){f(`optional module ${s.name} install failed, skipping`),f(a);return}throw a}},{retries:3,onFailedAttempt:()=>f(`failed to install module ${s.name}, retrying...`)})))).filter(mn)):[]}import{getAddress as Do}from"viem";import{hexToResource as To,resourceToHex as ko,writeContract as fn}from"@latticexyz/common";import yn from"@latticexyz/world/mud.config";async function Po({client:e,worldDeploy:o,resourceIds:t}){let r=Array.from(new Set(t.map(p=>To(p).namespace))),n=await V({client:e,worldDeploy:o}),s=new Set(n.map(p=>To(p).namespace));s.size&&f("found",s.size,"existing namespaces:",Array.from(s).map(p=>p===""?"<root>":p).join(", "));let a=r.filter(p=>s.has(p)),d=(await Promise.all(a.map(async p=>{let{owner:g}=await _({client:e,worldDeploy:o,table:yn.namespaces.world.tables.NamespaceOwner,key:{namespaceId:ko({type:"namespace",namespace:p,name:""})}});return[p,g]}))).filter(([,p])=>Do(p)!==Do(e.account.address)).map(([p])=>p);if(d.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${d.join(", ")}`);let l=r.filter(p=>!s.has(p));return l.length>0&&f("registering namespaces:",Array.from(l).join(", ")),Promise.all(l.map(p=>fn(e,{chain:e.chain??null,address:o.address,abi:T,functionName:"registerNamespace",args:[ko({namespace:p,type:"namespace",name:""})]})))}import{resourceToHex as zn,resourceToLabel as Nn}from"@latticexyz/common";import{randomBytes as Un}from"crypto";import{stringToHex as Oo,BaseError as kn}from"viem";import{hexToResource as Pn,writeContract as Mn}from"@latticexyz/common";import{identity as Bn,isDefined as Io}from"@latticexyz/common/utils";import On from"@latticexyz/world-module-metadata/mud.config";import In from"@latticexyz/world-module-metadata/out/IMetadataSystem.sol/IMetadataSystem.abi.json"assert{type:"json"};import{decodeValueArgs as un,getKeyTuple as gn,getSchemaTypes as bn,getValueSchema as hn}from"@latticexyz/protocol-parser/internal";import{readContract as wn}from"viem/actions";import{mapObject as xn}from"@latticexyz/common/utils";async function K({client:e,worldDeploy:o,table:t,key:r}){let[n,s,a]=await wn(e,{blockNumber:o.stateBlock,address:o.address,abi:T,functionName:"getRecord",args:[t.tableId,gn(t,r)]}),i={...r,...un(bn(hn(t)),{staticData:n,encodedLengths:s,dynamicData:a})};return xn(t.schema,(d,l)=>i[l])}import Hn from"@latticexyz/world-module-metadata/out/MetadataModule.sol/MetadataModule.json"assert{type:"json"};import{isHex as Cn,size as An}from"viem";function ge(e){return Object.entries(e).flatMap(([o,t])=>Object.entries(t).flatMap(([r,n])=>n.map(s=>({path:o,name:r,start:s.start,length:s.length}))))}import{z as H}from"zod";import{Abi as Sn}from"abitype/zod";function vn(e){return Cn(e,{strict:!1})}var Mo=H.object({object:H.string().refine(vn),linkReferences:H.record(H.record(H.array(H.object({start:H.number(),length:H.number()})))).optional()}),Dn=H.object({bytecode:Mo,deployedBytecode:Mo,abi:Sn});function be(e){let o=Dn.parse(e),t=ge(o.bytecode.linkReferences??{});return{abi:o.abi,bytecode:o.bytecode.object,placeholders:t,deployedBytecodeSize:An(o.deployedBytecode.object)}}import{spliceHex as Tn}from"@latticexyz/common";import{getCreate2Address as Bo}from"viem";function $(e,o){return function(r,n){let s=e;if(o.length===0)return{bytecode:s,address:Bo({from:r,bytecode:s,salt:D})};if(!n)throw new Error("Libraries must be provided if there are placeholders");for(let a of o){let i=n.getAddress({name:a.name,path:a.path,deployer:r});s=Tn(s,a.start,a.length,i)}return{bytecode:s,address:Bo({from:r,bytecode:s,salt:D})}}}var he=be(Hn);async function Ho({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,tags:n,valueToHex:s=Bn}){let a=(await Promise.all(n.map(async d=>{let{value:l}=await K({client:e,worldDeploy:r,table:On.tables.metadata__ResourceTag,key:{resource:d.resourceId,tag:Oo(d.tag,{size:32})}});if(l!==s(d.value))return d}))).filter(Io);if(a.length===0)return[];let i=await ue({client:e,deployerAddress:o,worldDeploy:r,libraryMap:t,modules:[{optional:!0,name:"MetadataModule",installAsRoot:!1,installData:"0x",prepareDeploy:$(he.bytecode,he.placeholders),deployedBytecodeSize:he.deployedBytecodeSize,abi:he.abi}]});return await B({client:e,hashes:i,debugLabel:"metadata module installation"}),f("setting",a.length,"resource tags"),(await Promise.all(a.map(async d=>{let l=Pn(d.resourceId),m=`${l.type}:${l.namespace}:${l.name}`;f(`tagging ${m} with ${d.tag}: ${JSON.stringify(d.value)}`);try{return await Mn(e,{chain:e.chain??null,address:r.address,abi:In,functionName:"metadata__setResourceTag",args:[d.resourceId,Oo(d.tag,{size:32}),s(d.value)]})}catch(p){f(`failed to set resource tag for ${m}, skipping
18
- ${p instanceof kn?p.shortMessage:p}`)}}))).filter(Io)}import{concatHex as Wn,encodeDeployData as Rn,getCreate2Address as jn,isHex as Ro}from"viem";import{waitForTransactionReceipt as $n}from"viem/actions";import{resourceToHex as En,sendTransaction as Ln,writeContract as Wo}from"@latticexyz/common";function He(e,o){let t=o.find(r=>r.sourcePath===e.sourcePath&&r.name===e.name);if(!t)throw new Error(`Could not find referenced artifact at "${e.sourcePath}:${e.name}".`);return t}function jo(e,o){return e.bytecode.filter(t=>!Ro(t)).flatMap(t=>jo(He(t,o),o))}function Ie(e,o,t){return Wn(o.bytecode.map(r=>Ro(r)?r:jn({from:e,salt:D,bytecode:Ie(e,He(r,t),t)})))}async function $o({client:e,deployerAddress:o,artifacts:t,customWorld:r}){let n=z(o);await M({client:e,deployerAddress:o,contracts:Object.values(n)});let s=He(r,t),a=jo(s,t);a.length&&(f(`deploying ${a.length} world dependencies`),await M({client:e,deployerAddress:o,contracts:a.map(g=>Ie(o,g,t)).reverse().map(g=>({bytecode:g}))})),f("deploying custom world");let i=await Ln(e,{chain:e.chain??null,data:Rn({abi:s.abi,args:[],bytecode:Ie(o,s,t)})});f("waiting for custom world deploy");let d=await $n(e,{hash:i});if(d.status!=="success")throw console.error("world deploy failed",d),new Error("world deploy failed");let l=N(d.logs);f("deployed custom world to",l.address,"at block",l.deployBlock);let m=await Wo(e,{chain:e.chain??null,address:l.address,abi:T,functionName:"initialize",args:[n.InitModule.address]});await B({client:e,hashes:[m],debugLabel:"world init"});let p=await Wo(e,{chain:e.chain??null,address:l.address,abi:T,functionName:"transferOwnership",args:[En({type:"namespace",namespace:"",name:""}),e.account.address]});return await B({client:e,hashes:[p],debugLabel:"world ownership transfer"}),{...l,stateBlock:l.deployBlock}}import{uniqueBy as Vn}from"@latticexyz/common/utils";function Eo({path:e,name:o}){return`${e}:${o}`}function Lo(e){let o=Object.fromEntries(e.map(r=>[Eo(r),r])),t={getAddress:({path:r,name:n,deployer:s})=>{let a=o[Eo({path:r,name:n})];if(!a)throw new Error(`Could not find library for bytecode placeholder ${r}:${n}`);return a.address??={},a.address[s]??=a.prepareDeploy(s,t).address,a.address[s]}};return t}async function Fo({config:e,client:o,tables:t,systems:r,libraries:n,modules:s=[],artifacts:a,salt:i,worldAddress:d,deployerAddress:l}){let m=l??await Ge(o),p=d?await ye(o,d):e.deploy.customWorld?await $o({client:o,deployerAddress:m,artifacts:a,customWorld:e.deploy.customWorld}):await co(o,m,i??`0x${Un(32).toString("hex")}`,e.deploy.upgradeableWorldImplementation);if(!Qe.includes(p.storeVersion))throw new Error(`Unsupported Store version: ${p.storeVersion}`);if(!Ze.includes(p.worldVersion))throw new Error(`Unsupported World version: ${p.worldVersion}`);let g=Lo(n);await M({client:o,deployerAddress:m,contracts:[...n.map(h=>({bytecode:h.prepareDeploy(m,g).bytecode,deployedBytecodeSize:h.deployedBytecodeSize,debugLabel:`${h.path}:${h.name} library`})),...r.map(h=>({bytecode:h.prepareDeploy(m,g).bytecode,deployedBytecodeSize:h.deployedBytecodeSize,debugLabel:`${Nn(h)} system`})),...s.map(h=>({bytecode:h.prepareDeploy(m,g).bytecode,deployedBytecodeSize:h.deployedBytecodeSize,debugLabel:`${h.name} module`}))]});let C=await Po({client:o,worldDeploy:p,resourceIds:[...t.map(({tableId:h})=>h),...r.map(({systemId:h})=>h)]});await B({client:o,hashes:C,debugLabel:"namespace registrations"});let u=await wo({client:o,worldDeploy:p,tables:t}),x=await Ao({client:o,deployerAddress:m,libraryMap:g,worldDeploy:p,systems:r});await B({client:o,hashes:[...u,...x],debugLabel:"table and system registrations"});let S=await vo({client:o,worldDeploy:p,functions:r.flatMap(h=>h.worldFunctions)}),b=await ue({client:o,deployerAddress:m,libraryMap:g,worldDeploy:p,modules:s}),w=Vn([...t,...r].filter(({namespace:h,namespaceLabel:k})=>k!==h).map(({namespace:h,namespaceLabel:k})=>({resourceId:zn({type:"namespace",namespace:h,name:""}),tag:"label",value:k})),h=>h.resourceId),c=t.filter(h=>h.label!==h.name).map(({tableId:h,label:k})=>({resourceId:h,tag:"label",value:k})),y=r.flatMap(({name:h,systemId:k,label:Q,abi:ve,worldAbi:De})=>[...Q!==h?[{resourceId:k,tag:"label",value:Q}]:[],{resourceId:k,tag:"abi",value:ve.join(`
19
- `)},{resourceId:k,tag:"worldAbi",value:De.join(`
20
- `)}]),A=await Ho({client:o,deployerAddress:m,libraryMap:g,worldDeploy:p,tags:[...w,...c,...y],valueToHex:Fn});return await B({client:o,hashes:[...S,...b,...A],debugLabel:"remaining transactions"}),f("deploy complete"),p}import{createWalletClient as Cs,http as As,isHex as Ss}from"viem";import{privateKeyToAccount as vs}from"viem/accounts";import{loadConfig as Ds,resolveConfigPath as Ts}from"@latticexyz/config/node";import{getOutDirectory as ks,getRpcUrl as Ps}from"@latticexyz/common/foundry";import q from"chalk";import{MUDError as Re}from"@latticexyz/common/errors";import Uo from"path";import{loadSystemsManifest as Qn,resolveSystems as Zn}from"@latticexyz/world/node";import{isHex as Vo,toFunctionSelector as _o,toFunctionSignature as Ko}from"viem";import{readFileSync as _n}from"fs";import Kn from"path";import{MUDError as we}from"@latticexyz/common/errors";import{size as Jn}from"viem";function J(e,o,t){let r,n=Kn.join(t,e,o+".json");try{r=JSON.parse(_n(n,"utf8"))}catch{throw new we(`Error reading file at ${n}`)}let s=r?.bytecode?.object;if(!s)throw new we(`No bytecode found in ${n}`);let a=r?.deployedBytecode?.object;if(!a)throw new we(`No deployed bytecode found in ${n}`);let i=r?.abi;if(!i)throw new we(`No ABI found in ${n}`);let d=ge(r?.bytecode?.linkReferences??{});return{abi:i,bytecode:s,placeholders:d,deployedBytecodeSize:Jn(a)}}import{groupBy as Xn}from"@latticexyz/common/utils";import{readFileSync as Yn}from"fs";import{globSync as Gn}from"glob";import qn from"toposort";function zo(e,o,t){let r=qn(e.flatMap(n=>t(n).map(s=>[o(n),s])));return[...e].sort((n,s)=>r.indexOf(o(n))-r.indexOf(o(s)))}function No(e){let t=Gn(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).sort().map(r=>JSON.parse(Yn(r,"utf8"))).flatMap(r=>{if(!r.metadata)return[];let n=Object.keys(r.metadata.settings.compilationTarget)[0],s=r.metadata.settings.compilationTarget[n],a=r.bytecode.linkReferences;return Object.entries(a).flatMap(([i,d])=>Object.keys(d).map(l=>({path:i,name:l,dependentPath:n,dependentName:s})))});return zo(t,r=>`${r.path}:${r.name}`,r=>[`${r.dependentPath}:${r.dependentName}`])}import{findUp as es}from"find-up";import{createRequire as os}from"node:module";async function Jo({rootDir:e,config:o,forgeOutDir:t}){let r=await es("package.json");if(!r)throw new Error("Could not find package.json to import relative to.");let n=os(r),s=o.modules.flatMap(u=>u.artifactPath==null?[]:[Uo.join(n.resolve(u.artifactPath),"../../")]),a=[t,...s].flatMap(u=>No(u).map(x=>{let S=J(Uo.basename(x.path),x.name,u);return{path:x.path,name:x.name,abi:S.abi,prepareDeploy:$(S.bytecode,S.placeholders),deployedBytecodeSize:S.deployedBytecodeSize}})),d=J("System.sol","System",t).abi.filter(u=>u.type==="function").map(Ko),l=await Zn({rootDir:e,config:o}),m=await Qn({rootDir:e,config:o}),p=l.filter(u=>!u.deploy.disabled).map(u=>{let x=m.systems.find(({systemId:y})=>y===u.systemId);if(!x)throw new Error(`System "${u.label}" not found in systems manifest. Run \`mud build\` before trying again.`);let S=J(`${u.label}.sol`,u.label,t),b=u.deploy.registerWorldFunctions?S.abi.filter(y=>y.type==="function").map(Ko).filter(y=>!d.includes(y)).map(y=>{let A=u.namespace===""?y:`${u.namespace}__${y}`;return{signature:A,selector:_o(A),systemId:u.systemId,systemFunctionSignature:y,systemFunctionSelector:_o(y)}}):[],w=u.accessList.filter(y=>Vo(y)),c=u.accessList.filter(y=>!Vo(y)).map(y=>l.find(h=>h.label===y).systemId);return{...u,allowAll:u.openAccess,allowedAddresses:w,allowedSystemIds:c,prepareDeploy:$(S.bytecode,S.placeholders),deployedBytecodeSize:S.deployedBytecodeSize,worldFunctions:b,abi:x.abi,worldAbi:x.worldAbi}}),g=Xn(p,u=>u.systemId),C=Array.from(g.values()).filter(u=>u.length>1).flat();if(C.length){let u=C.map(x=>x.name);throw new Error(`Found systems with overlapping system ID: ${u.join(", ")}.
21
-
22
- System IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`)}return{systems:p,libraries:a}}import{getChainId as Ms}from"viem/actions";import{existsSync as ts}from"fs";import rs from"path";import ns from"chalk";import{getScriptDirectory as ss,forge as as}from"@latticexyz/common/foundry";async function qo(e,o,t,r,n,s){let a=n?.replaceAll("\\","").split(" ")??[],i=rs.join(await ss(),e+".s.sol");if(!ts(i)){console.log(`No script at ${i}, skipping post deploy hook`);return}console.log(ns.blue(`Executing post deploy script at ${i}`)),await as(["script",e,"--broadcast","--sig","run(address)",o,"--rpc-url",t,"-vvv",s?"--aws":"",...a],{profile:r})}import{kmsKeyToAccount as Bs}from"@latticexyz/common/kms";import Go from"node:path";import{encodeField as ls}from"@latticexyz/protocol-parser/internal";import{bytesToHex as cs}from"viem";import{createRequire as is}from"node:module";import{findUp as ds}from"find-up";async function Yo({packageJsonPath:e,artifactPath:o}){let t;try{let r=e??await ds("package.json",{cwd:process.cwd()});if(!r)throw new Error("Could not find package.json to import relative to.");t=is(r)(o)}catch(r){throw console.error(),console.error("Could not import contract artifact at",o),console.error(),r}return be(t)}import{resolveWithContext as ms}from"@latticexyz/world/internal";var ps={KeysWithValueModule:"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json",KeysInTableModule:"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json",UniqueEntityModule:"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json",Unstable_CallWithSignatureModule:"@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json"};async function xe(e,o){return await Promise.all(e.modules.map(async r=>{let n=r.artifactPath;if(!n)if(r.name)n=ps[r.name]??Go.join(o,`${r.name}.sol`,`${r.name}.json`),console.warn(["","\u26A0\uFE0F Your `mud.config.ts` is using a module with a `name`, but this option is deprecated.","","To resolve this, you can replace this:","",` name: ${JSON.stringify(r.name)}`,"","with this:","",` artifactPath: ${JSON.stringify(n)}`,""].join(`
23
- `));else throw new Error("No `artifactPath` provided for module.");let s=Go.basename(n,".json"),a=await Yo({artifactPath:n}),i=r.args.map(d=>ms(d,{config:e})).map(d=>{let l=d.value instanceof Uint8Array?cs(d.value):d.value;return ls(d.type,l)});if(i.length>1)throw new Error(`${s} module should only have 0-1 args, but had ${i.length} args.`);return{name:s,installAsRoot:r.root,installData:i.length===0?"0x":i[0],prepareDeploy:$(a.bytecode,a.placeholders),deployedBytecodeSize:a.deployedBytecodeSize,abi:a.abi}}))}import{findContractArtifacts as Os}from"@latticexyz/world/node";import{getAutomine as fs,getBlock as Qo,setAutomine as ys,setIntervalMining as us}from"viem/actions";import{getAction as te}from"viem/utils";async function Xo(e){let o=await gs(e).catch(()=>{});if(!(!o||o.type==="automine"))return O("Enabling automine"),await Zo(e,{type:"automine"}),{reset:()=>(O("Disabling automine"),Zo(e,o))}}async function gs(e){let o={mode:"anvil",...e};return await te(o,fs,"getAutomine")({})?{type:"automine"}:{type:"interval",blockTime:await bs(e)}}async function Zo(e,o){o.type==="automine"?await te(e,ys,"setAutomine")(!0):await te(e,us,"setIntervalMining")({interval:o.blockTime})}async function bs(e){let o=await te(e,Qo,"getBlock")({blockTag:"latest"}),t=await te(e,Qo,"getBlock")({blockNumber:o.number-1n}),r=o.timestamp-t.timestamp;return Number(r)}var I={configPath:{type:"string",desc:"Path to the MUD config file"},printConfig:{type:"boolean",desc:"Print the resolved config"},profile:{type:"string",desc:"The foundry profile to use"},saveDeployment:{type:"boolean",desc:"Save the deployment info to a file",default:!0},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},deployerAddress:{type:"string",desc:"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)"},worldAddress:{type:"string",desc:"Deploy to an existing World at the given address"},skipBuild:{type:"boolean",desc:"Skip rebuilding the contracts before deploying"},alwaysRunPostDeploy:{type:"boolean",desc:"Always run PostDeploy.s.sol after each deploy (including during upgrades). By default, PostDeploy.s.sol is only run once after a new world is deployed."},forgeScriptOptions:{type:"string",description:"Options to pass to forge script PostDeploy.s.sol"},salt:{type:"string",desc:"The deployment salt to use. Defaults to a random salt."},kms:{type:"boolean",desc:"Deploy the World with an AWS KMS key instead of local private key."}};async function Y(e){let o=e.salt;if(o!=null&&!Ss(o))throw new Re("Expected hex string for salt");let t=e.profile??process.env.FOUNDRY_PROFILE,r=await Ts(e.configPath),n=await Ds(r),s=Ce.dirname(r);e.printConfig&&console.log(q.green(`
24
- Resolved config:
25
- `),JSON.stringify(n,null,2));let a=await ks(t),i=e.rpc??await Ps(t);console.log(q.bgBlue(q.whiteBright(`
26
- Deploying MUD contracts${t?" with profile "+t:""} to RPC ${i}
27
- `))),e.skipBuild||await F({rootDir:s,config:n,foundryProfile:t});let{systems:d,libraries:l}=await Jo({rootDir:s,config:n,forgeOutDir:a}),m=await Os({forgeOutDir:a}),p=await xe(n,a),g=Object.values(n.namespaces).flatMap(c=>Object.values(c.tables)).filter(c=>!c.deploy.disabled),C=await(async()=>{if(e.kms){let c=process.env.AWS_KMS_KEY_ID;if(!c)throw new Re("Missing `AWS_KMS_KEY_ID` environment variable. This is required when using with `--kms` option.");return await Bs({keyId:c})}else{let c=process.env.PRIVATE_KEY;if(!c)throw new Re(`Missing PRIVATE_KEY environment variable.
28
- Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
29
- in your contracts directory to use the default anvil private key.`);return vs(c)}})(),u=Cs({transport:As(i,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:C});console.log("Deploying from",u.account.address);let x=await Xo(u),S=Date.now(),b=await Fo({config:n,deployerAddress:e.deployerAddress,salt:o,worldAddress:e.worldAddress,client:u,tables:g,systems:d,libraries:l,modules:p,artifacts:m});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await qo(n.deploy.postDeployScript,b.address,i,t,e.forgeScriptOptions,!!e.kms),await x?.reset(),console.log(q.green("Deployment completed in",(Date.now()-S)/1e3,"seconds"));let w={worldAddress:b.address,blockNumber:Number(b.deployBlock)};if(e.saveDeployment){let c=await Ms(u),y=Ce.join(n.deploy.deploysDirectory,c.toString());ws(y,{recursive:!0}),We(Ce.join(y,"latest.json"),JSON.stringify(w,null,2)),We(Ce.join(y,Date.now()+".json"),JSON.stringify(w,null,2));let A=[1337,31337],h=hs(n.deploy.worldsFile)?JSON.parse(xs(n.deploy.worldsFile,"utf-8")):{};h[c]={address:w.worldAddress,blockNumber:A.includes(c)?void 0:w.blockNumber},We(n.deploy.worldsFile,JSON.stringify(h,null,2)),console.log(q.bgGreen(q.whiteBright(`
30
- Deployment result (written to ${n.deploy.worldsFile} and ${y}):
31
- `)))}return console.log(w),b}var Is={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(I)},async handler(e){try{await Y(e)}catch(o){se(o),process.exit(1)}process.exit(0)}},et=Is;import Hs from"node:path";import{loadConfig as Ws,resolveConfigPath as Rs}from"@latticexyz/config/node";import{worldgen as js}from"@latticexyz/world/node";var $s={command:"worldgen",describe:"Autogenerate interfaces for Systems and World based on existing contracts and the config file",builder(e){return e.options({configPath:{type:"string",desc:"Path to the MUD config file"},clean:{type:"boolean",desc:"Clear the worldgen directory before generating new interfaces (defaults to true)",default:!0}})},async handler(e){await Es(e),process.exit(0)}};async function Es(e){let o=await Rs(e.configPath),t=await Ws(o),r=Hs.dirname(o);await js({rootDir:r,config:t,clean:e.clean})}var ot=$s;import re from"chalk";import{readFileSync as Us,writeFileSync as Vs}from"fs";import $e from"path";import{MUDError as G}from"@latticexyz/common/errors";var tt={name:"@latticexyz/cli",version:"2.2.14",description:"Command line interface for mud",repository:{type:"git",url:"https://github.com/latticexyz/mud.git",directory:"packages/cli"},license:"MIT",type:"module",exports:{".":"./dist/index.js"},typesVersions:{"*":{index:["./dist/index.d.ts"]}},bin:{mud:"./bin/mud.js"},files:["bin","dist"],scripts:{build:"pnpm run build:js && pnpm run build:test-tables","build:js":"tsup && chmod +x ./dist/mud.js","build:test-tables":"tsx ./scripts/generate-test-tables.ts",clean:"pnpm run clean:js && pnpm run clean:test-tables","clean:js":"shx rm -rf dist","clean:test-tables":"shx rm -rf src/**/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ark/util":"catalog:","@aws-sdk/client-kms":"^3.556.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/block-logs-stream":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-module-metadata":"workspace:*",abitype:"catalog:","asn1.js":"^5.4.1",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",dotenv:"^16.0.3",execa:"^7.0.0","find-up":"^6.3.0",glob:"^10.4.2",openurl:"^1.1.1","p-queue":"^7.4.1","p-retry":"^5.1.2",path:"^0.12.7",rxjs:"7.5.5","throttle-debounce":"^5.0.0",toposort:"^2.0.2",typescript:"5.4.2",viem:"catalog:",yargs:"^17.7.1",zod:"3.23.8","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/node":"^18.15.11","@types/openurl":"^1.0.0","@types/throttle-debounce":"^5.0.0","@types/toposort":"^2.0.6","@types/yargs":"^17.0.10","ds-test":"https://github.com/dapphub/ds-test.git#e282159d5170298eb2455a6c05280ab5a73a4ef0","forge-std":"https://github.com/foundry-rs/forge-std.git#74cfb77e308dd188d2f58864aaf44963ae6b88b1",tsup:"^6.7.0",vitest:"0.34.6"}};import{globSync as _s}from"glob";import{ZodError as Fs,z as rt}from"zod";var zs=rt.object({MUD_PACKAGES:rt.string().transform(e=>JSON.parse(e))});function Ns(){try{return zs.parse({MUD_PACKAGES:'{"@latticexyz/abi-ts":{"localPath":"packages/abi-ts"},"@latticexyz/block-logs-stream":{"localPath":"packages/block-logs-stream"},"@latticexyz/cli":{"localPath":"packages/cli"},"@latticexyz/common":{"localPath":"packages/common"},"@latticexyz/config":{"localPath":"packages/config"},"create-mud":{"localPath":"packages/create-mud"},"@latticexyz/dev-tools":{"localPath":"packages/dev-tools"},"@latticexyz/explorer":{"localPath":"packages/explorer"},"@latticexyz/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@latticexyz/react":{"localPath":"packages/react"},"@latticexyz/recs":{"localPath":"packages/recs"},"@latticexyz/schema-type":{"localPath":"packages/schema-type"},"solhint-config-mud":{"localPath":"packages/solhint-config-mud"},"solhint-plugin-mud":{"localPath":"packages/solhint-plugin-mud"},"@latticexyz/stash":{"localPath":"packages/stash"},"@latticexyz/store-indexer":{"localPath":"packages/store-indexer"},"@latticexyz/store-sync":{"localPath":"packages/store-sync"},"@latticexyz/store":{"localPath":"packages/store"},"@latticexyz/utils":{"localPath":"packages/utils"},"@latticexyz/world-module-erc20":{"localPath":"packages/world-module-erc20"},"@latticexyz/world-module-metadata":{"localPath":"packages/world-module-metadata"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof Fs){let{...o}=e.format();console.error(`
32
- Missing or invalid environment variables:
33
-
34
- ${Object.keys(o).join(`
35
- `)}
36
- `),process.exit(1)}throw e}}var je=Ns().MUD_PACKAGES;var Ks={command:"set-version",describe:"Set MUD version in all package.json files and optionally backup the previously installed version",builder(e){return e.options({mudVersion:{alias:"v",type:"string",description:"Set MUD to the given version"},tag:{alias:"t",type:"string",description:"Set MUD to the latest version with the given tag from npm"},commit:{alias:"c",type:"string",description:"Set MUD to the version based on a given git commit hash from npm"},link:{alias:"l",type:"string",description:"Relative path to the local MUD root directory to link"}})},async handler(e){try{let o=["mudVersion","link","tag","commit","restore"],t=o.reduce((n,s)=>e[s]?n+1:n,0);if(t===0)throw new G(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new G(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await Js(e));let r=_s("**/package.json").sort().filter(n=>!n.includes("node_modules"));for(let n of r)qs(n,e)}catch(o){se(o)}finally{process.exit(0)}}};async function Js(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(re.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${tt.name}`)).json()}catch{throw new G("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new G(`Could not find npm version with tag "${e.tag}"`);return console.log(re.green(`Latest version with tag ${e.tag}: ${t}`)),t}if(e.commit){let t=e.commit.substring(0,8),r=Object.keys(o.versions).find(n=>n.includes(t));if(!r)throw new G(`Could not find npm version based on commit "${e.commit}"`);return console.log(re.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function qs(e,o){let{link:t}=o,{mudVersion:r}=o,n=Ys(e),s=Object.keys(je),a={};for(let l in n.dependencies)s.includes(l)&&(a[l]=n.dependencies[l]);let i={};for(let l in n.devDependencies)s.includes(l)&&(i[l]=n.devDependencies[l]);for(let l in n.dependencies)s.includes(l)&&(n.dependencies[l]=d(l,"dependencies"));for(let l in n.devDependencies)s.includes(l)&&(n.devDependencies[l]=d(l,"devDependencies"));return Vs(e,JSON.stringify(n,null,2)+`
37
- `),console.log(`Updating ${e}`),nt(a,n.dependencies),nt(i,n.devDependencies),n;function d(l,m){return t&&(r=Gs(e,t,l)),r||n[m][l]}}function Ys(e){try{let o=Us(e,"utf8");return JSON.parse(o)}catch{throw new G("Could not read JSON at "+e)}}function nt(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${re.red(e[t])} -> ${re.green(o[t])}`)}function Gs(e,o,t){let r=$e.relative($e.dirname(e),process.cwd());return"link:"+$e.join(r,o,je[t].localPath)}var st=Ks;import{anvil as Qs,forge as Zs,getRpcUrl as Xs}from"@latticexyz/common/foundry";import ea from"chalk";var oa={...I,port:{type:"number",description:"Port to run internal node for fork testing on",default:4242},worldAddress:{type:"string",description:"Address of an existing world contract. If provided, deployment is skipped and the RPC provided in the foundry.toml is used for fork testing."},forgeOptions:{type:"string",description:"Options to pass to forge test"}},ta={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(oa)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Qs(n)}let o=e.worldAddress?await Xs(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await Y({...e,saveDeployment:!1,rpc:o})).address;console.log(ea.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Zs(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},at=ta;import ra from"node:path";import it from"node:fs";import{loadConfig as na,resolveConfigPath as sa}from"@latticexyz/config/node";import{MUDError as dt}from"@latticexyz/common/errors";import{cast as aa,getRpcUrl as ia}from"@latticexyz/common/foundry";import da from"@latticexyz/world/mud.config";import{createClient as la,http as ca}from"viem";import{getChainId as ma,readContract as pa}from"viem/actions";import{resolveSystems as fa}from"@latticexyz/world/node";var ya=da.namespaces.world.tables.Systems.tableId;function ua(e,o){if(!it.existsSync(e))throw new dt(`Missing expected worlds.json file at "${e}"`);let t=JSON.parse(it.readFileSync(e,"utf-8"));if(!t[o])throw new dt(`Missing chain ID ${o} in "${e}"`);return t[o].address}var ga={command:"trace",describe:"Display the trace of a transaction",builder(e){return e.options({tx:{type:"string",required:!0,description:"Transaction hash to replay"},worldAddress:{type:"string",description:"World contract address. Defaults to the value from worlds.json, based on rpc's chainId"},configPath:{type:"string",description:"Path to the MUD config file"},profile:{type:"string",description:"The foundry profile to use"},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){let o=await sa(e.configPath),t=ra.dirname(o),r=e.profile??process.env.FOUNDRY_PROFILE,n=e.rpc??await ia(r),s=await na(o),a=la({transport:ca(n)}),i=await ma(a),d=e.worldAddress??ua(s.deploy.worldsFile,i),l=await fa({rootDir:t,config:s}),m=await Promise.all(l.map(async g=>({label:g.label,address:await pa(a,{abi:T,address:d,functionName:"getField",args:[ya,[g.systemId],0]})}))),p=await aa(["run","--label",`${d}:World`,...m.map(({label:g,address:C})=>["--label",`${C}:${g}`]).flat(),`${e.tx}`]);console.log(p),process.exit(0)}},lt=ga;import{anvil as ba,getScriptDirectory as ha,getSrcDirectory as wa}from"@latticexyz/common/foundry";import j from"chalk";import xa from"chokidar";import{loadConfig as Ca,resolveConfigPath as Aa}from"@latticexyz/config/node";import Sa from"path";import{homedir as va}from"os";import{rmSync as Da}from"fs";import{BehaviorSubject as Ta,debounceTime as ka,exhaustMap as Pa,filter as Ma}from"rxjs";import{isDefined as Ba}from"@latticexyz/common/utils";var Oa={rpc:I.rpc,configPath:I.configPath,alwaysRunPostDeploy:I.alwaysRunPostDeploy,forgeScriptOptions:I.forgeScriptOptions,worldAddress:I.worldAddress},Ia={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(Oa)},async handler(e){let o=e.rpc,t=e.configPath??await Aa(e.configPath),r=await wa(),n=await ha(),s=await Ca(t);if(!e.rpc){console.log(j.gray("Cleaning devnode cache"));let l=va();Da(Sa.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),ba(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let a=new Ta(Date.now());xa.watch([t,r,n],{ignoreInitial:!0}).on("all",async(l,m)=>{m.includes(t)&&(console.log(j.blue("Config changed, queuing deploy\u2026")),a.next(Date.now())),(m.includes(r)||m.includes(n))&&(m.includes(s.codegen.outputDirectory)||(console.log(j.blue("Contracts changed, queuing deploy\u2026")),a.next(Date.now())))});let i=e.worldAddress;a.pipe(ka(200),Pa(async l=>{i&&console.log(j.blue("Rebuilding and upgrading world\u2026"));try{let m=await Y({...e,configPath:t,rpc:o,rpcBatch:!1,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,deployerAddress:void 0,worldAddress:i,salt:"0x",kms:void 0});return i=m.address,l<a.value?a.next(a.value):console.log(j.gray(`
38
- Waiting for file changes\u2026
39
- `)),m}catch(m){console.error(j.bgRed(j.whiteBright(`
40
- Error while attempting deploy
41
- `))),console.error(m),console.log(j.gray(`
42
- Waiting for file changes\u2026
43
- `))}}),Ma(Ba)).subscribe()}},ct=Ia;import{getCreate2Address as mt,sliceHex as Wa,zeroHash as Ra}from"viem";import{forge as Ha}from"@latticexyz/common/foundry";async function E(e){let o=["verify-contract",e.address,e.name,"--rpc-url",e.rpc];e.verifier&&o.push("--verifier",e.verifier),e.verifierUrl&&o.push("--verifier-url",e.verifierUrl),await Ha(o,{cwd:e.cwd})}import ja from"p-queue";import{MUDError as $a}from"@latticexyz/common/errors";import{getStorageAt as Ea}from"viem/actions";import{execa as Ee}from"execa";var La="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function pt({client:e,rpc:o,systems:t,modules:r,worldAddress:n,deployerAddress:s,verifier:a,verifierUrl:i}){let d=s??await ie(e);if(!d)throw new $a("No deployer address provided or found.");let l=await Ea(e,{address:n,slot:La}),m=l&&l!==Ra,p=new ja({concurrency:4});if(t.map(({name:g,bytecode:C})=>p.add(()=>E({name:g,rpc:o,verifier:a,verifierUrl:i,address:mt({from:d,bytecode:C,salt:D})}).catch(u=>{console.error(`Error verifying system contract ${g}:`,u)}))),a==="sourcify")if(await Ee("npm",["install"],{cwd:"node_modules/@latticexyz/store"}),await Ee("npm",["install"],{cwd:"node_modules/@latticexyz/world"}),await Ee("npm",["install"],{cwd:"node_modules/@latticexyz/world-modules"}),Object.entries(m?ce(d):le(d)).map(([g,{bytecode:C}])=>p.add(()=>E({cwd:"node_modules/@latticexyz/world",name:g,rpc:o,verifier:a,verifierUrl:i,address:mt({from:d,bytecode:C,salt:D})}).catch(u=>{console.error(`Error verifying world factory contract ${g}:`,u)}))),r.map(({name:g,prepareDeploy:C})=>{let{address:u}=C(d);return p.add(()=>E({cwd:"node_modules/@latticexyz/world-modules",name:g,rpc:o,verifier:a,verifierUrl:i,address:u}).catch(x=>{console.error(`Error verifying module contract ${g}:`,x)}))}),m){let g=Wa(l,-20);p.add(()=>E({cwd:"node_modules/@latticexyz/world",name:"WorldProxy",rpc:o,verifier:a,verifierUrl:i,address:n}).catch(C=>{console.error("Error verifying WorldProxy contract:",C)})),p.add(()=>E({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:a,verifierUrl:i,address:g}).catch(C=>{console.error("Error verifying World contract:",C)}))}else p.add(()=>E({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:a,verifierUrl:i,address:n}).catch(g=>{console.error("Error verifying World contract:",g)}));else console.log(""),console.log(`Note: MUD is currently unable to verify store, world, and world-modules contracts with ${a}. We are planning to expand support in a future version.`),console.log("")}import{loadConfig as Fa,resolveConfigPath as za}from"@latticexyz/config/node";import{resolveSystems as Na}from"@latticexyz/world/node";import{getOutDirectory as Ua,getRpcUrl as Va}from"@latticexyz/common/foundry";import{createWalletClient as _a,http as Ka}from"viem";import ft from"chalk";import Ja from"node:path";var qa={deployerAddress:{type:"string",desc:"Deploy using an existing deterministic deployer (https://github.com/Arachnid/deterministic-deployment-proxy)"},worldAddress:{type:"string",required:!0,desc:"Verify an existing World at the given address"},configPath:{type:"string",desc:"Path to the MUD config file"},profile:{type:"string",desc:"The foundry profile to use"},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},verifier:{type:"string",desc:"The verifier to use. Defaults to blockscout",default:"blockscout"},verifierUrl:{type:"string",desc:"The verification provider."}},Ya={command:"verify",describe:"Verify contracts",builder(e){return e.options(qa)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await za(e.configPath),r=Ja.dirname(t),n=await Fa(t),s=await Ua(o),a=e.rpc??await Va(o);console.log(ft.bgBlue(ft.whiteBright(`
44
- Verifying MUD contracts${o?" with profile "+o:""} to RPC ${a}
45
- `)));let i=_a({transport:Ka(a,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),l=(await Na({rootDir:r,config:n})).map(p=>{let g=J(`${p.name}.sol`,p.name,s);return{name:p.name,bytecode:g.bytecode}}),m=await xe(n,s);await pt({client:i,rpc:a,systems:l,modules:m,deployerAddress:e.deployerAddress,worldAddress:e.worldAddress,verifier:e.verifier,verifierUrl:e.verifierUrl})}},yt=Ya;import{getRpcUrl as ai}from"@latticexyz/common/foundry";import{createClient as ii,http as di}from"viem";import Se from"chalk";import{hexToString as Le,parseAbiItem as ut,stringToHex as Fe}from"viem";import{getSchemaTypes as Qa}from"@latticexyz/protocol-parser/internal";import{hexToResource as Za,resourceToHex as Xa}from"@latticexyz/common";import ze from"@latticexyz/world-module-metadata/mud.config";import L from"node:path";import Ae from"node:fs/promises";import{getFunctions as ei}from"@latticexyz/world/internal";import{abiToInterface as gt,formatSolidity as bt,formatTypescript as oi}from"@latticexyz/common/codegen";var W=O.extend("pull"),Ga=O.extend("pull");W.log=console.debug.bind(console);Ga.log=console.error.bind(console);import{defineWorld as ti}from"@latticexyz/world";import{findUp as ri}from"find-up";import{isDefined as ht}from"@latticexyz/common/utils";var ni=new Set(["store","world","metadata"]);function wt(e){return Xa({type:"namespace",namespace:e,name:""})}var ne=class extends Error{constructor(t){super(`Attempted to write file at "${t}", but it already exists.`);this.filename=t}name="WriteFileExistsError"};async function xt({rootDir:e,client:o,worldAddress:t,replace:r}){let n=r??await ri(".git",{cwd:e})!=null,s=await ye(o,t),a=await V({client:o,worldDeploy:s}),i=a.map(Za).filter(b=>!ni.has(b.namespace)),d=await me({client:o,worldDeploy:s}),l=Object.fromEntries((await Promise.all(a.map(async b=>{let{value:w}=await K({client:o,worldDeploy:s,table:ze.tables.metadata__ResourceTag,key:{resource:b,tag:Fe("label",{size:32})}}),c=Le(w);return[b,c===""?null:c]}))).filter(([,b])=>b!=null));l[wt("")]??="root";let m=await ei({client:o,worldAddress:s.address,fromBlock:s.deployBlock,toBlock:s.stateBlock}),p=i.filter(b=>b.type==="namespace"),g=await Promise.all(i.filter(b=>b.type==="system").map(async({namespace:b,name:w,resourceId:c})=>{let y=wt(b),A=l[c]??w.replace(/(S(y(s(t(e(m)?)?)?)?)?)?$/,"System"),[h,k]=await Promise.all([K({client:o,worldDeploy:s,table:ze.tables.metadata__ResourceTag,key:{resource:c,tag:Fe("abi",{size:32})}}).then(v=>Le(v.value)).then(v=>v!==""?v.split(`
46
- `):[]),K({client:o,worldDeploy:s,table:ze.tables.metadata__ResourceTag,key:{resource:c,tag:Fe("worldAbi",{size:32})}}).then(v=>Le(v.value)).then(v=>v!==""?v.split(`
47
- `):[])]),Q=m.filter(v=>v.systemId===c),ve=(h.length?h:Q.map(v=>`function ${v.systemFunctionSignature}`)).map(v=>{try{return ut(v)}catch{W(`Skipping invalid system signature: ${v}`)}}).filter(ht),De=(k.length?k:Q.map(v=>`function ${v.signature}`)).map(v=>{try{return ut(v)}catch{W(`Skipping invalid world signature: ${v}`)}}).filter(ht);return{namespaceId:y,namespaceLabel:l[y]??b,label:A,systemId:c,namespace:b,name:w,abi:ve,worldAbi:De}}));W("generating config");let C={namespaces:Object.fromEntries(p.map(({namespace:b,resourceId:w})=>{let c=l[w]??b;return[c,{...c!==b?{namespace:b}:null,tables:Object.fromEntries(d.filter(y=>y.namespace===b).map(y=>{let A=l[y.tableId]??y.name;return[A,{...A!==y.name?{name:y.name}:null,...y.type!=="table"?{type:y.type}:null,schema:Qa(y.schema),key:y.key,deploy:{disabled:!0}}]}))}]}))};W("validating config");let u=ti(C);W("writing config"),await Ne(L.join(e,"mud.config.ts"),await oi(`
48
- import { defineWorld } from "@latticexyz/world";
49
-
50
- export default defineWorld(${JSON.stringify(C)});
51
- `),{overwrite:n});let x=L.join(u.sourceDirectory,"remote");n&&await Ae.rm(x,{recursive:!0,force:!0});for(let b of g.filter(w=>w.abi.length)){let w=`I${b.label}`,c=L.join(x,"namespaces",b.namespaceLabel,`${w}.sol`);W("writing system interface",w,"to",c);let y=gt({name:w,systemId:b.systemId,abi:b.abi});await Ne(L.join(e,c),await bt(y),{overwrite:n})}let S=g.flatMap(b=>b.worldAbi);if(S.length){let b="IWorldSystems",w=L.join(x,`${b}.sol`);W("writing world systems interface to",w);let c=gt({name:b,abi:S});await Ne(L.join(e,w),await bt(c),{overwrite:n})}return{config:u}}async function si(e){return Ae.access(e).then(()=>!0,()=>!1)}async function Ne(e,o,t={}){if(!t.overwrite&&await si(e))throw new ne(e);await Ae.mkdir(L.dirname(e),{recursive:!0}),await Ae.writeFile(e,o)}import li from"node:path";var ci={worldAddress:{type:"string",required:!0,desc:"Remote world address"},profile:{type:"string",desc:"The foundry profile to use"},rpc:{type:"string",desc:"The RPC URL to use. Defaults to the RPC url from the local foundry.toml"},rpcBatch:{type:"boolean",desc:"Enable batch processing of RPC requests in viem client (defaults to batch size of 100 and wait of 1s)"},replace:{type:"boolean",desc:"Replace existing files and directories with data from remote world."}},mi={command:"pull",describe:"Pull mud.config.ts and interfaces from an existing world.",builder(e){return e.options(ci)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=e.rpc??await ai(o),r=ii({transport:di(t,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})});console.log(Se.bgBlue(Se.whiteBright(`
52
- Pulling MUD config from world at ${e.worldAddress}
53
- `)));let n=process.cwd();try{let{config:s}=await xt({rootDir:n,client:r,worldAddress:e.worldAddress,replace:e.replace});await F({rootDir:n,config:s,foundryProfile:o})}catch(s){if(s instanceof ne){console.log(),console.log(Se.bgRed(Se.whiteBright(" Error "))),console.log(` Attempted to write file at "${li.relative(n,s.filename)}", but it already exists.`),console.log(),console.log(" To overwrite files, use `--replace` when running this command."),console.log();return}throw s}}},Ct=mi;var Ag=[Ue,et,Ve,pi,_e,Ke,ot,st,at,lt,ct,fi,yt,Ct];export{Ag as commands};
54
- //# sourceMappingURL=commands-TAUKPNBI.js.map