@latticexyz/cli 2.2.17-ffefc8f000769d5ca625dd19290007a853a21788 → 2.2.18-04065f05390b9975400db7e15b185a86976ba199

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-R4UWN5VJ.js"),{commands:t}=await import("./commands-6WDCECG5.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-R4UWN5VJ.js"),{commands:t}=await import("./commands-TC2F5WA4.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.17-ffefc8f000769d5ca625dd19290007a853a21788",
3
+ "version": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
4
4
  "description": "Command line interface for mud",
5
5
  "repository": {
6
6
  "type": "git",
@@ -49,19 +49,19 @@
49
49
  "yargs": "^17.7.1",
50
50
  "zod": "3.23.8",
51
51
  "zod-validation-error": "^1.3.0",
52
- "@latticexyz/abi-ts": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
53
- "@latticexyz/block-logs-stream": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
54
- "@latticexyz/common": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
55
- "@latticexyz/config": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
56
- "@latticexyz/gas-report": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
57
- "@latticexyz/protocol-parser": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
58
- "@latticexyz/schema-type": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
59
- "@latticexyz/store": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
60
- "@latticexyz/store-sync": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
61
- "@latticexyz/utils": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
62
- "@latticexyz/world": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
63
- "@latticexyz/world-module-callwithsignature": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788",
64
- "@latticexyz/world-module-metadata": "2.2.17-ffefc8f000769d5ca625dd19290007a853a21788"
52
+ "@latticexyz/abi-ts": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
53
+ "@latticexyz/block-logs-stream": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
54
+ "@latticexyz/common": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
55
+ "@latticexyz/config": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
56
+ "@latticexyz/gas-report": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
57
+ "@latticexyz/protocol-parser": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
58
+ "@latticexyz/schema-type": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
59
+ "@latticexyz/store": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
60
+ "@latticexyz/store-sync": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
61
+ "@latticexyz/utils": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
62
+ "@latticexyz/world": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
63
+ "@latticexyz/world-module-callwithsignature": "2.2.18-04065f05390b9975400db7e15b185a86976ba199",
64
+ "@latticexyz/world-module-metadata": "2.2.18-04065f05390b9975400db7e15b185a86976ba199"
65
65
  },
66
66
  "devDependencies": {
67
67
  "@types/debug": "^4.1.7",
@@ -1,44 +0,0 @@
1
- import{a as re}from"./chunk-PZL6GJOK.js";import{command as Za}from"@latticexyz/gas-report/internal";import{command as Xa}from"@latticexyz/abi-ts/internal";import{loadConfig as Dt,resolveConfigPath as At}from"@latticexyz/config/node";import{tablegen as wt}from"@latticexyz/store/codegen";import{buildSystemsManifest as xt,worldgen as St}from"@latticexyz/world/node";import{forge as vt}from"@latticexyz/common/foundry";import{execa as Ct}from"execa";async function L({rootDir:e,config:o,foundryProfile:t=process.env.FOUNDRY_PROFILE}){await Promise.all([wt({rootDir:e,config:o}),St({rootDir:e,config:o})]),await vt(["build"],{profile:t}),await xt({rootDir:e,config:o}),await Ct("mud",["abi-ts"],{stdio:"inherit"})}import kt from"node:path";var Tt={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 At(e.configPath),t=await Dt(o);await L({rootDir:kt.dirname(o),config:t,foundryProfile:e.profile}),process.exit(0)}},Fe=Tt;import{rmSync as Pt}from"fs";import{homedir as Mt}from"os";import Ot from"path";import{execa as Bt}from"execa";var Ht={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=Mt();Pt(Ot.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=Bt("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}},Le=Ht;var Wt={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)}},Ee=Wt;import{loadConfig as It,resolveConfigPath as jt}from"@latticexyz/config/node";import{tablegen as Rt}from"@latticexyz/store/codegen";import $t from"node:path";var Ft={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 jt(e.configPath),t=await It(o);await Rt({rootDir:$t.dirname(o),config:t}),process.exit(0)}},ze=Ft;import xe from"node:path";import{existsSync as Yo,mkdirSync as Gn,readFileSync as Go,writeFileSync as Oe}from"node:fs";import{stringToHex as pn}from"viem";import{waitForTransactionReceipt as nr}from"viem/actions";import Je from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import zt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{encodeDeployData as Nt,size as Ut}from"viem";import Ne from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import Ue from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import _e from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import Ve from"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json"assert{type:"json"};import Ke from"@latticexyz/world/out/InitModule.sol/InitModule.json"assert{type:"json"};import Lt from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{encodeDeployData as Et,size as Y}from"viem";import{getContractAddress as G}from"@latticexyz/common/internal";function E(e){let o=Y(Ne.deployedBytecode.object),t=Ne.bytecode.object,r=G({deployerAddress:e,bytecode:t}),n=Y(Ue.deployedBytecode.object),s=Ue.bytecode.object,a=G({deployerAddress:e,bytecode:s}),i=Y(_e.deployedBytecode.object),p=_e.bytecode.object,l=G({deployerAddress:e,bytecode:p}),c=Y(Ve.deployedBytecode.object),u=Ve.bytecode.object,y=G({deployerAddress:e,bytecode:u}),d=Y(Ke.deployedBytecode.object),f=Et({bytecode:Ke.bytecode.object,abi:Lt,args:[r,a,l,y]}),h=G({deployerAddress:e,bytecode:f});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:p,deployedBytecodeSize:i,debugLabel:"batch call system",address:l},RegistrationSystem:{bytecode:u,deployedBytecodeSize:c,debugLabel:"core registration system",address:y},InitModule:{bytecode:f,deployedBytecodeSize:d,debugLabel:"core module",address:h}}}import{getContractAddress as _t}from"@latticexyz/common/internal";function ne(e){let o=E(e),t=Ut(Je.deployedBytecode.object),r=Nt({bytecode:Je.bytecode.object,abi:zt,args:[o.InitModule.address]}),n=_t({deployerAddress:e,bytecode:r});return{...o,WorldFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world factory",address:n}}}import qe from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.json"assert{type:"json"};import Vt from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json"assert{type:"json"};import{encodeDeployData as Kt,size as Jt}from"viem";import{getContractAddress as qt}from"@latticexyz/common/internal";function se(e){let o=E(e),t=Jt(qe.deployedBytecode.object),r=Kt({bytecode:qe.bytecode.object,abi:Vt,args:[o.InitModule.address]}),n=qt({deployerAddress:e,bytecode:r});return{...o,WorldProxyFactory:{bytecode:r,deployedBytecodeSize:t,debugLabel:"world proxy factory",address:n}}}import{ensureContractsDeployed as Ye}from"@latticexyz/common/internal";async function Ge(e,o,t){if(t){let n=se(o);return await Ye({client:e,deployerAddress:o,contracts:Object.values(n)}),n.WorldProxyFactory.address}let r=ne(o);return await Ye({client:e,deployerAddress:o,contracts:Object.values(r)}),r.WorldFactory.address}import sr from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as ar}from"@latticexyz/common";import Qe from"debug";var M=Qe("mud:cli"),Yt=Qe("mud:cli");M.log=console.debug.bind(console);Yt.log=console.error.bind(console);var g=M.extend("deploy"),Gt=M.extend("deploy");g.log=console.debug.bind(console);Gt.log=console.error.bind(console);import{AbiEventSignatureNotFoundError as er,decodeEventLog as or,hexToString as eo,parseAbi as tr}from"viem";import Qt from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{helloStoreEvent as Zt}from"@latticexyz/store";import{helloWorldEvent as Xt}from"@latticexyz/world";var ae=[Zt,Xt],D=Qt,Ze=["2.0.0","2.0.1","2.0.2"],Xe=["2.0.0","2.0.1","2.0.2"];import{isDefined as rr}from"@latticexyz/common/utils";function z(e){let o=e.map(a=>{try{return{...a,...or({strict:!0,abi:tr(ae),topics:a.topics,data:a.data})}}catch(i){if(i instanceof er)return;throw i}}).filter(rr),{address:t,deployBlock:r,worldVersion:n,storeVersion:s}=o.reduce((a,i)=>({...a,address:i.address,deployBlock:i.blockNumber,...i.eventName==="HelloWorld"?{worldVersion:eo(i.args.worldVersion).replace(/\0+$/,"")}:null,...i.eventName==="HelloStore"?{storeVersion:eo(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 oo(e,o,t,r){let n=await Ge(e,o,r);g("deploying world");let s=await ar(e,{chain:e.chain??null,address:n,abi:sr,functionName:"deployWorld",args:[t]});g("waiting for world deploy");let a=await nr(e,{hash:s});if(a.status!=="success")throw console.error("world deploy failed",a),new Error("world deploy failed");let i=z(a.logs);return g("deployed world to",i.address,"at block",i.deployBlock),{...i,stateBlock:i.deployBlock}}import{resourceToLabel as le,writeContract as cr}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as mr,keySchemaToHex as so,valueSchemaToHex as ao,getSchemaTypes as N,getValueSchema as io,getKeySchema as lo}from"@latticexyz/protocol-parser/internal";import{decodeAbiParameters as to,parseAbiParameters as ro}from"viem";import{hexToResource as ir}from"@latticexyz/common";import{hexToSchema as no}from"@latticexyz/protocol-parser/internal";import lr from"@latticexyz/store/mud.config";import{getRecords as dr}from"@latticexyz/store-sync";async function ie({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){g("looking up tables for",o.address);let{records:n}=await dr({table:lr.namespaces.store.tables.Tables,worldAddress:o.address,indexerUrl:t,chainId:r,client:e,fromBlock:o.deployBlock,toBlock:o.stateBlock}),s=n.map(a=>{let{type:i,namespace:p,name:l}=ir(a.tableId),c=no(a.keySchema),u=no(a.valueSchema),y=to(ro("string[]"),a.abiEncodedKeyNames)[0],d=to(ro("string[]"),a.abiEncodedFieldNames)[0],f=[...u.staticFields,...u.dynamicFields],h=Object.fromEntries(c.staticFields.map((A,k)=>[y[k],{type:A,internalType:A}])),v=Object.fromEntries(f.map((A,k)=>[d[k],{type:A,internalType:A}]));return{type:i,namespace:p,name:l,tableId:a.tableId,schema:{...h,...v},key:Object.keys(h),keySchema:h,keySchemaHex:a.keySchema,valueSchema:v,valueSchemaHex:a.valueSchema}});return g("found",s.length,"tables for",o.address),s}import pr from"p-retry";import{isDefined as fr}from"@latticexyz/common/utils";async function co({client:e,worldDeploy:o,tables:t,indexerUrl:r,chainId:n}){let s=new Map(t.map(c=>{let u=N(lo(c)),y=N(io(c)),d=so(u),f=ao(y);return[c.tableId,{...c,keySchema:u,keySchemaHex:d,valueSchema:y,valueSchemaHex:f}]})),i=(await ie({client:e,worldDeploy:o,indexerUrl:r,chainId:n})).filter(({tableId:c})=>s.has(c));if(i.length){g("existing tables:",i.map(le).join(", "));let c=i.map(u=>{let y=s.get(u.tableId);if(u.keySchemaHex!==y.keySchemaHex||u.valueSchemaHex!==y.valueSchemaHex)return[`"${le(u)}" table:`,` Registered schema: ${JSON.stringify({schema:N(u.schema),key:u.key})}`,` Config schema: ${JSON.stringify({schema:N(y.schema),key:y.key})}`].join(`
3
- `)}).filter(fr);if(c.length)throw new Error(["Table schemas are immutable, but found registered tables with a different schema than what you have configured.",...c,"You can either update your config with the registered schema or change the table name to register a new table."].join(`
4
-
5
- `)+`
6
- `)}let p=new Set(i.map(({tableId:c})=>c)),l=t.filter(c=>!p.has(c.tableId));return l.length?(g("registering tables:",l.map(le).join(", ")),await Promise.all(l.map(c=>{let u=N(lo(c)),y=N(io(c));return pr(()=>cr(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerTable",args:[c.tableId,mr(y),so(u),ao(y),Object.keys(u),Object.keys(y)]}),{retries:3,onFailedAttempt:()=>g(`failed to register table ${le(c)}, retrying...`)})}))):[]}import{getAddress as W}from"viem";import{writeContract as De,resourceToLabel as Q}from"@latticexyz/common";import{hexToResource as Dr,resourceToLabel as Ar}from"@latticexyz/common";import{getFunctions as kr}from"@latticexyz/store-sync/world";import ur from"@latticexyz/store/mud.config";import{getRecords as yr}from"@latticexyz/store-sync";async function U({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){g("looking up resource IDs for",o.address);let{records:n}=await yr({table:ur.namespaces.store.tables.ResourceIds,worldAddress:o.address,indexerUrl:t,chainId:r,client:e,fromBlock:o.deployBlock,toBlock:o.stateBlock}),s=n.map(a=>a.resourceId);return g("found",s.length,"resource IDs for",o.address),s}import{decodeValueArgs as gr,encodeKey as br,getKeySchema as hr,getSchemaTypes as mo,getValueSchema as wr}from"@latticexyz/protocol-parser/internal";import{readContract as xr}from"viem/actions";async function de({client:e,worldDeploy:o,table:t,key:r}){let[n,s,a]=await xr(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[t.tableId,br(mo(hr(t)),r)]});return gr(mo(wr(t)),{staticData:n,encodedLengths:s,dynamicData:a})}import{getAddress as Sr}from"viem";import vr from"@latticexyz/world/mud.config";import{getRecords as Cr}from"@latticexyz/store-sync";async function ce({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){g("looking up resource access for",o.address);let{records:n}=await Cr({table:vr.namespaces.world.tables.ResourceAccess,worldAddress:o.address,indexerUrl:t,chainId:r,client:e,fromBlock:o.deployBlock,toBlock:o.stateBlock}),s=n.filter(a=>a.access).map(a=>({resourceId:a.resourceId,address:Sr(a.caller)}));return g("found",s.length,"resource<>address access pairs"),s}import Tr from"@latticexyz/world/mud.config";async function po({client:e,worldDeploy:o,indexerUrl:t,chainId:r}){let[n,s,a]=await Promise.all([U({client:e,worldDeploy:o,indexerUrl:t,chainId:r}),kr({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,indexerUrl:t,chainId:r}),ce({client:e,worldDeploy:o,indexerUrl:t,chainId:r})]),i=n.map(Dr).filter(p=>p.type==="system");return g("looking up systems:",i.map(Ar).join(", ")),await Promise.all(i.map(async p=>{let{system:l,publicAccess:c}=await de({client:e,worldDeploy:o,table:Tr.namespaces.world.tables.Systems,key:{systemId:p.resourceId}}),u=s.filter(y=>y.systemId===p.resourceId);return{address:l,namespace:p.namespace,name:p.name,systemId:p.resourceId,allowAll:c,allowedAddresses:a.filter(({resourceId:y})=>y===p.resourceId).map(({address:y})=>y),worldFunctions:u}}))}import Ae from"p-retry";import{ensureContractsDeployed as Pr}from"@latticexyz/common/internal";async function fo({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,systems:n,indexerUrl:s,chainId:a}){let[i,p]=await Promise.all([po({client:e,worldDeploy:r,indexerUrl:s,chainId:a}),ce({client:e,worldDeploy:r,indexerUrl:s,chainId:a})]),l=n.filter(m=>i.some(b=>b.systemId===m.systemId&&W(b.address)===W(m.prepareDeploy(o,t).address)));l.length&&g("existing systems:",l.map(Q).join(", "));let c=l.map(m=>m.systemId),u=n.filter(m=>!c.includes(m.systemId));if(!u.length)return[];let y=u.filter(m=>i.some(b=>b.systemId===m.systemId&&W(b.address)!==W(m.prepareDeploy(o,t).address)));y.length&&g("upgrading systems:",y.map(Q).join(", "));let d=u.filter(m=>!i.some(b=>b.systemId===m.systemId));d.length&&g("registering new systems:",d.map(Q).join(", ")),await Pr({client:e,deployerAddress:o,contracts:u.map(m=>({bytecode:m.prepareDeploy(o,t).bytecode,deployedBytecodeSize:m.deployedBytecodeSize,debugLabel:`${Q(m)} system`}))});let f=await Promise.all(u.map(m=>Ae(()=>De(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"registerSystem",args:[m.systemId,m.prepareDeploy(o,t).address,m.allowAll]}),{retries:3,onFailedAttempt:()=>g(`failed to register system ${Q(m)}, retrying...`)}))),h=n.map(m=>m.systemId),v=p.filter(({resourceId:m})=>h.includes(m)),A=[...n.flatMap(m=>m.allowedAddresses.map(b=>({resourceId:m.systemId,address:b}))),...n.flatMap(m=>m.allowedSystemIds.map(b=>({resourceId:m.systemId,address:i.find(T=>T.systemId===b)?.address??n.find(T=>T.systemId===b)?.prepareDeploy(o,t).address})).filter(b=>b.address!=null))],k=A.filter(m=>!v.some(({resourceId:b,address:T})=>b===m.resourceId&&W(T)===W(m.address))),x=v.filter(m=>!A.some(({resourceId:b,address:T})=>b===m.resourceId&&W(T)===W(m.address)));x.length&&g("revoking",x.length,"access grants"),k.length&&g("adding",k.length,"access grants");let w=await Promise.all([...x.map(m=>Ae(()=>De(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"revokeAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:()=>g("failed to revoke access, retrying...")})),...k.map(m=>Ae(()=>De(e,{chain:e.chain??null,address:r.address,abi:D,functionName:"grantAccess",args:[m.resourceId,m.address]}),{retries:3,onFailedAttempt:()=>g("failed to grant access, retrying...")}))]);return[...f,...w]}import{getAddress as Mr,parseAbi as Or}from"viem";import{getBlock as uo}from"viem/actions";import{fetchBlockLogs as Br}from"@latticexyz/block-logs-stream";var yo=new Map;async function me(e,o,t){let r=Mr(o),n=await uo(e,{blockTag:"latest"}),s=yo.get(r);if(s!=null)return{...s,stateBlock:n.number};g("looking up world deploy for",r);let[a,i]=t?[{number:t},{number:t}]:[await uo(e,{blockTag:"earliest"}),n],p=await Br({publicClient:e,address:r,events:Or(ae),fromBlock:a.number,toBlock:i.number,maxBlockRange:100000n});if(p.length===0)throw new Error("could not find `HelloWorld` or `HelloStore` event");return s={...z(p.flatMap(l=>l.logs)),stateBlock:n.number},yo.set(r,s),g("found world deploy for",r,"at block",s.deployBlock),s}import{hexToResource as Hr,writeContract as Wr}from"@latticexyz/common";import{getFunctions as Ir}from"@latticexyz/store-sync/world";import jr from"p-retry";async function go({client:e,worldDeploy:o,functions:t,indexerUrl:r,chainId:n}){let s=await Ir({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,indexerUrl:r,chainId:n}),a=Object.fromEntries(s.map(l=>[l.selector,l])),i=t.filter(l=>a[l.selector]),p=t.filter(l=>!i.includes(l));if(i.length){g("functions already registered:",i.map(c=>c.signature).join(", "));let l=i.filter(c=>c.systemId!==a[c.selector]?.systemId);l.length&&console.warn("found",l.length,"functions already registered but pointing at a different system ID:",l.map(c=>c.signature).join(", "))}return p.length?(g("registering functions:",p.map(l=>l.signature).join(", ")),Promise.all(p.map(l=>{let{namespace:c}=Hr(l.systemId),u=c===""?{functionName:"registerRootFunctionSelector",args:[l.systemId,l.systemFunctionSignature,l.systemFunctionSignature]}:{functionName:"registerFunctionSelector",args:[l.systemId,l.systemFunctionSignature]};return jr(()=>Wr(e,{chain:e.chain??null,address:o.address,abi:D,...u}),{retries:3,onFailedAttempt:()=>g(`failed to register function ${l.signature}, retrying...`)})}))):[]}import{BaseError as Rr}from"viem";import{writeContract as $r}from"@latticexyz/common";import{isDefined as Fr}from"@latticexyz/common/utils";import Lr from"p-retry";import{ensureContractsDeployed as Er}from"@latticexyz/common/internal";async function pe({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,modules:n}){return n.length?(await Er({client:e,deployerAddress:o,contracts:n.map(s=>({bytecode:s.prepareDeploy(o,t).bytecode,deployedBytecodeSize:s.deployedBytecodeSize,debugLabel:`${s.name} module`}))}),g("installing modules:",n.map(s=>s.name).join(", ")),(await Promise.all(n.map(s=>Lr(async()=>{try{let a=[...D,...s.abi],i=s.prepareDeploy(o,t).address,p=s.installAsRoot?{functionName:"installRootModule",args:[i,s.installData]}:{functionName:"installModule",args:[i,s.installData]};return await $r(e,{chain:e.chain??null,address:r.address,abi:a,...p})}catch(a){if(a instanceof Rr&&a.message.includes("Module_AlreadyInstalled")){g(`module ${s.name} already installed`);return}if(s.optional){g(`optional module ${s.name} install failed, skipping`),g(a);return}throw a}},{retries:3,onFailedAttempt:()=>g(`failed to install module ${s.name}, retrying...`)})))).filter(Fr)):[]}import{getAddress as bo}from"viem";import{hexToResource as ho,resourceToHex as wo,writeContract as zr}from"@latticexyz/common";import Nr from"@latticexyz/world/mud.config";async function xo({client:e,worldDeploy:o,resourceIds:t,indexerUrl:r,chainId:n}){let s=Array.from(new Set(t.map(d=>ho(d).namespace))),a=await U({client:e,worldDeploy:o,indexerUrl:r,chainId:n}),i=new Set(a.map(d=>ho(d).namespace));i.size&&g("found",i.size,"existing namespaces:",Array.from(i).map(d=>d===""?"<root>":d).join(", "));let p=s.filter(d=>i.has(d)),c=(await Promise.all(p.map(async d=>{let{owner:f}=await de({client:e,worldDeploy:o,table:Nr.namespaces.world.tables.NamespaceOwner,key:{namespaceId:wo({type:"namespace",namespace:d,name:""})}});return[d,f]}))).filter(([,d])=>bo(d)!==bo(e.account.address)).map(([d])=>d);if(c.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${c.join(", ")}`);let u=s.filter(d=>!i.has(d));return u.length>0&&g("registering namespaces:",Array.from(u).join(", ")),Promise.all(u.map(d=>zr(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerNamespace",args:[wo({namespace:d,type:"namespace",name:""})]})))}import{resourceToHex as fn,resourceToLabel as un}from"@latticexyz/common";import{randomBytes as yn}from"crypto";import{stringToHex as Yr,BaseError as Gr,concatHex as Co}from"viem";import{hexToResource as Qr,writeContract as Zr}from"@latticexyz/common";import{identity as Xr,isDefined as en}from"@latticexyz/common/utils";import ke from"@latticexyz/world-module-metadata/mud.config";import on from"@latticexyz/world-module-metadata/out/IMetadataSystem.sol/IMetadataSystem.abi.json"assert{type:"json"};import tn from"@latticexyz/world-module-metadata/out/MetadataModule.sol/MetadataModule.json"assert{type:"json"};import{isHex as Ur,size as _r}from"viem";function fe(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 B}from"zod";import{Abi as Vr}from"abitype/zod";function Kr(e){return Ur(e,{strict:!1})}var So=B.object({object:B.string().refine(Kr),linkReferences:B.record(B.record(B.array(B.object({start:B.number(),length:B.number()})))).optional()}),Jr=B.object({bytecode:So,deployedBytecode:So,abi:Vr});function _(e){let o=Jr.parse(e),t=fe(o.bytecode.linkReferences??{});return{abi:o.abi,bytecode:o.bytecode.object,placeholders:t,deployedBytecodeSize:_r(o.deployedBytecode.object)}}import{spliceHex as qr}from"@latticexyz/common";import{getContractAddress as vo}from"@latticexyz/common/internal";function I(e,o){return function(r,n){let s=e;if(o.length===0)return{bytecode:s,address:vo({deployerAddress:r,bytecode:s})};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=qr(s,a.start,a.length,i)}return{bytecode:s,address:vo({deployerAddress:r,bytecode:s})}}}import{getKeyTuple as Do}from"@latticexyz/protocol-parser/internal";import{getRecords as rn}from"@latticexyz/store-sync";import{waitForTransactions as nn}from"@latticexyz/common/internal";var ue=_(tn);async function Ao({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,tags:n,valueToHex:s=Xr,indexerUrl:a,chainId:i}){g("ensuring",n.length,"resource tags"),g("looking up existing resource tags");let{records:p}=await rn({table:ke.tables.metadata__ResourceTag,worldAddress:r.address,chainId:i,indexerUrl:a,client:e,fromBlock:r.deployBlock,toBlock:r.stateBlock});g("found",p.length,"resource tags");let l=new Map(p.map(d=>[Co(Do(ke.tables.metadata__ResourceTag,d)),d.value])),u=n.map(d=>({resource:d.resourceId,tag:Yr(d.tag,{size:32}),value:s(d.value)})).filter(d=>{let f=Co(Do(ke.tables.metadata__ResourceTag,d));return l.get(f)!==d.value});if(u.length===0)return[];let y=await pe({client:e,deployerAddress:o,worldDeploy:r,libraryMap:t,modules:[{optional:!0,name:"MetadataModule",installAsRoot:!1,installData:"0x",prepareDeploy:I(ue.bytecode,ue.placeholders),deployedBytecodeSize:ue.deployedBytecodeSize,abi:ue.abi}]});return await nn({client:e,hashes:y,debugLabel:"metadata module installation"}),g("setting",u.length,"resource tags"),(await Promise.all(u.map(async d=>{let f=Qr(d.resource),h=`${f.type}:${f.namespace}:${f.name}`;g(`tagging ${h} with ${d.tag}: ${JSON.stringify(d.value)}`);try{return await Zr(e,{chain:e.chain??null,address:r.address,abi:on,functionName:"metadata__setResourceTag",args:[d.resource,d.tag,d.value]})}catch(v){g(`failed to set resource tag for ${h}, skipping
7
- ${v instanceof Gr?v.shortMessage:v}`)}}))).filter(en)}import{concatHex as sn,encodeDeployData as an,isHex as Mo}from"viem";import{waitForTransactionReceipt as ln}from"viem/actions";import{resourceToHex as dn,sendTransaction as cn,writeContract as ko}from"@latticexyz/common";import{ensureContractsDeployed as To,getContractAddress as mn,waitForTransactions as Po}from"@latticexyz/common/internal";function Pe(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 Oo(e,o){return e.bytecode.filter(t=>!Mo(t)).flatMap(t=>Oo(Pe(t,o),o))}function Te(e,o,t){return sn(o.bytecode.map(r=>Mo(r)?r:mn({deployerAddress:e,bytecode:Te(e,Pe(r,t),t)})))}async function Bo({client:e,deployerAddress:o,artifacts:t,customWorld:r}){let n=E(o);await To({client:e,deployerAddress:o,contracts:Object.values(n)});let s=Pe(r,t),a=Oo(s,t);a.length&&(g(`deploying ${a.length} world dependencies`),await To({client:e,deployerAddress:o,contracts:a.map(y=>Te(o,y,t)).reverse().map(y=>({bytecode:y}))})),g("deploying custom world");let i=await cn(e,{chain:e.chain??null,data:an({abi:s.abi,args:[],bytecode:Te(o,s,t)})});g("waiting for custom world deploy");let p=await ln(e,{hash:i});if(p.status!=="success")throw console.error("world deploy failed",p),new Error("world deploy failed");let l=z(p.logs);g("deployed custom world to",l.address,"at block",l.deployBlock);let c=await ko(e,{chain:e.chain??null,address:l.address,abi:D,functionName:"initialize",args:[n.InitModule.address]});await Po({client:e,hashes:[c],debugLabel:"world init"});let u=await ko(e,{chain:e.chain??null,address:l.address,abi:D,functionName:"transferOwnership",args:[dn({type:"namespace",namespace:"",name:""}),e.account.address]});return await Po({client:e,hashes:[u],debugLabel:"world ownership transfer"}),{...l,stateBlock:l.deployBlock}}import{uniqueBy as gn}from"@latticexyz/common/utils";function Ho({path:e,name:o}){return`${e}:${o}`}function Wo(e){let o=Object.fromEntries(e.map(r=>[Ho(r),r])),t={getAddress:({path:r,name:n,deployer:s})=>{let a=o[Ho({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}import{ensureContractsDeployed as bn,ensureDeployer as hn,waitForTransactions as Me}from"@latticexyz/common/internal";async function Io({config:e,client:o,tables:t,systems:r,libraries:n,modules:s=[],artifacts:a,salt:i,worldAddress:p,worldDeployBlock:l,deployerAddress:c,indexerUrl:u,chainId:y}){let d=c??await hn(o),f=p?await me(o,p,l):e.deploy.customWorld?await Bo({client:o,deployerAddress:d,artifacts:a,customWorld:e.deploy.customWorld}):await oo(o,d,i??`0x${yn(32).toString("hex")}`,e.deploy.upgradeableWorldImplementation),h={client:o,indexerUrl:u,chainId:y,worldDeploy:f};if(!Ze.includes(f.storeVersion))throw new Error(`Unsupported Store version: ${f.storeVersion}`);if(!Xe.includes(f.worldVersion))throw new Error(`Unsupported World version: ${f.worldVersion}`);let v=Wo(n);await bn({...h,deployerAddress:d,contracts:[...n.map(S=>({bytecode:S.prepareDeploy(d,v).bytecode,deployedBytecodeSize:S.deployedBytecodeSize,debugLabel:`${S.path}:${S.name} library`})),...r.map(S=>({bytecode:S.prepareDeploy(d,v).bytecode,deployedBytecodeSize:S.deployedBytecodeSize,debugLabel:`${un(S)} system`})),...s.map(S=>({bytecode:S.prepareDeploy(d,v).bytecode,deployedBytecodeSize:S.deployedBytecodeSize,debugLabel:`${S.name} module`}))]});let A=await xo({...h,resourceIds:[...t.map(({tableId:S})=>S),...r.map(({systemId:S})=>S)]});await Me({client:o,hashes:A,debugLabel:"namespace registrations"});let k=await co({...h,tables:t}),x=await fo({...h,deployerAddress:d,libraryMap:v,systems:r});await Me({client:o,hashes:[...k,...x],debugLabel:"table and system registrations"});let w=await go({...h,functions:r.flatMap(S=>S.worldFunctions)}),m=await pe({...h,deployerAddress:d,libraryMap:v,modules:s}),b=gn([...t,...r].filter(({namespace:S,namespaceLabel:P})=>P!==S).map(({namespace:S,namespaceLabel:P})=>({resourceId:fn({type:"namespace",namespace:S,name:""}),tag:"label",value:P})),S=>S.resourceId),T=t.filter(S=>S.label!==S.name).map(({tableId:S,label:P})=>({resourceId:S,tag:"label",value:P})),R=r.flatMap(({name:S,systemId:P,label:te,metadata:C})=>[...te!==S?[{resourceId:P,tag:"label",value:te}]:[],{resourceId:P,tag:"abi",value:C.abi.join(`
8
- `)},{resourceId:P,tag:"worldAbi",value:C.worldAbi.join(`
9
- `)}]),oe=await Ao({...h,deployerAddress:d,libraryMap:v,tags:[...b,...T,...R],valueToHex:pn});return await Me({client:o,hashes:[...w,...m,...oe],debugLabel:"remaining transactions"}),g("deploy complete"),f}import{createWalletClient as Qn,http as Zn,isHex as Xn,stringToHex as es}from"viem";import{privateKeyToAccount as os}from"viem/accounts";import{loadConfig as ts,resolveConfigPath as rs}from"@latticexyz/config/node";import{getOutDirectory as ns,getRpcUrl as ss}from"@latticexyz/common/foundry";import K from"chalk";import{MUDError as qo}from"@latticexyz/common/errors";import $o from"path";import{loadSystemsManifest as An,resolveSystems as kn}from"@latticexyz/world/node";import{isHex as Fo,toFunctionSelector as Lo,toFunctionSignature as Eo}from"viem";import{readFileSync as wn}from"fs";import xn from"path";import{MUDError as ye}from"@latticexyz/common/errors";import{size as Sn}from"viem";function V(e,o,t){let r,n=xn.join(t,e,o+".json");try{r=JSON.parse(wn(n,"utf8"))}catch{throw new ye(`Error reading file at ${n}`)}let s=r?.bytecode?.object;if(!s)throw new ye(`No bytecode found in ${n}`);let a=r?.deployedBytecode?.object;if(!a)throw new ye(`No deployed bytecode found in ${n}`);let i=r?.abi;if(!i)throw new ye(`No ABI found in ${n}`);let p=fe(r?.bytecode?.linkReferences??{});return{abi:i,bytecode:s,placeholders:p,deployedBytecodeSize:Sn(a)}}import{groupBy as Tn}from"@latticexyz/common/utils";import{readFileSync as Cn}from"fs";import{globSync as Dn}from"glob";import vn from"toposort";function jo(e,o,t){let r=vn(e.flatMap(n=>t(n).map(s=>[o(n),s])));return[...e].sort((n,s)=>r.indexOf(o(n))-r.indexOf(o(s)))}function Ro(e){let t=Dn(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).sort().map(r=>JSON.parse(Cn(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,p])=>Object.keys(p).map(l=>({path:i,name:l,dependentPath:n,dependentName:s})))});return jo(t,r=>`${r.path}:${r.name}`,r=>[`${r.dependentPath}:${r.dependentName}`])}import{findUp as Pn}from"find-up";import{createRequire as Mn}from"node:module";function ge(e){return e.artifactPath==="@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json"?(console.warn(["","\u26A0\uFE0F Your `mud.config.ts` is using `Unstable_CallWithSignatureModule`. This module can be removed from your config as it is now installed by default during deploy.",""].join(`
10
- `)),!1):!0}async function zo({rootDir:e,config:o,forgeOutDir:t}){let r=await Pn("package.json");if(!r)throw new Error("Could not find package.json to import relative to.");let n=Mn(r),s=o.modules.filter(ge).flatMap(f=>f.artifactPath==null?[]:[$o.join(n.resolve(f.artifactPath),"../../")]),a=[t,...s].flatMap(f=>Ro(f).map(h=>{let v=V($o.basename(h.path),h.name,f);return{path:h.path,name:h.name,abi:v.abi,prepareDeploy:I(v.bytecode,v.placeholders),deployedBytecodeSize:v.deployedBytecodeSize}})),p=V("System.sol","System",t).abi.filter(f=>f.type==="function").map(Eo),l=await kn({rootDir:e,config:o}),c=await An({rootDir:e,config:o}),u=l.filter(f=>!f.deploy.disabled).map(f=>{let h=c.systems.find(({systemId:w})=>w===f.systemId);if(!h)throw new Error(`System "${f.label}" not found in systems manifest. Run \`mud build\` before trying again.`);let v=V(`${f.label}.sol`,f.label,t),A=f.deploy.registerWorldFunctions?v.abi.filter(w=>w.type==="function").map(Eo).filter(w=>!p.includes(w)).map(w=>{let m=f.namespace===""?w:`${f.namespace}__${w}`;return{signature:m,selector:Lo(m),systemId:f.systemId,systemFunctionSignature:w,systemFunctionSelector:Lo(w)}}):[],k=f.accessList.filter(w=>Fo(w)),x=f.accessList.filter(w=>!Fo(w)).map(w=>l.find(b=>b.label===w).systemId);return{...f,allowAll:f.openAccess,allowedAddresses:k,allowedSystemIds:x,prepareDeploy:I(v.bytecode,v.placeholders),deployedBytecodeSize:v.deployedBytecodeSize,worldFunctions:A,abi:v.abi,metadata:{abi:h.abi,worldAbi:h.worldAbi}}}),y=Tn(u,f=>f.systemId),d=Array.from(y.values()).filter(f=>f.length>1).flat();if(d.length){let f=d.map(h=>h.name);throw new Error(`Found systems with overlapping system ID: ${f.join(", ")}.
11
-
12
- 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:u,libraries:a}}import{getChainId as as}from"viem/actions";import{existsSync as On}from"fs";import Bn from"path";import Hn from"chalk";import{getScriptDirectory as Wn,forge as In}from"@latticexyz/common/foundry";async function No(e,o,t,r,n,s){let a=n?.replaceAll("\\","").split(" ")??[],i=Bn.join(await Wn(),e+".s.sol");if(!On(i)){console.log(`No script at ${i}, skipping post deploy hook`);return}console.log(Hn.blue(`Executing post deploy script at ${i}`)),await In(["script",e,"--broadcast","--sig","run(address)",o,"--rpc-url",t,"-vvv",s?"--aws":"",...a],{profile:r})}import{kmsKeyToAccount as is}from"@latticexyz/common/kms";import _o from"node:path";import{encodeField as $n}from"@latticexyz/protocol-parser/internal";import{bytesToHex as Fn}from"viem";import{createRequire as jn}from"node:module";import{findUp as Rn}from"find-up";async function Uo({packageJsonPath:e,artifactPath:o}){let t;try{let r=e??await Rn("package.json",{cwd:process.cwd()});if(!r)throw new Error("Could not find package.json to import relative to.");t=jn(r)(o)}catch(r){throw console.error(),console.error("Could not import contract artifact at",o),console.error(),r}return _(t)}import{resolveWithContext as Ln}from"@latticexyz/world/internal";import En from"@latticexyz/world-module-callwithsignature/out/CallWithSignatureModule.sol/CallWithSignatureModule.json"assert{type:"json"};var be=_(En),zn={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"};async function he(e,o){let t=[{optional:!0,name:"CallWithSignatureModule",installAsRoot:!0,installData:"0x",prepareDeploy:I(be.bytecode,be.placeholders),deployedBytecodeSize:be.deployedBytecodeSize,abi:be.abi}],r=await Promise.all(e.modules.filter(ge).map(async n=>{let s=n.artifactPath;if(!s)if(n.name)s=zn[n.name]??_o.join(o,`${n.name}.sol`,`${n.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(n.name)}`,"","with this:","",` artifactPath: ${JSON.stringify(s)}`,""].join(`
13
- `));else throw new Error("No `artifactPath` provided for module.");let a=_o.basename(s,".json"),i=await Uo({artifactPath:s}),p=n.args.map(l=>Ln(l,{config:e})).map(l=>{let c=l.value instanceof Uint8Array?Fn(l.value):l.value;return $n(l.type,c)});if(p.length>1)throw new Error(`${a} module should only have 0-1 args, but had ${p.length} args.`);return{name:a,installAsRoot:n.root,installData:p.length===0?"0x":p[0],prepareDeploy:I(i.bytecode,i.placeholders),deployedBytecodeSize:i.deployedBytecodeSize,abi:i.abi}}));return[...t,...r]}import{findContractArtifacts as ls}from"@latticexyz/world/node";import{getAutomine as Nn,getBlock as Vo,setAutomine as Un,setIntervalMining as _n}from"viem/actions";import{getAction as Z}from"viem/utils";async function Jo(e){let o=await Vn(e).catch(()=>{});if(!(!o||o.type==="automine"))return M("Enabling automine"),await Ko(e,{type:"automine"}),{reset:()=>(M("Disabling automine"),Ko(e,o))}}async function Vn(e){let o={mode:"anvil",...e};return await Z(o,Nn,"getAutomine")({})?{type:"automine"}:{type:"interval",blockTime:await Kn(e)}}async function Ko(e,o){o.type==="automine"?await Z(e,Un,"setAutomine")(!0):await Z(e,_n,"setIntervalMining")({interval:o.blockTime})}async function Kn(e){let o=await Z(e,Vo,"getBlock")({blockTag:"latest"}),t=await Z(e,Vo,"getBlock")({blockNumber:o.number-1n}),r=o.timestamp-t.timestamp;return Number(r)}import{redstone as Jn,garnet as qn,rhodolite as Yn}from"@latticexyz/common/chains";var we=[Jn,qn,Yn];var O={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."},indexerUrl:{type:"string",desc:"The indexer URL to use.",required:!1}};async function J(e){let o=e.salt!=null?Xn(e.salt)?e.salt:es(e.salt):void 0,t=e.profile??process.env.FOUNDRY_PROFILE,r=await rs(e.configPath),n=await ts(r),s=xe.dirname(r);e.printConfig&&console.log(K.green(`
14
- Resolved config:
15
- `),JSON.stringify(n,null,2));let a=await ns(t),i=e.rpc??await ss(t);console.log(K.bgBlue(K.whiteBright(`
16
- Deploying MUD contracts${t?" with profile "+t:""} to RPC ${i}
17
- `))),e.skipBuild||await L({rootDir:s,config:n,foundryProfile:t});let{systems:p,libraries:l}=await zo({rootDir:s,config:n,forgeOutDir:a}),c=await ls({forgeOutDir:a}),u=await he(n,a),y=Object.values(n.namespaces).flatMap(b=>Object.values(b.tables)).filter(b=>!b.deploy.disabled),d=await(async()=>{if(e.kms){let b=process.env.AWS_KMS_KEY_ID;if(!b)throw new qo("Missing `AWS_KMS_KEY_ID` environment variable. This is required when using with `--kms` option.");return await is({keyId:b})}else{let b=process.env.PRIVATE_KEY;if(!b)throw new qo(`Missing PRIVATE_KEY environment variable.
18
- Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
19
- in your contracts directory to use the default anvil private key.`);return os(b)}})(),f=Qn({transport:Zn(i,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:d}),h=await as(f),v=e.indexerUrl??we.find(b=>b.id===h)?.indexerUrl,A=e.worldAddress?ds({worldAddress:e.worldAddress,worldsFile:n.deploy.worldsFile,chainId:h}):void 0;console.log("Deploying from",f.account.address);let k=await Jo(f),x=Date.now(),w=await Io({config:n,deployerAddress:e.deployerAddress,salt:o,worldAddress:e.worldAddress,worldDeployBlock:A,client:f,tables:y,systems:p,libraries:l,modules:u,artifacts:c,indexerUrl:v,chainId:h});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await No(n.deploy.postDeployScript,w.address,i,t,e.forgeScriptOptions,!!e.kms),await k?.reset(),console.log(K.green("Deployment completed in",(Date.now()-x)/1e3,"seconds"));let m={worldAddress:w.address,blockNumber:Number(w.deployBlock)};if(e.saveDeployment){let b=xe.join(n.deploy.deploysDirectory,h.toString());Gn(b,{recursive:!0}),Oe(xe.join(b,"latest.json"),JSON.stringify(m,null,2)),Oe(xe.join(b,Date.now()+".json"),JSON.stringify(m,null,2));let T=[1337,31337],R=Yo(n.deploy.worldsFile)?JSON.parse(Go(n.deploy.worldsFile,"utf-8")):{};R[h]={address:m.worldAddress,blockNumber:T.includes(h)?void 0:m.blockNumber},Oe(n.deploy.worldsFile,JSON.stringify(R,null,2)),console.log(K.bgGreen(K.whiteBright(`
20
- Deployment result (written to ${n.deploy.worldsFile} and ${b}):
21
- `)))}return console.log(m),w}function ds({chainId:e,worldAddress:o,worldsFile:t}){let r=Yo(t)?JSON.parse(Go(t,"utf-8")):{},n=r[e]?.address===o?r[e].blockNumber:void 0;return n?BigInt(n):void 0}var cs={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(O)},async handler(e){try{await J(e)}catch(o){re(o),process.exit(1)}process.exit(0)}},Qo=cs;import ms from"node:path";import{loadConfig as ps,resolveConfigPath as fs}from"@latticexyz/config/node";import{worldgen as us}from"@latticexyz/world/node";var ys={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 gs(e),process.exit(0)}};async function gs(e){let o=await fs(e.configPath),t=await ps(o),r=ms.dirname(o);await us({rootDir:r,config:t,clean:e.clean})}var Zo=ys;import X from"chalk";import{readFileSync as Ss,writeFileSync as vs}from"fs";import He from"path";import{MUDError as q}from"@latticexyz/common/errors";var Xo={name:"@latticexyz/cli",version:"2.2.16",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":"0.2.2","@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/store-sync":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-module-callwithsignature":"workspace:*","@latticexyz/world-module-metadata":"workspace:*",abitype:"1.0.6","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",viem:"2.21.19",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/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",vitest:"0.34.6"}};import{globSync as Cs}from"glob";import{ZodError as hs,z as et}from"zod";var ws=et.object({MUD_PACKAGES:et.string().transform(e=>JSON.parse(e))});function xs(){try{return ws.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/entrykit":{"localPath":"packages/entrykit"},"@latticexyz/explorer":{"localPath":"packages/explorer"},"@latticexyz/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/paymaster":{"localPath":"packages/paymaster"},"@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-consumer":{"localPath":"packages/store-consumer"},"@latticexyz/store-indexer":{"localPath":"packages/store-indexer"},"@latticexyz/store-sync":{"localPath":"packages/store-sync"},"@latticexyz/store":{"localPath":"packages/store"},"@latticexyz/utils":{"localPath":"packages/utils"},"vite-plugin-mud":{"localPath":"packages/vite-plugin-mud"},"@latticexyz/world-module-callwithsignature":{"localPath":"packages/world-module-callwithsignature"},"@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 hs){let{...o}=e.format();console.error(`
22
- Missing or invalid environment variables:
23
-
24
- ${Object.keys(o).join(`
25
- `)}
26
- `),process.exit(1)}throw e}}var Be=xs().MUD_PACKAGES;var Ds={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 q(`You need to provide one these options: ${o.join(", ")}`);if(t>1)throw new q(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await As(e));let r=Cs("**/package.json").sort().filter(n=>!n.includes("node_modules"));for(let n of r)ks(n,e)}catch(o){re(o)}finally{process.exit(0)}}};async function As(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(X.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${Xo.name}`)).json()}catch{throw new q("Could not fetch available MUD versions")}if(e.tag){let t=o["dist-tags"][e.tag];if(!t)throw new q(`Could not find npm version with tag "${e.tag}"`);return console.log(X.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 q(`Could not find npm version based on commit "${e.commit}"`);return console.log(X.green(`Version from commit ${e.commit}: ${r}`)),r}return e.mudVersion}function ks(e,o){let{link:t}=o,{mudVersion:r}=o,n=Ts(e),s=Object.keys(Be),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]=p(l,"dependencies"));for(let l in n.devDependencies)s.includes(l)&&(n.devDependencies[l]=p(l,"devDependencies"));return vs(e,JSON.stringify(n,null,2)+`
27
- `),console.log(`Updating ${e}`),ot(a,n.dependencies),ot(i,n.devDependencies),n;function p(l,c){return t&&(r=Ps(e,t,l)),r||n[c][l]}}function Ts(e){try{let o=Ss(e,"utf8");return JSON.parse(o)}catch{throw new q("Could not read JSON at "+e)}}function ot(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${X.red(e[t])} -> ${X.green(o[t])}`)}function Ps(e,o,t){let r=He.relative(He.dirname(e),process.cwd());return"link:"+He.join(r,o,Be[t].localPath)}var tt=Ds;import{anvil as Ms,forge as Os,getRpcUrl as Bs}from"@latticexyz/common/foundry";import Hs from"chalk";var Ws={...O,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"}},Is={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Ws)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Ms(n)}let o=e.worldAddress?await Bs(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await J({...e,saveDeployment:!1,rpc:o})).address;console.log(Hs.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Os(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},rt=Is;import js from"node:path";import nt from"node:fs";import{loadConfig as Rs,resolveConfigPath as $s}from"@latticexyz/config/node";import{MUDError as st}from"@latticexyz/common/errors";import{cast as Fs,getRpcUrl as Ls}from"@latticexyz/common/foundry";import Es from"@latticexyz/world/mud.config";import{createClient as zs,http as Ns}from"viem";import{getChainId as Us,readContract as _s}from"viem/actions";import{resolveSystems as Vs}from"@latticexyz/world/node";var Ks=Es.namespaces.world.tables.Systems.tableId;function Js(e,o){if(!nt.existsSync(e))throw new st(`Missing expected worlds.json file at "${e}"`);let t=JSON.parse(nt.readFileSync(e,"utf-8"));if(!t[o])throw new st(`Missing chain ID ${o} in "${e}"`);return t[o].address}var qs={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 $s(e.configPath),t=js.dirname(o),r=e.profile??process.env.FOUNDRY_PROFILE,n=e.rpc??await Ls(r),s=await Rs(o),a=zs({transport:Ns(n)}),i=await Us(a),p=e.worldAddress??Js(s.deploy.worldsFile,i),l=await Vs({rootDir:t,config:s}),c=await Promise.all(l.map(async y=>({label:y.label,address:await _s(a,{abi:D,address:p,functionName:"getField",args:[Ks,[y.systemId],0]})}))),u=await Fs(["run","--label",`${p}:World`,...c.map(({label:y,address:d})=>["--label",`${d}:${y}`]).flat(),`${e.tx}`]);console.log(u),process.exit(0)}},at=qs;import{anvil as Ys,getScriptDirectory as Gs,getSrcDirectory as Qs}from"@latticexyz/common/foundry";import j from"chalk";import Zs from"chokidar";import{loadConfig as Xs,resolveConfigPath as ea}from"@latticexyz/config/node";import oa from"path";import{homedir as ta}from"os";import{rmSync as ra}from"fs";import{BehaviorSubject as na,debounceTime as sa,exhaustMap as aa,filter as ia}from"rxjs";import{isDefined as la}from"@latticexyz/common/utils";var da={rpc:O.rpc,configPath:O.configPath,alwaysRunPostDeploy:O.alwaysRunPostDeploy,forgeScriptOptions:O.forgeScriptOptions,worldAddress:O.worldAddress},ca={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(da)},async handler(e){let o=e.rpc,t=e.configPath??await ea(e.configPath),r=await Qs(),n=await Gs(),s=await Xs(t);if(!e.rpc){console.log(j.gray("Cleaning devnode cache"));let l=ta();ra(oa.join(l,".foundry","anvil","tmp"),{recursive:!0,force:!0}),Ys(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let a=new na(Date.now());Zs.watch([t,r,n],{ignoreInitial:!0}).on("all",async(l,c)=>{c.includes(t)&&(console.log(j.blue("Config changed, queuing deploy\u2026")),a.next(Date.now())),(c.includes(r)||c.includes(n))&&(c.includes(s.codegen.outputDirectory)||(console.log(j.blue("Contracts changed, queuing deploy\u2026")),a.next(Date.now())))});let i=e.worldAddress;a.pipe(sa(200),aa(async l=>{i&&console.log(j.blue("Rebuilding and upgrading world\u2026"));try{let c=await J({...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,indexerUrl:void 0});return i=c.address,l<a.value?a.next(a.value):console.log(j.gray(`
28
- Waiting for file changes\u2026
29
- `)),c}catch(c){console.error(j.bgRed(j.whiteBright(`
30
- Error while attempting deploy
31
- `))),console.error(c),console.log(j.gray(`
32
- Waiting for file changes\u2026
33
- `))}}),ia(la)).subscribe()}},it=ca;import{sliceHex as pa,zeroHash as fa}from"viem";import{forge as ma}from"@latticexyz/common/foundry";async function $(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 ma(o,{cwd:e.cwd})}import ua from"p-queue";import{MUDError as ya}from"@latticexyz/common/errors";import{getStorageAt as ga}from"viem/actions";import{execa as We}from"execa";import{getContractAddress as lt,getDeployer as ba}from"@latticexyz/common/internal";var ha="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function dt({client:e,rpc:o,systems:t,modules:r,worldAddress:n,deployerAddress:s,verifier:a,verifierUrl:i}){let p=s??await ba(e);if(!p)throw new ya("No deployer address provided or found.");let l=await ga(e,{address:n,slot:ha}),c=l&&l!==fa,u=new ua({concurrency:4});if(t.map(({name:y,bytecode:d})=>u.add(()=>$({name:y,rpc:o,verifier:a,verifierUrl:i,address:lt({deployerAddress:p,bytecode:d})}).catch(f=>{console.error(`Error verifying system contract ${y}:`,f)}))),a==="sourcify")if(await We("npm",["install"],{cwd:"node_modules/@latticexyz/store"}),await We("npm",["install"],{cwd:"node_modules/@latticexyz/world"}),await We("npm",["install"],{cwd:"node_modules/@latticexyz/world-modules"}),Object.entries(c?se(p):ne(p)).map(([y,{bytecode:d}])=>u.add(()=>$({cwd:"node_modules/@latticexyz/world",name:y,rpc:o,verifier:a,verifierUrl:i,address:lt({deployerAddress:p,bytecode:d})}).catch(f=>{console.error(`Error verifying world factory contract ${y}:`,f)}))),r.map(({name:y,prepareDeploy:d})=>{let{address:f}=d(p);return u.add(()=>$({cwd:"node_modules/@latticexyz/world-modules",name:y,rpc:o,verifier:a,verifierUrl:i,address:f}).catch(h=>{console.error(`Error verifying module contract ${y}:`,h)}))}),c){let y=pa(l,-20);u.add(()=>$({cwd:"node_modules/@latticexyz/world",name:"WorldProxy",rpc:o,verifier:a,verifierUrl:i,address:n}).catch(d=>{console.error("Error verifying WorldProxy contract:",d)})),u.add(()=>$({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:a,verifierUrl:i,address:y}).catch(d=>{console.error("Error verifying World contract:",d)}))}else u.add(()=>$({cwd:"node_modules/@latticexyz/world",name:"World",rpc:o,verifier:a,verifierUrl:i,address:n}).catch(y=>{console.error("Error verifying World contract:",y)}));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 wa,resolveConfigPath as xa}from"@latticexyz/config/node";import{resolveSystems as Sa}from"@latticexyz/world/node";import{getOutDirectory as va,getRpcUrl as Ca}from"@latticexyz/common/foundry";import{createWalletClient as Da,http as Aa}from"viem";import ct from"chalk";import ka from"node:path";var Ta={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."}},Pa={command:"verify",describe:"Verify contracts",builder(e){return e.options(Ta)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await xa(e.configPath),r=ka.dirname(t),n=await wa(t),s=await va(o),a=e.rpc??await Ca(o);console.log(ct.bgBlue(ct.whiteBright(`
34
- Verifying MUD contracts${o?" with profile "+o:""} to RPC ${a}
35
- `)));let i=Da({transport:Aa(a,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),l=(await Sa({rootDir:r,config:n})).map(u=>{let y=V(`${u.name}.sol`,u.name,s);return{name:u.name,bytecode:y.bytecode}}),c=await he(n,s);await dt({client:i,rpc:a,systems:l,modules:c,deployerAddress:e.deployerAddress,worldAddress:e.worldAddress,verifier:e.verifier,verifierUrl:e.verifierUrl})}},mt=Pa;import{getRpcUrl as Va}from"@latticexyz/common/foundry";import{createClient as Ka,http as Ja}from"viem";import Ce from"chalk";import{hexToString as Ie,parseAbiItem as pt,stringToHex as je}from"viem";import{getSchemaTypes as Ra}from"@latticexyz/protocol-parser/internal";import{hexToResource as $a,resourceToHex as Fa}from"@latticexyz/common";import Re from"@latticexyz/world-module-metadata/mud.config";import{decodeValueArgs as Ma,getKeyTuple as Oa,getSchemaTypes as Ba,getValueSchema as Ha}from"@latticexyz/protocol-parser/internal";import{readContract as Wa}from"viem/actions";import{mapObject as Ia}from"@latticexyz/common/utils";async function Se({client:e,worldDeploy:o,table:t,key:r}){let[n,s,a]=await Wa(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[t.tableId,Oa(t,r)]}),i={...r,...Ma(Ba(Ha(t)),{staticData:n,encodedLengths:s,dynamicData:a})};return Ia(t.schema,(p,l)=>i[l])}import F from"node:path";import ve from"node:fs/promises";import{getFunctions as La}from"@latticexyz/store-sync/world";import{abiToInterface as ft,formatSolidity as ut,formatTypescript as Ea}from"@latticexyz/common/codegen";var H=M.extend("pull"),ja=M.extend("pull");H.log=console.debug.bind(console);ja.log=console.error.bind(console);import{defineWorld as za}from"@latticexyz/world";import{findUp as Na}from"find-up";import{isDefined as yt}from"@latticexyz/common/utils";var Ua=new Set(["store","world","metadata"]);function gt(e){return Fa({type:"namespace",namespace:e,name:""})}var ee=class extends Error{constructor(t){super(`Attempted to write file at "${t}", but it already exists.`);this.filename=t;this.name="WriteFileExistsError"}};async function bt({rootDir:e,client:o,worldAddress:t,replace:r,indexerUrl:n,chainId:s}){let a=r??await Na(".git",{cwd:e})!=null,i=await me(o,t),p=await U({client:o,worldDeploy:i,indexerUrl:n,chainId:s}),l=p.map($a).filter(x=>!Ua.has(x.namespace)),c=await ie({client:o,worldDeploy:i,indexerUrl:n,chainId:s}),u=Object.fromEntries((await Promise.all(p.map(async x=>{let{value:w}=await Se({client:o,worldDeploy:i,table:Re.tables.metadata__ResourceTag,key:{resource:x,tag:je("label",{size:32})}}),m=Ie(w);return[x,m===""?null:m]}))).filter(([,x])=>x!=null));u[gt("")]??="root";let y=await La({client:o,worldAddress:i.address,fromBlock:i.deployBlock,toBlock:i.stateBlock,indexerUrl:n,chainId:s}),d=l.filter(x=>x.type==="namespace"),f=await Promise.all(l.filter(x=>x.type==="system").map(async({namespace:x,name:w,resourceId:m})=>{let b=gt(x),T=u[m]??w.replace(/(S(y(s(t(e(m)?)?)?)?)?)?$/,"System"),[R,oe]=await Promise.all([Se({client:o,worldDeploy:i,table:Re.tables.metadata__ResourceTag,key:{resource:m,tag:je("abi",{size:32})}}).then(C=>Ie(C.value)).then(C=>C!==""?C.split(`
36
- `):[]),Se({client:o,worldDeploy:i,table:Re.tables.metadata__ResourceTag,key:{resource:m,tag:je("worldAbi",{size:32})}}).then(C=>Ie(C.value)).then(C=>C!==""?C.split(`
37
- `):[])]),S=y.filter(C=>C.systemId===m),P=(R.length?R:S.map(C=>`function ${C.systemFunctionSignature}`)).map(C=>{try{return pt(C)}catch{H(`Skipping invalid system signature: ${C}`)}}).filter(yt),te=(oe.length?oe:S.map(C=>`function ${C.signature}`)).map(C=>{try{return pt(C)}catch{H(`Skipping invalid world signature: ${C}`)}}).filter(yt);return{namespaceId:b,namespaceLabel:u[b]??x,label:T,systemId:m,namespace:x,name:w,abi:P,worldAbi:te}}));H("generating config");let h={namespaces:Object.fromEntries(d.map(({namespace:x,resourceId:w})=>{let m=u[w]??x;return[m,{...m!==x?{namespace:x}:null,tables:Object.fromEntries(c.filter(b=>b.namespace===x).map(b=>{let T=u[b.tableId]??b.name;return[T,{...T!==b.name?{name:b.name}:null,...b.type!=="table"?{type:b.type}:null,schema:Ra(b.schema),key:b.key,deploy:{disabled:!0}}]}))}]}))};H("validating config");let v=za(h);H("writing config"),await $e(F.join(e,"mud.config.ts"),await Ea(`
38
- import { defineWorld } from "@latticexyz/world";
39
-
40
- export default defineWorld(${JSON.stringify(h)});
41
- `),{overwrite:a});let A=F.join(v.sourceDirectory,"remote");a&&await ve.rm(A,{recursive:!0,force:!0});for(let x of f.filter(w=>w.abi.length)){let w=`I${x.label}`,m=F.join(A,"namespaces",x.namespaceLabel,`${w}.sol`);H("writing system interface",w,"to",m);let b=ft({name:w,systemId:x.systemId,abi:x.abi});await $e(F.join(e,m),await ut(b),{overwrite:a})}let k=f.flatMap(x=>x.worldAbi);if(k.length){let x="IWorldSystems",w=F.join(A,`${x}.sol`);H("writing world systems interface to",w);let m=ft({name:x,abi:k});await $e(F.join(e,w),await ut(m),{overwrite:a})}return{config:v}}async function _a(e){return ve.access(e).then(()=>!0,()=>!1)}async function $e(e,o,t={}){if(!t.overwrite&&await _a(e))throw new ee(e);await ve.mkdir(F.dirname(e),{recursive:!0}),await ve.writeFile(e,o)}import qa from"node:path";import{getChainId as Ya}from"viem/actions";var Ga={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."},indexerUrl:{type:"string",desc:"The indexer URL to pull from.",required:!1}},Qa={command:"pull",describe:"Pull mud.config.ts and interfaces from an existing world.",builder(e){return e.options(Ga)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=e.rpc??await Va(o),r=Ka({transport:Ja(t,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),n=await Ya(r),s=e.indexerUrl??we.find(i=>i.id===n)?.indexerUrl;console.log(Ce.bgBlue(Ce.whiteBright(`
42
- Pulling MUD config from world at ${e.worldAddress}
43
- `)));let a=process.cwd();try{let{config:i}=await bt({rootDir:a,client:r,worldAddress:e.worldAddress,indexerUrl:s,chainId:n,replace:e.replace});await L({rootDir:a,config:i,foundryProfile:o})}catch(i){if(i instanceof ee){console.log(),console.log(Ce.bgRed(Ce.whiteBright(" Error "))),console.log(` Attempted to write file at "${qa.relative(a,i.filename)}", but it already exists.`),console.log(),console.log(" To overwrite files, use `--replace` when running this command."),console.log();return}throw i}}},ht=Qa;var ay=[Fe,Qo,Le,Za,Ee,ze,Zo,tt,rt,at,it,Xa,mt,ht];export{ay as commands};
44
- //# sourceMappingURL=commands-6WDCECG5.js.map