@latticexyz/cli 2.2.18-9fa07c8489f1fbf167d0db01cd9aaa645a29c8e2 → 2.2.18-c44207f620a38653497b78db0b71f5de7bc1a940

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