@latticexyz/cli 2.2.15-entrykit-f3113a2da978f5b4fed35b3756893ea1c883b346 → 2.2.15-entrykit-a12e0377cb4a99f5d6891ae74070213ebf07e3a9

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,54 +1,54 @@
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 tc}from"@latticexyz/gas-report/internal";import{command as rc}from"@latticexyz/abi-ts/internal";import{loadConfig as Ft,resolveConfigPath as zt}from"@latticexyz/config/node";import{tablegen as Wt}from"@latticexyz/store/codegen";import{buildSystemsManifest as jt,worldgen as $t}from"@latticexyz/world/node";import{forge as Lt}from"@latticexyz/common/foundry";import{execa as Et}from"execa";async function F({rootDir:e,config:o,foundryProfile:t=process.env.FOUNDRY_PROFILE}){await Promise.all([Wt({rootDir:e,config:o}),$t({rootDir:e,config:o})]),await Lt(["build"],{profile:t}),await jt({rootDir:e,config:o}),await Et("mud",["abi-ts"],{stdio:"inherit"})}import Nt 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 zt(e.configPath),t=await Ft(o);await F({rootDir:Nt.dirname(o),config:t,foundryProfile:e.profile}),process.exit(0)}},Ye=_t;import{rmSync as Ut}from"fs";import{homedir as Vt}from"os";import Kt from"path";import{execa as Jt}from"execa";var qt={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=Vt();Ut(Kt.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=Jt("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=qt;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 Yt,resolveConfigPath as Qt}from"@latticexyz/config/node";import{tablegen as Zt}from"@latticexyz/store/codegen";import Xt from"node:path";var er={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 Qt(e.configPath),t=await Yt(o);await Zt({rootDir:Xt.dirname(o),config:t}),process.exit(0)}},Xe=er;import ve from"node:path";import{existsSync as os,mkdirSync as ts,readFileSync as rs,writeFileSync as ze}from"node:fs";import{stringToHex as ca}from"viem";import{getBalance as ir,sendRawTransaction as cr,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"),tr=eo("mud:cli");M.log=console.debug.bind(console);tr.log=console.error.bind(console);var m=M.extend("deploy"),rr=M.extend("deploy");m.log=console.debug.bind(console);rr.log=console.error.bind(console);import{sliceHex as nr}from"viem";import{getCode as ar}from"viem/actions";import{getAction as sr}from"viem/utils";var se=`0x${P.address}`;async function ie(e){let o=await sr(e,ar,"getCode")({address:se});if(o)return m("found CREATE2 deployer at",se),o!==nr(`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
- `),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(`
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,ir,"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,cr,"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.
6
6
 
7
7
  We recommend running your chain's node with \`--rpc.allow-unprotected-txs\` to enable determinstic deployments.
8
8
  `),m("deploying CREATE2 deployer"),z(e,oo,"sendTransaction")({chain:e.chain??null,account:e.account,data:`0x${P.creationCode}`});throw i}),s=await z(e,to,"waitForTransactionReceipt")({hash:a});if(!s.contractAddress)throw new Error("Deploy receipt did not have contract address, was the deployer not deployed?");return s.contractAddress!==Me&&console.warn(`
9
- \u26A0\uFE0F CREATE2 deployer created at ${s.contractAddress} does not match the CREATE2 determinstic deployer we expected (${Me})`),s.contractAddress}import{parseEventLogs as jr}from"viem";import{waitForTransactionReceipt as $r,writeContract as Lr}from"viem/actions";import{concatHex as ur,getCreate2Address as yr}from"viem";import{getCode as gr,sendTransaction as br}from"viem/actions";import{padHex as lr}from"viem";import mr from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{helloStoreEvent as pr}from"@latticexyz/store";import{helloWorldEvent as fr}from"@latticexyz/world";var T=lr("0x",{size:32}),Z=parseInt("6000",16),ce=[pr,fr],k=mr,no=["2.0.0","2.0.1","2.0.2"],ao=["2.0.0","2.0.1","2.0.2"];import hr from"p-retry";import{getAction as so}from"viem/utils";async function io({client:e,deployerAddress:o,bytecode:t,deployedBytecodeSize:r,debugLabel:n="contract"}){if(t.includes("__$"))throw new Error(`Found unlinked public library in ${n} bytecode`);let a=yr({from:o,salt:T,bytecode:t});return await so(e,gr,"getCode")({address:a,blockTag:"pending"})?(m("found",n,"at",a),[]):(r!=null&&(r>Z?console.warn(`
9
+ \u26A0\uFE0F CREATE2 deployer created at ${s.contractAddress} does not match the CREATE2 determinstic deployer we expected (${Me})`),s.contractAddress}import{parseEventLogs as Wr}from"viem";import{waitForTransactionReceipt as jr,writeContract as $r}from"viem/actions";import{concatHex as fr,getCreate2Address as ur}from"viem";import{getCode as yr,sendTransaction as gr}from"viem/actions";import{padHex as dr}from"viem";import lr from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import{helloStoreEvent as mr}from"@latticexyz/store";import{helloWorldEvent as pr}from"@latticexyz/world";var T=dr("0x",{size:32}),Z=parseInt("6000",16),ce=[mr,pr],k=lr,no=["2.0.0","2.0.1","2.0.2"],ao=["2.0.0","2.0.1","2.0.2"];import br from"p-retry";import{getAction as so}from"viem/utils";async function io({client:e,deployerAddress:o,bytecode:t,deployedBytecodeSize:r,debugLabel:n="contract"}){if(t.includes("__$"))throw new Error(`Found unlinked public library in ${n} bytecode`);let a=ur({from:o,salt:T,bytecode:t});return await so(e,yr,"getCode")({address:a,blockTag:"pending"})?(m("found",n,"at",a),[]):(r!=null&&(r>Z?console.warn(`
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(`
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(`
13
+ `)),m("deploying",n,"at",a),[await br(()=>so(e,gr,"sendTransaction")({chain:e.chain??null,account:e.account,to:o,data:fr([T,t])}),{retries:3,onFailedAttempt:()=>m(`failed to deploy ${n}, retrying...`)})])}import{uniqueBy as xr}from"@latticexyz/common/utils";import{waitForTransactionReceipt as hr}from"viem/actions";import{getAction as wr}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 wr(e,hr,"waitForTransactionReceipt")({hash:r})).status==="reverted")throw new Error(`Transaction reverted: ${r}`)}}async function B({client:e,deployerAddress:o,contracts:t}){let r=xr(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 vr from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{getCreate2Address as Sr,encodeDeployData as Tr,size as kr}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 Cr from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import{getCreate2Address as X,encodeDeployData as Ar,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=Ar({bytecode:fo.bytecode.object,abi:Cr,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=kr(uo.deployedBytecode.object),r=Tr({bytecode:uo.bytecode.object,abi:vr,args:[o.InitModule.address]}),n=Sr({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 Dr from"@latticexyz/world/out/WorldProxyFactory.sol/WorldProxyFactory.abi.json"assert{type:"json"};import{getCreate2Address as Pr,encodeDeployData as Mr,size as Br}from"viem";function le(e){let o=N(e),t=Br(yo.deployedBytecode.object),r=Mr({bytecode:yo.bytecode.object,abi:Dr,args:[o.InitModule.address]}),n=Pr({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 Lr from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{AbiEventSignatureNotFoundError as Or,decodeEventLog as Rr,hexToString as bo,parseAbi as Ir}from"viem";import{isDefined as Hr}from"@latticexyz/common/utils";function _(e){let o=e.map(s=>{try{return{...s,...Rr({strict:!0,abi:Ir(ce),topics:s.topics,data:s.data})}}catch(i){if(i instanceof Or)return;throw i}}).filter(Hr),{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 Er}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,$r,"writeContract")({chain:e.chain??null,account:e.account,address:n,abi:Lr,functionName:"deployWorld",args:[t]});m("waiting for world deploy at tx",a);let s=await ho(e,jr,"waitForTransactionReceipt")({hash:a});if(s.status!=="success")throw console.error("world deploy failed",s),new Error("world deploy failed");if(e.account.type==="smart"&&!Wr({logs:s.logs,abi:Er,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 qr,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 Fr}from"@latticexyz/common";import{decodeKey as zr,decodeValueArgs as Nr,getKeySchema as _r,getSchemaTypes as Ao,getValueSchema as Ur,hexToSchema as vo}from"@latticexyz/protocol-parser/internal";import Be from"@latticexyz/store/mud.config";import{fetchBlockLogs as Vr}from"@latticexyz/block-logs-stream";import{flattenStoreLogs as Kr,getStoreLogs as Jr}from"@latticexyz/store/internal";async function me({client:e,worldDeploy:o}){m("looking up tables for",o.address);let t=await Vr({fromBlock:o.deployBlock,toBlock:o.stateBlock,maxBlockRange:100000n,async getLogs({fromBlock:a,toBlock:s}){return Jr(e,{address:o.address,fromBlock:a,toBlock:s,tableId:Be.namespaces.store.tables.Tables.tableId})}}),n=Kr(t.flatMap(a=>a.logs)).map(a=>{let{tableId:s}=zr(Ao(_r(Be.namespaces.store.tables.Tables)),a.args.keyTuple),{type:i,namespace:d,name:c}=Fr(s),p=Nr(Ao(Ur(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 Yr}from"@latticexyz/common/utils";import{writeContract as Qr}from"viem/actions";import{getAction as Zr}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(`
14
+ `)}).filter(Yr);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=U(Do(d)),p=U(ko(d));return Gr(()=>Zr(e,Qr,"writeContract")({chain:e.chain??null,account:e.account,address:o.address,abi:k,functionName:"registerTable",args:[d.tableId,qr(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 bn,resourceToLabel as hn}from"@latticexyz/common";import{getFunctions as wn}from"@latticexyz/world/internal";import{flattenStoreLogs as Xr,getStoreLogs as en}from"@latticexyz/store/internal";import on from"@latticexyz/store/mud.config";import{fetchBlockLogs as tn}from"@latticexyz/block-logs-stream";async function V({client:e,worldDeploy:o}){m("looking up resource IDs for",o.address);let t=await tn({fromBlock:o.deployBlock,toBlock:o.stateBlock,maxBlockRange:100000n,async getLogs({fromBlock:a,toBlock:s}){return en(e,{address:o.address,fromBlock:a,toBlock:s,tableId:on.namespaces.store.tables.ResourceIds.tableId})}}),n=Xr(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 rn,encodeKey as nn,getKeySchema as an,getSchemaTypes as Mo,getValueSchema as sn}from"@latticexyz/protocol-parser/internal";import{readContract as cn}from"viem/actions";import{getAction as dn}from"viem/utils";async function K({client:e,worldDeploy:o,table:t,key:r}){let[n,a,s]=await dn(e,cn,"readContract")({blockNumber:o.stateBlock,address:o.address,abi:k,functionName:"getRecord",args:[t.tableId,nn(Mo(an(t)),r)]});return rn(Mo(sn(t)),{staticData:n,encodedLengths:a,dynamicData:s})}import{getAddress as ln}from"viem";import{decodeKey as mn,getKeySchema as pn,getSchemaTypes as fn}from"@latticexyz/protocol-parser/internal";import Oe from"@latticexyz/world/mud.config";import{fetchBlockLogs as un}from"@latticexyz/block-logs-stream";import{flattenStoreLogs as yn,getStoreLogs as gn}from"@latticexyz/store/internal";async function fe({client:e,worldDeploy:o}){m("looking up resource access for",o.address);let t=await un({fromBlock:o.deployBlock,toBlock:o.stateBlock,maxBlockRange:100000n,async getLogs({fromBlock:s,toBlock:i}){return gn(e,{address:o.address,fromBlock:s,toBlock:i,tableId:Oe.namespaces.world.tables.ResourceAccess.tableId})}}),n=yn(t.flatMap(s=>s.logs)).map(s=>mn(fn(pn(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:ln(s.caller)}));return m("found",a.length,"resource<>address access pairs"),a}import xn from"@latticexyz/world/mud.config";async function Bo({client:e,worldDeploy:o}){let[t,r,n]=await Promise.all([V({client:e,worldDeploy:o}),wn({client:e,worldAddress:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock}),fe({client:e,worldDeploy:o})]),a=t.map(bn).filter(s=>s.type==="system");return m("looking up systems:",a.map(hn).join(", ")),await Promise.all(a.map(async s=>{let{system:i,publicAccess:d}=await K({client:e,worldDeploy:o,table:xn.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 Cn,parseAbi as An}from"viem";import{getBlock as We}from"viem/actions";import{fetchBlockLogs as vn}from"@latticexyz/block-logs-stream";import{getAction as je}from"viem/utils";var Ro=new Map;async function ue(e,o){let t=Cn(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 vn({publicClient:e,address:t,events:An(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 Sn}from"@latticexyz/common";import{getFunctions as Tn}from"@latticexyz/world/internal";import kn from"p-retry";import{getAction as Dn}from"viem/utils";import{writeContract as Pn}from"viem/actions";async function Io({client:e,worldDeploy:o,functions:t}){let r=await Tn({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}=Sn(i.systemId),c=d===""?{functionName:"registerRootFunctionSelector",args:[i.systemId,i.systemFunctionSignature,i.systemFunctionSignature]}:{functionName:"registerFunctionSelector",args:[i.systemId,i.systemFunctionSignature]};return kn(()=>Dn(e,Pn,"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 Mn}from"viem";import{isDefined as Bn}from"@latticexyz/common/utils";import On from"p-retry";import{getAction as Rn}from"viem/utils";import{writeContract as In}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=>On(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 Rn(e,In,"writeContract")({chain:e.chain??null,account:e.account,address:r.address,abi:s,...d})}catch(s){if(s instanceof Mn&&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(Bn)):[]}import{getAddress as Ho}from"viem";import{hexToResource as Wo,resourceToHex as jo}from"@latticexyz/common";import Hn from"@latticexyz/world/mud.config";import{getAction as Wn}from"viem/utils";import{writeContract as jn}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:Hn.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=>Wn(e,jn,"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 da,resourceToLabel as la}from"@latticexyz/common";import{randomBytes as ma}from"crypto";import{stringToHex as _n,BaseError as Un,concatHex as Fo}from"viem";import{hexToResource as Vn}from"@latticexyz/common";import{identity as Kn,isDefined as Jn}from"@latticexyz/common/utils";import he from"@latticexyz/world-module-metadata/mud.config";import qn 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 $n,size as Ln}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 En}from"abitype/zod";function Fn(e){return $n(e,{strict:!1})}var Lo=I.object({object:I.string().refine(Fn),linkReferences:I.record(I.record(I.array(I.object({start:I.number(),length:I.number()})))).optional()}),zn=I.object({bytecode:Lo,deployedBytecode:Lo,abi:En});function be(e){let o=zn.parse(e),t=ge(o.bytecode.linkReferences??{});return{abi:o.abi,bytecode:o.bytecode.object,placeholders:t,deployedBytecodeSize:Ln(o.deployedBytecode.object)}}import{spliceHex as Nn}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=Nn(a,s.start,s.length,i)}return{bytecode:a,address:Eo({from:r,bytecode:a,salt:T})}}}import{fetchBlockLogs as Yn}from"@latticexyz/block-logs-stream";import{getStoreLogs as Qn,flattenStoreLogs as Zn,logToRecord as Xn}from"@latticexyz/store/internal";import{getKeyTuple as zo}from"@latticexyz/protocol-parser/internal";import{getAction as ea}from"viem/utils";import{writeContract as oa}from"viem/actions";var we=be(Gn);async function No({client:e,deployerAddress:o,libraryMap:t,worldDeploy:r,tags:n,valueToHex:a=Kn}){m("ensuring",n.length,"resource tags"),m("looking up existing resource tags");let s=await Yn({fromBlock:r.deployBlock,toBlock:r.stateBlock,maxBlockRange:100000n,async getLogs({fromBlock:b,toBlock:y}){return Qn(e,{address:r.address,fromBlock:b,toBlock:y,tableId:he.tables.metadata__ResourceTag.tableId})}}),d=Zn(s.flatMap(b=>b.logs)).map(b=>Xn({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=Vn(b.resource),x=`${y.type}:${y.namespace}:${y.name}`;m(`tagging ${x} with ${b.tag}: ${JSON.stringify(b.value)}`);try{return await ea(e,oa,"writeContract")({chain:e.chain??null,account:e.account,address:r.address,abi:qn,functionName:"metadata__setResourceTag",args:[b.resource,b.tag,b.value]})}catch(A){m(`failed to set resource tag for ${x}, skipping
18
+ ${A instanceof Un?A.shortMessage:A}`)}}))).filter(Jn)}import{concatHex as ta,encodeDeployData as ra,getCreate2Address as na,isHex as Uo}from"viem";import{waitForTransactionReceipt as aa,writeContract as _o,sendTransaction as sa}from"viem/actions";import{resourceToHex as ia}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 ta(o.bytecode.map(r=>Uo(r)?r:na({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,sa,"sendTransaction")({chain:e.chain??null,account:e.account,data:ra({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,aa,"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:[ia({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 pa}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${ma(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:`${la(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=pa([...t,...r].filter(({namespace:w,namespaceLabel:D})=>D!==w).map(({namespace:w,namespaceLabel:D})=>({resourceId:da({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:ca});return await O({client:o,hashes:[...A,...h,...v],debugLabel:"remaining transactions"}),m("deploy complete"),f}import{isHex as ns}from"viem";import{privateKeyToAccount as as}from"viem/accounts";import{loadConfig as ss,resolveConfigPath as is}from"@latticexyz/config/node";import{getOutDirectory as cs,getRpcUrl as ds}from"@latticexyz/common/foundry";import q from"chalk";import{MUDError as Ne}from"@latticexyz/common/errors";import Zo from"path";import{loadSystemsManifest as wa,resolveSystems as xa}from"@latticexyz/world/node";import{isHex as Xo,toFunctionSelector as et,toFunctionSignature as ot}from"viem";import{readFileSync as fa}from"fs";import ua from"path";import{MUDError as Ce}from"@latticexyz/common/errors";import{size as ya}from"viem";function J(e,o,t){let r,n=ua.join(t,e,o+".json");try{r=JSON.parse(fa(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:ya(s)}}import{groupBy as Ca}from"@latticexyz/common/utils";import{readFileSync as ba}from"fs";import{globSync as ha}from"glob";import ga from"toposort";function Yo(e,o,t){let r=ga(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=ha(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).sort().map(r=>JSON.parse(ba(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 Aa}from"find-up";import{createRequire as va}from"node:module";async function tt({rootDir:e,config:o,forgeOutDir:t}){let r=await Aa("package.json");if(!r)throw new Error("Could not find package.json to import relative to.");let n=va(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 xa({rootDir:e,config:o}),p=await wa({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=Ca(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
- 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=[Za,mt];async function pt(e){let o=await Ga(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"})},userOperation:{estimateFeesPerGas:t?async()=>({maxFeePerGas:100000n,maxPriorityFeePerGas:0n}):void 0}}).extend(Ka());if(Ua(t)&&(await _a({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,Ya,"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 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(`
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 ls}from"viem/actions";import{existsSync as Sa}from"fs";import Ta from"path";import ka from"chalk";import{getScriptDirectory as Da,forge as Pa}from"@latticexyz/common/foundry";async function rt(e,o,t,r,n,a){let s=n?.replaceAll("\\","").split(" ")??[],i=Ta.join(await Da(),e+".s.sol");if(!Sa(i)){console.log(`No script at ${i}, skipping post deploy hook`);return}console.log(ka.blue(`Executing post deploy script at ${i}`)),await Pa(["script",e,"--broadcast","--sig","run(address)",o,"--rpc-url",t,"-vvv",a?"--aws":"",...s],{profile:r})}import{kmsKeyToAccount as ms}from"@latticexyz/common/kms";import at from"node:path";import{encodeField as Oa}from"@latticexyz/protocol-parser/internal";import{bytesToHex as Ra}from"viem";import{createRequire as Ma}from"node:module";import{findUp as Ba}from"find-up";async function nt({packageJsonPath:e,artifactPath:o}){let t;try{let r=e??await Ba("package.json",{cwd:process.cwd()});if(!r)throw new Error("Could not find package.json to import relative to.");t=Ma(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 Ia}from"@latticexyz/world/internal";var Ha={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=Ha[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=>Ia(d,{config:e})).map(d=>{let c=d.value instanceof Uint8Array?Ra(d.value):d.value;return Oa(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 ps}from"@latticexyz/world/node";import{getAutomine as Wa,getBlock as st,setAutomine as ja,setIntervalMining as $a}from"viem/actions";import{getAction as te}from"viem/utils";async function ct(e){let o=await La(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 La(e){let o={mode:"anvil",...e};return await te(o,Wa,"getAutomine")({})?{type:"automine"}:{type:"interval",blockTime:await Ea(e)}}async function it(e,o){o.type==="automine"?await te(e,ja,"setAutomine")(!0):await te(e,$a,"setIntervalMining")({interval:o.blockTime})}async function Ea(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 Fa}from"@latticexyz/common/actions";import{rhodolite as lt}from"@latticexyz/common/chains";import{claimGasPass as za,getAllowance as Na,hasPassIssuer as _a,gasEstimator as Ua}from"@latticexyz/paymaster/internal";import{smartAccountActions as Va}from"permissionless";import{toSimpleSmartAccount as Ka}from"permissionless/accounts";import{createClient as Ee,http as Fe,zeroAddress as Ja,parseEther as dt}from"viem";import{getChainId as qa,getTransactionReceipt as Ga,setBalance as Ya}from"viem/actions";import{anvil as Qa}from"viem/chains";import{createBundlerClient as Za}from"viem/account-abstraction";import{getAction as Xa}from"viem/utils";var es=[Qa,lt];async function mt(e){let o=await qa(Ee({transport:Fe(e.rpcUrl)})),t=es.find(s=>s.id===o),r=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 Ka({client:c,owner:e.account}),f=Za({chain:t,transport:Ua(Fe(s)),account:p,paymaster:{getPaymasterData:async()=>({paymaster:d,paymasterData:"0x"})},userOperation:{estimateFeesPerGas:t?async()=>({maxFeePerGas:100000n,maxPriorityFeePerGas:0n}):void 0}}).extend(Va());if(_a(t)&&(await Na({client:c,paymasterAddress:d,userAddress:p.address})>=dt("0.01")?m("deployer smart account should have enough gas allowance"):(m("claimimg gas pass for deployer smart account"),await za({chain:lt,userAddress:p.address}))),!await p.isDeployed()){m("creating deployer smart account at",p.address);let g=await f.sendTransaction({to:Ja});m("tx:",g);let b=await Xa(f,Ga,"getTransactionReceipt")({hash:g});m("receipt:",b.status)}return f}}let a=Ee({...n,account:e.account}).extend(Fa());return o==31337&&(m("setting anvil balance"),await Ya(a.extend(()=>({mode:"anvil"})),{address:a.account.address,value:dt("100")})),a}import{getAction as fs}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 G(e){let o=e.salt;if(o!=null&&!ns(o))throw new Ne("Expected hex string for salt");let t=e.profile??process.env.FOUNDRY_PROFILE,r=await is(e.configPath),n=await ss(r),a=ve.dirname(r);e.printConfig&&console.log(q.green(`
24
24
  Resolved config:
25
- `),JSON.stringify(n,null,2));let s=await ds(t),i=e.rpc??await ls(t);console.log(q.bgBlue(q.whiteBright(`
25
+ `),JSON.stringify(n,null,2));let s=await cs(t),i=e.rpc??await ds(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}),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.
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 ps({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 ms({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,useSmartAccount:e.smartAccount}),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 as(l)}})();console.log("Deploying from",b.address),M("deploying from",b.address);let y=await mt({rpcUrl:i,rpcBatch:e.rpcBatch,account:b,useSmartAccount:e.smartAccount}),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 fs(y,ls,"getChainId")({}),u=ve.join(n.deploy.deploysDirectory,l.toString());ts(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=os(n.deploy.worldsFile)?JSON.parse(rs(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 us={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)}},pt=us;import ys from"node:path";import{loadConfig as gs,resolveConfigPath as bs}from"@latticexyz/config/node";import{worldgen as hs}from"@latticexyz/world/node";var ws={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 xs(e),process.exit(0)}};async function xs(e){let o=await bs(e.configPath),t=await gs(o),r=ys.dirname(o);await hs({rootDir:r,config:t,clean:e.clean})}var ft=ws;import re from"chalk";import{readFileSync as Ts,writeFileSync as ks}from"fs";import Ue from"path";import{MUDError as Y}from"@latticexyz/common/errors";var ut={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 Ds}from"glob";import{ZodError as As,z as yt}from"zod";var vs=yt.object({MUD_PACKAGES:yt.string().transform(e=>JSON.parse(e))});function Ss(){try{return vs.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 As){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,smartAccount:R.smartAccount},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 _e=Ss().MUD_PACKAGES;var Ps={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 Ms(e));let r=Ds("**/package.json").sort().filter(n=>!n.includes("node_modules"));for(let n of r)Bs(n,e)}catch(o){ae(o)}finally{process.exit(0)}}};async function Ms(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/${ut.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 Bs(e,o){let{link:t}=o,{mudVersion:r}=o,n=Os(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 ks(e,JSON.stringify(n,null,2)+`
37
+ `),console.log(`Updating ${e}`),gt(s,n.dependencies),gt(i,n.devDependencies),n;function d(c,p){return t&&(r=Rs(e,t,c)),r||n[p][c]}}function Os(e){try{let o=Ts(e,"utf8");return JSON.parse(o)}catch{throw new Y("Could not read JSON at "+e)}}function gt(e,o){for(let t in e)e[t]!==o[t]&&console.log(`${t}: ${re.red(e[t])} -> ${re.green(o[t])}`)}function Rs(e,o,t){let r=Ue.relative(Ue.dirname(e),process.cwd());return"link:"+Ue.join(r,o,_e[t].localPath)}var bt=Ps;import{anvil as Is,forge as Hs,getRpcUrl as Ws}from"@latticexyz/common/foundry";import js from"chalk";var $s={...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"}},Ls={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options($s)},async handler(e){if(!e.worldAddress){let n=["--block-base-fee-per-gas","0","--port",String(e.port)];Is(n)}let o=e.worldAddress?await Ws(e.profile):`http://127.0.0.1:${e.port}`,t=e.worldAddress??(await G({...e,saveDeployment:!1,rpc:o})).address;console.log(js.blue("World address",t));let r=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await Hs(["test","--fork-url",o,...r],{profile:e.profile,env:{WORLD_ADDRESS:t}}),process.exit(0)}catch(n){console.error(n),process.exit(1)}}},ht=Ls;import Es from"node:path";import wt from"node:fs";import{loadConfig as Fs,resolveConfigPath as zs}from"@latticexyz/config/node";import{MUDError as xt}from"@latticexyz/common/errors";import{cast as Ns,getRpcUrl as _s}from"@latticexyz/common/foundry";import Us from"@latticexyz/world/mud.config";import{createClient as Vs,http as Ks}from"viem";import{getChainId as Js,readContract as qs}from"viem/actions";import{resolveSystems as Gs}from"@latticexyz/world/node";import{getAction as Ct}from"viem/utils";var Ys=Us.namespaces.world.tables.Systems.tableId;function Qs(e,o){if(!wt.existsSync(e))throw new xt(`Missing expected worlds.json file at "${e}"`);let t=JSON.parse(wt.readFileSync(e,"utf-8"));if(!t[o])throw new xt(`Missing chain ID ${o} in "${e}"`);return t[o].address}var Zs={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 zs(e.configPath),t=Es.dirname(o),r=e.profile??process.env.FOUNDRY_PROFILE,n=e.rpc??await _s(r),a=await Fs(o),s=Vs({transport:Ks(n)}),i=await Ct(s,Js,"getChainId")({}),d=e.worldAddress??Qs(a.deploy.worldsFile,i),c=await Gs({rootDir:t,config:a}),p=await Promise.all(c.map(async g=>({label:g.label,address:await Ct(s,qs,"readContract")({abi:k,address:d,functionName:"getField",args:[Ys,[g.systemId],0]})}))),f=await Ns(["run","--label",`${d}:World`,...p.map(({label:g,address:b})=>["--label",`${b}:${g}`]).flat(),`${e.tx}`]);console.log(f),process.exit(0)}},At=Zs;import{anvil as Xs,getScriptDirectory as ei,getSrcDirectory as oi}from"@latticexyz/common/foundry";import j from"chalk";import ti from"chokidar";import{loadConfig as ri,resolveConfigPath as ni}from"@latticexyz/config/node";import ai from"path";import{homedir as si}from"os";import{rmSync as ii}from"fs";import{BehaviorSubject as ci,debounceTime as di,exhaustMap as li,filter as mi}from"rxjs";import{isDefined as pi}from"@latticexyz/common/utils";var fi={rpc:R.rpc,configPath:R.configPath,alwaysRunPostDeploy:R.alwaysRunPostDeploy,forgeScriptOptions:R.forgeScriptOptions,worldAddress:R.worldAddress,smartAccount:R.smartAccount},ui={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(fi)},async handler(e){let o=e.rpc,t=e.configPath??await ni(e.configPath),r=await oi(),n=await ei(),a=await ri(t);if(!e.rpc){console.log(j.gray("Cleaning devnode cache"));let c=si();ii(ai.join(c,".foundry","anvil","tmp"),{recursive:!0,force:!0}),Xs(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let s=new ci(Date.now());ti.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(di(200),li(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(`
38
38
  Waiting for file changes\u2026
39
39
  `)),p}catch(p){console.error(j.bgRed(j.whiteBright(`
40
40
  Error while attempting deploy
41
41
  `))),console.error(p),console.log(j.gray(`
42
42
  Waiting for file changes\u2026
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(`
43
+ `))}}),mi(pi)).subscribe()}},vt=ui;import{getCreate2Address as St,sliceHex as gi,zeroHash as bi}from"viem";import{forge as yi}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 yi(o,{cwd:e.cwd})}import hi from"p-queue";import{MUDError as wi}from"@latticexyz/common/errors";import{getStorageAt as xi}from"viem/actions";import{execa as Ve}from"execa";import{getAction as Ci}from"viem/utils";var Ai="0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";async function Tt({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 wi("No deployer address provided or found.");let c=await Ci(e,xi,"getStorageAt")({address:n,slot:Ai}),p=c&&c!==bi,f=new hi({concurrency:4});if(t.map(({name:g,bytecode:b})=>f.add(()=>L({name:g,rpc:o,verifier:s,verifierUrl:i,address:St({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:St({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=gi(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 vi,resolveConfigPath as Si}from"@latticexyz/config/node";import{resolveSystems as Ti}from"@latticexyz/world/node";import{getOutDirectory as ki,getRpcUrl as Di}from"@latticexyz/common/foundry";import{createWalletClient as Pi,http as Mi}from"viem";import kt from"chalk";import Bi from"node:path";var Oi={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."}},Ri={command:"verify",describe:"Verify contracts",builder(e){return e.options(Oi)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=await Si(e.configPath),r=Bi.dirname(t),n=await vi(t),a=await ki(o),s=e.rpc??await Di(o);console.log(kt.bgBlue(kt.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=Pi({transport:Mi(s,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0})}),c=(await Ti({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 Tt({client:i,rpc:s,systems:c,modules:p,deployerAddress:e.deployerAddress,worldAddress:e.worldAddress,verifier:e.verifier,verifierUrl:e.verifierUrl})}},Dt=Ri;import{getRpcUrl as Yi}from"@latticexyz/common/foundry";import{createClient as Qi,http as Zi}from"viem";import ke from"chalk";import{hexToString as Ke,parseAbiItem as Pt,stringToHex as Je}from"viem";import{getSchemaTypes as zi}from"@latticexyz/protocol-parser/internal";import{hexToResource as Ni,resourceToHex as _i}from"@latticexyz/common";import qe from"@latticexyz/world-module-metadata/mud.config";import{decodeValueArgs as Ii,getKeyTuple as Hi,getSchemaTypes as Wi,getValueSchema as ji}from"@latticexyz/protocol-parser/internal";import{readContract as $i}from"viem/actions";import{mapObject as Li}from"@latticexyz/common/utils";import{getAction as Ei}from"viem/utils";async function Se({client:e,worldDeploy:o,table:t,key:r}){let[n,a,s]=await Ei(e,$i,"readContract")({blockNumber:o.stateBlock,address:o.address,abi:k,functionName:"getRecord",args:[t.tableId,Hi(t,r)]}),i={...r,...Ii(Wi(ji(t)),{staticData:n,encodedLengths:a,dynamicData:s})};return Li(t.schema,(d,c)=>i[c])}import E from"node:path";import Te from"node:fs/promises";import{getFunctions as Ui}from"@latticexyz/world/internal";import{abiToInterface as Mt,formatSolidity as Bt,formatTypescript as Vi}from"@latticexyz/common/codegen";var H=M.extend("pull"),Fi=M.extend("pull");H.log=console.debug.bind(console);Fi.log=console.error.bind(console);import{defineWorld as Ki}from"@latticexyz/world";import{findUp as Ji}from"find-up";import{isDefined as Ot}from"@latticexyz/common/utils";var qi=new Set(["store","world","metadata"]);function Rt(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 It({rootDir:e,client:o,worldAddress:t,replace:r}){let n=r??await Ji(".git",{cwd:e})!=null,a=await ue(o,t),s=await V({client:o,worldDeploy:a}),i=s.map(Ni).filter(h=>!qi.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[Rt("")]??="root";let p=await Ui({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=Rt(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 Pt(S)}catch{H(`Skipping invalid system signature: ${S}`)}}).filter(Ot),Pe=(D.length?D:Q.map(S=>`function ${S.signature}`)).map(S=>{try{return Pt(S)}catch{H(`Skipping invalid world signature: ${S}`)}}).filter(Ot);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:zi(u.schema),key:u.key,deploy:{disabled:!0}}]}))}]}))};H("validating config");let y=Ki(b);H("writing config"),await Ge(E.join(e,"mud.config.ts"),await Vi(`
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=Mt({name:C,systemId:h.systemId,abi:h.abi});await Ge(E.join(e,l),await Bt(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=Mt({name:h,abi:A});await Ge(E.join(e,C),await Bt(l),{overwrite:n})}return{config:y}}async function Gi(e){return Te.access(e).then(()=>!0,()=>!1)}async function Ge(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 Xi from"node:path";var ec={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."}},oc={command:"pull",describe:"Pull mud.config.ts and interfaces from an existing world.",builder(e){return e.options(ec)},async handler(e){let o=e.profile??process.env.FOUNDRY_PROFILE,t=e.rpc??await Yi(o),r=Qi({transport:Zi(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-NPM3ZTRX.js.map
53
+ `)));let n=process.cwd();try{let{config:a}=await It({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 "${Xi.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}}},Ht=oc;var lh=[Ye,pt,Qe,tc,Ze,Xe,ft,bt,ht,At,vt,rc,Dt,Ht];export{lh as commands};
54
+ //# sourceMappingURL=commands-GQTCKKN3.js.map