@latticexyz/cli 2.2.15-entrykit-4c25d1ec5af1bd68a4c1f367c9fe4b6fbea82cb2 → 2.2.15-entrykit-335157ddad18fcbacac0dc64c4efe21778729d96

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