@latticexyz/cli 2.0.7-account-kit-bdf954ce → 2.0.7-main-632a7525
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{commands-KUNU6FEX.js → commands-2FAWZS5F.js} +13 -13
- package/dist/commands-2FAWZS5F.js.map +1 -0
- package/dist/mud.js +1 -1
- package/package.json +12 -12
- package/src/deploy/create2/README.md +2 -2
- package/src/deploy/create2/deployment.json +1 -1
- package/src/deploy/ensureDeployer.ts +4 -4
- package/dist/commands-KUNU6FEX.js.map +0 -1
@@ -1,36 +1,36 @@
|
|
1
|
-
import{a as K}from"./chunk-QXUPZVZL.js";import ps from"@latticexyz/gas-report";import fs from"@latticexyz/abi-ts";import{loadConfig as
|
2
|
-
gracefully shutting down from SIGINT (Crtl-C)`),t.kill(),process.exit()}),await t}},we=
|
1
|
+
import{a as K}from"./chunk-QXUPZVZL.js";import ps from"@latticexyz/gas-report";import fs from"@latticexyz/abi-ts";import{loadConfig as zo}from"@latticexyz/config/node";import{getSrcDirectory as Lo}from"@latticexyz/common/foundry";import Mo from"node:path";import{tablegen as Wo}from"@latticexyz/store/codegen";import{worldgen as $o}from"@latticexyz/world/node";import{worldToV1 as Ho}from"@latticexyz/world/config/v2";import{forge as Fo,getRemappings as Eo}from"@latticexyz/common/foundry";import Oo from"glob";import{basename as Ro}from"path";function I(e){return Oo.sync(`${e}/**/*.sol`).map(o=>({path:o,basename:Ro(o,".sol")}))}import{execa as No}from"execa";async function J({config:e,srcDir:o,foundryProfile:n=process.env.FOUNDRY_PROFILE}){let t=Ho(e),r=Mo.join(o,t.codegenDirectory),s=await Eo(n);await Promise.all([Wo(e,r,s),$o(e,I(o),r)]),await Fo(["build"],{profile:n}),await No("mud",["abi-ts"],{stdio:"inherit"})}var Vo={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 config file"},profile:{type:"string",desc:"The foundry profile to use"}})},async handler({configPath:e,profile:o}){let n=await zo(e),t=await Lo();await J({config:n,srcDir:t,foundryProfile:o}),process.exit(0)}},he=Vo;import{rmSync as Uo}from"fs";import{homedir as _o}from"os";import Ko from"path";import{execa as Jo}from"execa";var qo={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=_o();Uo(Ko.join(o,".foundry","anvil","tmp"),{recursive:!0,force:!0});let n=["-b",String(e),"--block-base-fee-per-gas","0"];console.log(`Running: anvil ${n.join(" ")}`);let t=Jo("anvil",n,{stdio:["inherit","inherit","inherit"]});process.on("SIGINT",()=>{console.log(`
|
2
|
+
gracefully shutting down from SIGINT (Crtl-C)`),t.kill(),process.exit()}),await t}},we=qo;import{FaucetServiceDefinition as Yo}from"@latticexyz/services/faucet";import{createChannel as Go,createClient as Zo}from"nice-grpc-web";import xe from"chalk";import{NodeHttpTransport as Qo}from"@improbable-eng/grpc-web-node-http-transport";function Xo(e){return Zo(Yo,Go(e,Qo()))}var et={command:"faucet",describe:"Interact with a MUD faucet",builder(e){return e.options({dripDev:{type:"boolean",desc:"Request a drip from the dev endpoint (requires faucet to have dev mode enabled)",default:!0},faucetUrl:{type:"string",desc:"URL of the MUD faucet",default:"https://faucet.testnet-mud-services.linfra.xyz"},address:{type:"string",desc:"Ethereum address to fund",required:!0}})},async handler({dripDev:e,faucetUrl:o,address:n}){let t=Xo(o);e&&(console.log(xe.yellow("Dripping to",n)),await t.dripDev({address:n}),console.log(xe.yellow("Success"))),process.exit(0)}},Se=et;var ot={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)}},Ce=ot;import tt from"path";import{loadConfig as rt}from"@latticexyz/config/node";import{tablegen as nt}from"@latticexyz/store/codegen";import{getRemappings as st,getSrcDirectory as at}from"@latticexyz/common/foundry";var it={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 config file"}})},async handler({configPath:e}){let o=await rt(e),n=await at(),t=await st();await nt(o,tt.join(n,o.codegen.outputDirectory),t),process.exit(0)}},De=it;import fe from"node:path";import{existsSync as Zr,mkdirSync as Qr,readFileSync as Xr,writeFileSync as ye}from"node:fs";import{sliceHex as mt}from"viem";import{getBalance as pt,getBytecode as ft,sendRawTransaction as yt,sendTransaction as ve,waitForTransactionReceipt as Ae}from"viem/actions";var A={gasPrice:1e11,gasLimit:1e5,signerAddress:"3fab184622dc19b6109349b94811493bf2a45362",transaction:"f8a58085174876e800830186a08080b853604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf31ba02222222222222222222222222222222222222222222222222222222222222222a02222222222222222222222222222222222222222222222222222222222222222",address:"4e59b44847b379578588920ca78fbf26c0b4956c",creationCode:"604580600e600039806000f350fe7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe03601600081602082378035828234f58015156039578182fd5b8082525050506014600cf3"};import Te from"debug";var q=Te("mud:cli"),ct=Te("mud:cli");q.log=console.debug.bind(console);ct.log=console.error.bind(console);var l=q.extend("deploy"),lt=q.extend("deploy");l.log=console.debug.bind(console);lt.log=console.error.bind(console);var R=`0x${A.address}`;async function ke(e){let o=await ft(e,{address:R});if(o)return l("found CREATE2 deployer at",R),o!==mt(`0x${A.creationCode}`,14)&&console.warn(`
|
3
3
|
\u26A0\uFE0F Bytecode for deployer at ${R} did not match the expected CREATE2 bytecode. You may have unexpected results.
|
4
4
|
`),R;let n=BigInt(A.gasLimit)*BigInt(A.gasPrice),t=await pt(e,{address:`0x${A.signerAddress}`}),r=n-t;if(r>0){l("sending gas for CREATE2 deployer to signer at",A.signerAddress);let a=await ve(e,{chain:e.chain??null,to:`0x${A.signerAddress}`,value:r}),m=await Ae(e,{hash:a});if(m.status!=="success")throw console.error("failed to send gas to deployer signer",m),new Error("failed to send gas to deployer signer")}l("deploying CREATE2 deployer at",R);let s=await yt(e,{serializedTransaction:`0x${A.transaction}`}).catch(a=>{if(String(a).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
|
-
`),l("deploying CREATE2 deployer"),ve(e,{chain:e.chain??null,data
|
9
|
-
\u26A0\uFE0F CREATE2 deployer created at ${i.contractAddress} does not match the CREATE2 determinstic deployer we expected (${R})`),i.contractAddress}import{waitForTransactionReceipt as Et}from"viem/actions";import
|
8
|
+
`),l("deploying CREATE2 deployer"),ve(e,{chain:e.chain??null,data:`0x${A.creationCode}`});throw a}),i=await Ae(e,{hash:s});if(!i.contractAddress)throw new Error("Deploy receipt did not have contract address, was the deployer not deployed?");return i.contractAddress!==R&&console.warn(`
|
9
|
+
\u26A0\uFE0F CREATE2 deployer created at ${i.contractAddress} does not match the CREATE2 determinstic deployer we expected (${R})`),i.contractAddress}import{waitForTransactionReceipt as Et}from"viem/actions";import Oe from"@latticexyz/world/out/AccessManagementSystem.sol/AccessManagementSystem.json"assert{type:"json"};import Re from"@latticexyz/world/out/BalanceTransferSystem.sol/BalanceTransferSystem.json"assert{type:"json"};import Me from"@latticexyz/world/out/BatchCallSystem.sol/BatchCallSystem.json"assert{type:"json"};import We from"@latticexyz/world/out/RegistrationSystem.sol/RegistrationSystem.json"assert{type:"json"};import $e from"@latticexyz/world/out/InitModule.sol/InitModule.json"assert{type:"json"};import Rt from"@latticexyz/world/out/InitModule.sol/InitModule.abi.json"assert{type:"json"};import He from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.json"assert{type:"json"};import Mt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{getCreate2Address as $,encodeDeployData as Fe,size as H}from"viem";import{padHex as gt}from"viem";import bt from"@latticexyz/store/mud.config";import ht from"@latticexyz/world/mud.config";import wt from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import xt from"@latticexyz/world-modules/out/IModule.sol/IModule.abi.json"assert{type:"json"};import{resourceToHex as ut}from"@latticexyz/common";import{resolveUserTypes as Ie}from"@latticexyz/store/internal";function z(e){let o={...e.userTypes,...Object.fromEntries(Object.entries(e.enums).map(([n])=>[n,{internalType:"uint8"}]))};return Object.fromEntries(Object.entries(e.tables).map(([n,t])=>[`${e.namespace}_${n}`,{namespace:e.namespace,name:t.name,tableId:ut({type:t.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:t.name}),keySchema:Ie(t.keySchema,o),valueSchema:Ie(t.valueSchema,o)}]))}import{helloStoreEvent as St}from"@latticexyz/store";import{helloWorldEvent as Ct}from"@latticexyz/world";import{storeToV1 as Dt}from"@latticexyz/store/config/v2";import{worldToV1 as Tt}from"@latticexyz/world/config/v2";var T=gt("0x",{size:32}),L=parseInt("6000",16),W=z(Dt(bt)),v=z(Tt(ht)),Y=[St,Ct],D=[...wt,...xt],Be=["2.0.0","2.0.1"],Pe=["2.0.0","2.0.1"];import{waitForTransactionReceipt as jt}from"viem/actions";import{concatHex as vt,getCreate2Address as At}from"viem";import{getBytecode as kt}from"viem/actions";import{sendTransaction as It}from"@latticexyz/common";import Bt from"p-retry";import{wait as Pt}from"@latticexyz/common/utils";async function je({client:e,deployerAddress:o,bytecode:n,deployedBytecodeSize:t,label:r="contract"}){if(n.includes("__$"))throw new Error(`Found unlinked public library in ${r} bytecode`);let s=At({from:o,salt:T,bytecode:n});return await kt(e,{address:s,blockTag:"pending"})?(l("found",r,"at",s),[]):(t>L?console.warn(`
|
10
10
|
Bytecode for ${r} (${t} bytes) is over the contract size limit (${L} bytes). Run \`forge build --sizes\` for more info.
|
11
11
|
`):t>L*.95&&console.warn(`
|
12
12
|
Bytecode for ${r} (${t} bytes) is almost over the contract size limit (${L} bytes). Run \`forge build --sizes\` for more info.
|
13
|
-
`),l("deploying",r,"at",s),[await Bt(()=>It(e,{chain:e.chain??null,to:o,data:vt([T,n])}),{retries:3,onFailedAttempt:async a=>{let m=a.attemptNumber*500;l(`failed to deploy ${r}, retrying in ${m}ms...`),await Pt(m)}})])}import{uniqueBy as Ot}from"@latticexyz/common/utils";async function B({client:e,deployerAddress:o,contracts:n}){let t=Ot(n,s=>s.bytecode),r=(await Promise.all(t.map(s=>Oe({client:e,deployerAddress:o,...s})))).flat();if(r.length){l("waiting for contracts");for(let s of r)await jt(e,{hash:s})}return r}async function G(e,o){let n=H(Re.deployedBytecode.object),t=Re.bytecode.object,r=$({from:o,bytecode:t,salt:T}),s=H(Me.deployedBytecode.object),i=Me.bytecode.object,a=$({from:o,bytecode:i,salt:T}),m=H(We.deployedBytecode.object),c=We.bytecode.object,f=$({from:o,bytecode:c,salt:T}),y=H($e.deployedBytecode.object),x=$e.bytecode.object,C=$({from:o,bytecode:x,salt:T}),d=H(He.deployedBytecode.object),u=Ee({bytecode:He.bytecode.object,abi:Rt,args:[r,a,f,C]}),w=$({from:o,bytecode:u,salt:T}),h=H(Fe.deployedBytecode.object),S=Ee({bytecode:Fe.bytecode.object,abi:Mt,args:[w]}),p=$({from:o,bytecode:S,salt:T});return await B({client:e,deployerAddress:o,contracts:[{bytecode:t,deployedBytecodeSize:n,label:"access management system"},{bytecode:i,deployedBytecodeSize:s,label:"balance transfer system"},{bytecode:c,deployedBytecodeSize:m,label:"batch call system"},{bytecode:x,deployedBytecodeSize:y,label:"core registration system"},{bytecode:u,deployedBytecodeSize:d,label:"core module"},{bytecode:S,deployedBytecodeSize:h,label:"world factory"}]}),p}import Nt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as zt}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as Wt,decodeEventLog as $t,hexToString as Ne,parseAbi as Ht}from"viem";import{isDefined as Ft}from"@latticexyz/common/utils";function Z(e){let o=e.map(i=>{try{return{...i,...$t({strict:!0,abi:Ht(Y),topics:i.topics,data:i.data})}}catch(a){if(a instanceof Wt)return;throw a}}).filter(Ft),{address:n,deployBlock:t,worldVersion:r,storeVersion:s}=o.reduce((i,a)=>({...i,address:a.address,deployBlock:a.blockNumber,...a.eventName==="HelloWorld"?{worldVersion:Ne(a.args.worldVersion).replace(/\0+$/,"")}:null,...a.eventName==="HelloStore"?{storeVersion:Ne(a.args.storeVersion).replace(/\0+$/,"")}:null}),{});if(n==null)throw new Error("could not find world address");if(t==null)throw new Error("could not find world deploy block number");if(r==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:n,deployBlock:t,worldVersion:r,storeVersion:s}}async function ze(e,o,n){let t=await G(e,o);l("deploying world");let r=await zt(e,{chain:e.chain??null,address:t,abi:Nt,functionName:"deployWorld",args:[n]});l("waiting for world deploy");let s=await Et(e,{hash:r});if(s.status!=="success")throw console.error("world deploy failed",s),new Error("world deploy failed");let i=Z(s.logs);return l("deployed world to",i.address,"at block",i.deployBlock),{...i,stateBlock:i.deployBlock}}import{resourceToLabel as de,writeContract as qt}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as Yt,keySchemaToHex as Gt,valueSchemaToHex as Zt}from"@latticexyz/protocol-parser/internal";import{parseAbiItem as Lt,decodeAbiParameters as Le,parseAbiParameters as Ve}from"viem";import{hexToResource as Vt}from"@latticexyz/common";import{storeSetRecordEvent as Ut}from"@latticexyz/store";import{getLogs as _t}from"viem/actions";import{decodeKey as Kt,decodeValueArgs as Jt,hexToSchema as Ue}from"@latticexyz/protocol-parser/internal";async function _e({client:e,worldDeploy:o}){l("looking up tables for",o.address);let t=(await _t(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Lt(Ut),args:{tableId:W.store_Tables.tableId}})).map(r=>{let{tableId:s}=Kt(W.store_Tables.keySchema,r.args.keyTuple),{namespace:i,name:a}=Vt(s),m=Jt(W.store_Tables.valueSchema,r.args),c=Ue(m.keySchema),f=Ue(m.valueSchema),y=Le(Ve("string[]"),m.abiEncodedKeyNames)[0],x=Le(Ve("string[]"),m.abiEncodedFieldNames)[0],C=[...f.staticFields,...f.dynamicFields],d=Object.fromEntries(c.staticFields.map((w,h)=>[y[h],w])),u=Object.fromEntries(C.map((w,h)=>[x[h],w]));return{namespace:i,name:a,tableId:s,keySchema:d,valueSchema:u}});return l("found",t.length,"tables for",o.address),t}import Qt from"p-retry";import{wait as Xt}from"@latticexyz/common/utils";async function Ke({client:e,worldDeploy:o,tables:n}){let r=(await _e({client:e,worldDeploy:o})).map(a=>a.tableId),s=n.filter(a=>r.includes(a.tableId));s.length&&l("existing tables",s.map(de).join(", "));let i=n.filter(a=>!r.includes(a.tableId));return i.length?(l("registering tables",i.map(de).join(", ")),await Promise.all(i.map(a=>Qt(()=>qt(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerTable",args:[a.tableId,Yt(a.valueSchema),Gt(a.keySchema),Zt(a.valueSchema),Object.keys(a.keySchema),Object.keys(a.valueSchema)]}),{retries:3,onFailedAttempt:async m=>{let c=m.attemptNumber*500;l(`failed to register table ${de(a)}, retrying in ${c}ms...`),await Xt(c)}})))):[]}import{getAddress as j}from"viem";import{writeContract as ce,resourceToLabel as V}from"@latticexyz/common";import{parseAbiItem as er}from"viem";import{getLogs as or}from"viem/actions";import{storeSpliceStaticDataEvent as tr}from"@latticexyz/store";async function Q({client:e,worldDeploy:o}){l("looking up resource IDs for",o.address);let t=(await or(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:er(tr),args:{tableId:W.store_ResourceIds.tableId}})).map(r=>r.args.keyTuple[0]);return l("found",t.length,"resource IDs for",o.address),t}import{hexToResource as br,resourceToLabel as hr}from"@latticexyz/common";import{decodeValueArgs as rr,encodeKey as nr}from"@latticexyz/protocol-parser/internal";import{readContract as sr}from"viem/actions";async function P({client:e,worldDeploy:o,table:n,key:t}){let[r,s,i]=await sr(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[n.tableId,nr(n.keySchema,t)]});return rr(n.valueSchema,{staticData:r,encodedLengths:s,dynamicData:i})}import{toFunctionSelector as ar,parseAbiItem as ir}from"viem";import{storeSetRecordEvent as dr}from"@latticexyz/store";import{getLogs as cr}from"viem/actions";import{decodeValueArgs as lr}from"@latticexyz/protocol-parser/internal";import{hexToResource as mr}from"@latticexyz/common";async function X({client:e,worldDeploy:o}){l("looking up function signatures for",o.address);let t=(await cr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:ir(dr),args:{tableId:v.world_FunctionSignatures.tableId}})).map(s=>lr(v.world_FunctionSignatures.valueSchema,s.args).functionSignature);return l("found",t.length,"function signatures for",o.address),await Promise.all(t.map(async s=>{let i=ar(s),{systemId:a,systemFunctionSelector:m}=await P({client:e,worldDeploy:o,table:v.world_FunctionSelectors,key:{worldFunctionSelector:i}}),{namespace:c,name:f}=mr(a),y=c===""?s:s.replace(`${c}_${f}_`,"");return{signature:s,selector:i,systemId:a,systemFunctionSignature:y,systemFunctionSelector:m}}))}import{parseAbiItem as pr,getAddress as fr}from"viem";import{storeSpliceStaticDataEvent as yr}from"@latticexyz/store";import{getLogs as ur}from"viem/actions";import{decodeKey as gr}from"@latticexyz/protocol-parser/internal";async function ee({client:e,worldDeploy:o}){l("looking up resource access for",o.address);let t=(await ur(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:pr(yr),args:{tableId:v.world_ResourceAccess.tableId}})).map(s=>gr(v.world_ResourceAccess.keySchema,s.args.keyTuple)),r=(await Promise.all(t.map(async s=>[s,await P({client:e,worldDeploy:o,table:v.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:fr(s.caller)}));return l("found",r.length,"resource<>address access pairs"),r}async function Je({client:e,worldDeploy:o}){let[n,t,r]=await Promise.all([Q({client:e,worldDeploy:o}),X({client:e,worldDeploy:o}),ee({client:e,worldDeploy:o})]),s=n.map(br).filter(i=>i.type==="system");return l("looking up systems",s.map(hr).join(", ")),await Promise.all(s.map(async i=>{let{system:a,publicAccess:m}=await P({client:e,worldDeploy:o,table:v.world_Systems,key:{systemId:i.resourceId}}),c=t.filter(f=>f.systemId===i.resourceId);return{address:a,namespace:i.namespace,name:i.name,systemId:i.resourceId,allowAll:m,allowedAddresses:r.filter(({resourceId:f})=>f===i.resourceId).map(({address:f})=>f),functions:c}}))}import{wait as le}from"@latticexyz/common/utils";import me from"p-retry";async function qe({client:e,deployerAddress:o,libraries:n,worldDeploy:t,systems:r}){let[s,i]=await Promise.all([Je({client:e,worldDeploy:t}),ee({client:e,worldDeploy:t})]),a=r.filter(p=>s.some(g=>g.systemId===p.systemId&&j(g.address)===j(p.prepareDeploy(o,n).address)));a.length&&l("existing systems",a.map(V).join(", "));let m=a.map(p=>p.systemId),c=r.filter(p=>!m.includes(p.systemId));if(!c.length)return[];let f=c.filter(p=>s.some(g=>g.systemId===p.systemId&&j(g.address)!==j(p.prepareDeploy(o,n).address)));f.length&&l("upgrading systems",f.map(V).join(", "));let y=c.filter(p=>!s.some(g=>g.systemId===p.systemId));y.length&&l("registering new systems",y.map(V).join(", ")),await B({client:e,deployerAddress:o,contracts:c.map(p=>({bytecode:p.prepareDeploy(o,n).bytecode,deployedBytecodeSize:p.deployedBytecodeSize,label:`${V(p)} system`}))});let x=await Promise.all(c.map(p=>me(()=>ce(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"registerSystem",args:[p.systemId,p.prepareDeploy(o,n).address,p.allowAll]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;l(`failed to register system ${V(p)}, retrying in ${b}ms...`),await le(b)}}))),C=r.map(p=>p.systemId),d=i.filter(({resourceId:p})=>C.includes(p)),u=[...r.flatMap(p=>p.allowedAddresses.map(g=>({resourceId:p.systemId,address:g}))),...r.flatMap(p=>p.allowedSystemIds.map(g=>({resourceId:p.systemId,address:s.find(b=>b.systemId===g)?.address??r.find(b=>b.systemId===g)?.prepareDeploy(o,n).address})).filter(g=>g.address!=null))],w=u.filter(p=>!d.some(({resourceId:g,address:b})=>g===p.resourceId&&j(b)===j(p.address))),h=d.filter(p=>!u.some(({resourceId:g,address:b})=>g===p.resourceId&&j(b)===j(p.address)));h.length&&l("revoking",h.length,"access grants"),w.length&&l("adding",w.length,"access grants");let S=await Promise.all([...h.map(p=>me(()=>ce(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"revokeAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;l(`failed to revoke access, retrying in ${b}ms...`),await le(b)}})),...w.map(p=>me(()=>ce(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"grantAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;l(`failed to grant access, retrying in ${b}ms...`),await le(b)}}))]);return[...x,...S]}import{waitForTransactionReceipt as io}from"viem/actions";import{getAddress as wr,parseAbi as xr}from"viem";import{getBlockNumber as Sr,getLogs as Cr}from"viem/actions";var Ye=new Map;async function Ge(e,o){let n=wr(o),t=Ye.get(n);if(t!=null)return t;l("looking up world deploy for",n);let r=await Sr(e),s=await Cr(e,{strict:!0,address:n,events:xr(Y),fromBlock:"earliest",toBlock:r});return t={...Z(s),stateBlock:r},Ye.set(n,t),l("found world deploy for",n,"at block",t.deployBlock),t}import{hexToResource as Dr,writeContract as Ze}from"@latticexyz/common";import Qe from"p-retry";import{wait as Xe}from"@latticexyz/common/utils";async function eo({client:e,worldDeploy:o,functions:n}){let t=await X({client:e,worldDeploy:o}),r=Object.fromEntries(t.map(a=>[a.selector,a])),s=n.filter(a=>r[a.selector]),i=n.filter(a=>!s.includes(a));if(s.length){l("functions already registered:",s.map(m=>m.signature).join(", "));let a=s.filter(m=>m.systemId!==r[m.selector]?.systemId);a.length&&console.warn("found",a.length,"functions already registered but pointing at a different system ID:",a.map(m=>m.signature).join(", "))}return i.length?(l("registering functions:",i.map(a=>a.signature).join(", ")),Promise.all(i.map(a=>{let{namespace:m}=Dr(a.systemId);return m===""?Qe(()=>Ze(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerRootFunctionSelector",args:[a.systemId,a.systemFunctionSignature,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async c=>{let f=c.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${f}ms...`),await Xe(f)}}):Qe(()=>Ze(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerFunctionSelector",args:[a.systemId,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async c=>{let f=c.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${f}ms...`),await Xe(f)}})}))):[]}import{BaseError as Tr}from"viem";import{writeContract as oo}from"@latticexyz/common";import{isDefined as vr,wait as Ar}from"@latticexyz/common/utils";import kr from"p-retry";async function to({client:e,deployerAddress:o,libraries:n,worldDeploy:t,modules:r}){return r.length?(await B({client:e,deployerAddress:o,contracts:r.map(s=>({bytecode:s.prepareDeploy(o,n).bytecode,deployedBytecodeSize:s.deployedBytecodeSize,label:`${s.name} module`}))}),l("installing modules:",r.map(s=>s.name).join(", ")),(await Promise.all(r.map(s=>kr(async()=>{try{let i=s.prepareDeploy(o,n).address;return s.installAsRoot?await oo(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"installRootModule",args:[i,s.installData]}):await oo(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"installModule",args:[i,s.installData]})}catch(i){if(i instanceof Tr&&i.message.includes("Module_AlreadyInstalled")){l(`module ${s.name} already installed`);return}throw i}},{retries:3,onFailedAttempt:async i=>{let a=i.attemptNumber*500;l(`failed to install module ${s.name}, retrying in ${a}ms...`),await Ar(a)}})))).filter(vr)):[]}import{getAddress as ro}from"viem";import{hexToResource as no,resourceToHex as so,writeContract as Ir}from"@latticexyz/common";async function ao({client:e,worldDeploy:o,resourceIds:n}){let t=Array.from(new Set(n.map(y=>no(y).namespace))),r=await Q({client:e,worldDeploy:o}),s=new Set(r.map(y=>no(y).namespace));s.size&&l("found",s.size,"existing namespaces:",Array.from(s).map(y=>y===""?"<root>":y).join(", "));let i=t.filter(y=>s.has(y)),m=(await Promise.all(i.map(async y=>{let{owner:x}=await P({client:e,worldDeploy:o,table:v.world_NamespaceOwner,key:{namespaceId:so({type:"namespace",namespace:y,name:""})}});return[y,x]}))).filter(([,y])=>ro(y)!==ro(e.account.address)).map(([y])=>y);if(m.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${m.join(", ")}`);let c=t.filter(y=>!s.has(y));return c.length>0&&l("registering namespaces",Array.from(c).join(", ")),Promise.all(c.map(y=>Ir(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerNamespace",args:[so({namespace:y,type:"namespace",name:""})]})))}import{resourceToLabel as Br}from"@latticexyz/common";import{randomBytes as Pr}from"crypto";async function co({client:e,config:o,salt:n,worldAddress:t,deployerAddress:r}){let s=Object.values(o.tables),i=r??await Ie(e);await G(e,i),await B({client:e,deployerAddress:i,contracts:[...o.libraries.map(d=>({bytecode:d.prepareDeploy(i,o.libraries).bytecode,deployedBytecodeSize:d.deployedBytecodeSize,label:`${d.path}:${d.name} library`})),...o.systems.map(d=>({bytecode:d.prepareDeploy(i,o.libraries).bytecode,deployedBytecodeSize:d.deployedBytecodeSize,label:`${Br(d)} system`})),...o.modules.map(d=>({bytecode:d.prepareDeploy(i,o.libraries).bytecode,deployedBytecodeSize:d.deployedBytecodeSize,label:`${d.name} module`}))]});let a=t?await Ge(e,t):await ze(e,i,n??`0x${Pr(32).toString("hex")}`);if(!Pe.includes(a.storeVersion))throw new Error(`Unsupported Store version: ${a.storeVersion}`);if(!je.includes(a.worldVersion))throw new Error(`Unsupported World version: ${a.worldVersion}`);let m=await ao({client:e,worldDeploy:a,resourceIds:[...s.map(d=>d.tableId),...o.systems.map(d=>d.systemId)]});l("waiting for all namespace registration transactions to confirm");for(let d of m)await io(e,{hash:d});let c=await Ke({client:e,worldDeploy:a,tables:s}),f=await qe({client:e,deployerAddress:i,libraries:o.libraries,worldDeploy:a,systems:o.systems}),y=await eo({client:e,worldDeploy:a,functions:o.systems.flatMap(d=>d.functions)}),x=await to({client:e,deployerAddress:i,libraries:o.libraries,worldDeploy:a,modules:o.modules}),C=[...c,...f,...y,...x];l("waiting for all transactions to confirm");for(let d of C)await io(e,{hash:d});return l("deploy complete"),a}import{createWalletClient as en,http as on,isHex as tn}from"viem";import{privateKeyToAccount as rn}from"viem/accounts";import{loadConfig as nn}from"@latticexyz/config/node";import{worldToV1 as sn}from"@latticexyz/world/config/v2";import{getOutDirectory as an,getRpcUrl as dn,getSrcDirectory as cn}from"@latticexyz/common/foundry";import F from"chalk";import{MUDError as bo}from"@latticexyz/common/errors";import Er from"path";import{resolveWorldConfig as Nr}from"@latticexyz/world/internal";import{resourceToHex as pe}from"@latticexyz/common";import{resolveWithContext as zr}from"@latticexyz/config/library";import{encodeField as Lr}from"@latticexyz/protocol-parser/internal";import{hexToBytes as Vr,bytesToHex as Ur,toFunctionSelector as fo,toFunctionSignature as yo}from"viem";import oe from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import te from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import re from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};import ne from"@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json"assert{type:"json"};import{size as se}from"viem";function M(e){return Object.entries(e).flatMap(([o,n])=>Object.entries(n).flatMap(([t,r])=>r.map(s=>({path:o,name:t,start:s.start,length:s.length}))))}var lo=[{name:"KeysWithValueModule",abi:oe.abi,bytecode:oe.bytecode.object,placeholders:M(oe.bytecode.linkReferences),deployedBytecodeSize:se(oe.deployedBytecode.object)},{name:"KeysInTableModule",abi:te.abi,bytecode:te.bytecode.object,placeholders:M(te.bytecode.linkReferences),deployedBytecodeSize:se(te.deployedBytecode.object)},{name:"UniqueEntityModule",abi:re.abi,bytecode:re.bytecode.object,placeholders:M(re.bytecode.linkReferences),deployedBytecodeSize:se(re.deployedBytecode.object)},{name:"Unstable_CallWithSignatureModule",abi:ne.abi,bytecode:ne.bytecode.object,placeholders:M(ne.bytecode.linkReferences),deployedBytecodeSize:se(ne.deployedBytecode.object)}];import{readFileSync as jr}from"fs";import Or from"path";import{MUDError as ae}from"@latticexyz/common/errors";import{size as Rr}from"viem";function U(e,o,n){let t,r=Or.join(n,e,o+".json");try{t=JSON.parse(jr(r,"utf8"))}catch{throw new ae(`Error reading file at ${r}`)}let s=t?.bytecode?.object;if(!s)throw new ae(`No bytecode found in ${r}`);let i=t?.deployedBytecode?.object;if(!i)throw new ae(`No deployed bytecode found in ${r}`);let a=t?.abi;if(!a)throw new ae(`No ABI found in ${r}`);let m=M(t?.bytecode?.linkReferences??{});return{abi:a,bytecode:s,placeholders:m,deployedBytecodeSize:Rr(i)}}import{groupBy as _r}from"@latticexyz/common/utils";import{readFileSync as Wr}from"fs";import $r from"glob";import Mr from"toposort";function mo(e,o,n){let t=Mr(e.flatMap(r=>n(r).map(s=>[o(r),s])));return[...e].sort((r,s)=>t.indexOf(o(r))-t.indexOf(o(s)))}function po(e){let n=$r.sync(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).map(t=>JSON.parse(Wr(t,"utf8"))).flatMap(t=>{if(!t.metadata)return[];let r=Object.keys(t.metadata.settings.compilationTarget)[0],s=t.metadata.settings.compilationTarget[r],i=t.bytecode.linkReferences;return Object.entries(i).flatMap(([a,m])=>Object.keys(m).map(c=>({path:a,name:c,dependentPath:r,dependentName:s})))});return mo(n,t=>`${t.path}:${t.name}`,t=>[`${t.dependentPath}:${t.dependentName}`])}import{spliceHex as Hr}from"@latticexyz/common";import{getCreate2Address as Fr}from"viem";function ie(e,o){return function(t,r){let s=e;for(let i of o){let a=r.find(m=>m.path===i.path&&m.name===i.name);if(!a)throw new Error(`Could not find library for bytecode placeholder ${i.path}:${i.name}`);s=Hr(s,i.start,i.length,a.prepareDeploy(t,r).address)}return{bytecode:s,address:Fr({from:t,bytecode:s,salt:T})}}}function uo({config:e,forgeSourceDir:o,forgeOutDir:n}){let t=po(n).map(d=>{let u=U(Er.basename(d.path),d.name,n);return{path:d.path,name:d.name,abi:u.abi,prepareDeploy:ie(u.bytecode,u.placeholders),deployedBytecodeSize:u.deployedBytecodeSize}}),r=z(e),s=I(o).map(({basename:d})=>d),i=Nr(e,s),m=U("System.sol","System",n).abi.filter(d=>d.type==="function").map(yo),c=Object.entries(i.systems).map(([d,u])=>{let w=e.namespace,h=u.name,S=pe({type:"system",namespace:w,name:h}),p=U(`${d}.sol`,d,n),g=p.abi.filter(b=>b.type==="function").map(yo).filter(b=>!m.includes(b)).map(b=>{let be=w===""?b:`${w}__${b}`;return{signature:be,selector:fo(be),systemId:S,systemFunctionSignature:b,systemFunctionSelector:fo(b)}});return{namespace:w,name:h,systemId:S,allowAll:u.openAccess,allowedAddresses:u.accessListAddresses,allowedSystemIds:u.accessListSystems.map(b=>pe({type:"system",namespace:w,name:i.systems[b].name})),prepareDeploy:ie(p.bytecode,p.placeholders),deployedBytecodeSize:p.deployedBytecodeSize,abi:p.abi,functions:g}}),f=_r(c,d=>d.systemId),y=Array.from(f.values()).filter(d=>d.length>1).flat();if(y.length){let d=y.map(u=>u.name);throw new Error(`Found systems with overlapping system ID: ${d.join(", ")}.
|
13
|
+
`),l("deploying",r,"at",s),[await Bt(()=>It(e,{chain:e.chain??null,to:o,data:vt([T,n])}),{retries:3,onFailedAttempt:async a=>{let m=a.attemptNumber*500;l(`failed to deploy ${r}, retrying in ${m}ms...`),await Pt(m)}})])}import{uniqueBy as Ot}from"@latticexyz/common/utils";async function B({client:e,deployerAddress:o,contracts:n}){let t=Ot(n,s=>s.bytecode),r=(await Promise.all(t.map(s=>je({client:e,deployerAddress:o,...s})))).flat();if(r.length){l("waiting for contracts");for(let s of r)await jt(e,{hash:s})}return r}async function G(e,o){let n=H(Oe.deployedBytecode.object),t=Oe.bytecode.object,r=$({from:o,bytecode:t,salt:T}),s=H(Re.deployedBytecode.object),i=Re.bytecode.object,a=$({from:o,bytecode:i,salt:T}),m=H(Me.deployedBytecode.object),c=Me.bytecode.object,f=$({from:o,bytecode:c,salt:T}),y=H(We.deployedBytecode.object),x=We.bytecode.object,C=$({from:o,bytecode:x,salt:T}),d=H($e.deployedBytecode.object),u=Fe({bytecode:$e.bytecode.object,abi:Rt,args:[r,a,f,C]}),w=$({from:o,bytecode:u,salt:T}),h=H(He.deployedBytecode.object),S=Fe({bytecode:He.bytecode.object,abi:Mt,args:[w]}),p=$({from:o,bytecode:S,salt:T});return await B({client:e,deployerAddress:o,contracts:[{bytecode:t,deployedBytecodeSize:n,label:"access management system"},{bytecode:i,deployedBytecodeSize:s,label:"balance transfer system"},{bytecode:c,deployedBytecodeSize:m,label:"batch call system"},{bytecode:x,deployedBytecodeSize:y,label:"core registration system"},{bytecode:u,deployedBytecodeSize:d,label:"core module"},{bytecode:S,deployedBytecodeSize:h,label:"world factory"}]}),p}import Nt from"@latticexyz/world/out/WorldFactory.sol/WorldFactory.abi.json"assert{type:"json"};import{writeContract as zt}from"@latticexyz/common";import{AbiEventSignatureNotFoundError as Wt,decodeEventLog as $t,hexToString as Ee,parseAbi as Ht}from"viem";import{isDefined as Ft}from"@latticexyz/common/utils";function Z(e){let o=e.map(i=>{try{return{...i,...$t({strict:!0,abi:Ht(Y),topics:i.topics,data:i.data})}}catch(a){if(a instanceof Wt)return;throw a}}).filter(Ft),{address:n,deployBlock:t,worldVersion:r,storeVersion:s}=o.reduce((i,a)=>({...i,address:a.address,deployBlock:a.blockNumber,...a.eventName==="HelloWorld"?{worldVersion:Ee(a.args.worldVersion).replace(/\0+$/,"")}:null,...a.eventName==="HelloStore"?{storeVersion:Ee(a.args.storeVersion).replace(/\0+$/,"")}:null}),{});if(n==null)throw new Error("could not find world address");if(t==null)throw new Error("could not find world deploy block number");if(r==null)throw new Error("could not find world version");if(s==null)throw new Error("could not find store version");return{address:n,deployBlock:t,worldVersion:r,storeVersion:s}}async function Ne(e,o,n){let t=await G(e,o);l("deploying world");let r=await zt(e,{chain:e.chain??null,address:t,abi:Nt,functionName:"deployWorld",args:[n]});l("waiting for world deploy");let s=await Et(e,{hash:r});if(s.status!=="success")throw console.error("world deploy failed",s),new Error("world deploy failed");let i=Z(s.logs);return l("deployed world to",i.address,"at block",i.deployBlock),{...i,stateBlock:i.deployBlock}}import{resourceToLabel as de,writeContract as qt}from"@latticexyz/common";import{valueSchemaToFieldLayoutHex as Yt,keySchemaToHex as Gt,valueSchemaToHex as Zt}from"@latticexyz/protocol-parser/internal";import{parseAbiItem as Lt,decodeAbiParameters as ze,parseAbiParameters as Le}from"viem";import{hexToResource as Vt}from"@latticexyz/common";import{storeSetRecordEvent as Ut}from"@latticexyz/store";import{getLogs as _t}from"viem/actions";import{decodeKey as Kt,decodeValueArgs as Jt,hexToSchema as Ve}from"@latticexyz/protocol-parser/internal";async function Ue({client:e,worldDeploy:o}){l("looking up tables for",o.address);let t=(await _t(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:Lt(Ut),args:{tableId:W.store_Tables.tableId}})).map(r=>{let{tableId:s}=Kt(W.store_Tables.keySchema,r.args.keyTuple),{namespace:i,name:a}=Vt(s),m=Jt(W.store_Tables.valueSchema,r.args),c=Ve(m.keySchema),f=Ve(m.valueSchema),y=ze(Le("string[]"),m.abiEncodedKeyNames)[0],x=ze(Le("string[]"),m.abiEncodedFieldNames)[0],C=[...f.staticFields,...f.dynamicFields],d=Object.fromEntries(c.staticFields.map((w,h)=>[y[h],w])),u=Object.fromEntries(C.map((w,h)=>[x[h],w]));return{namespace:i,name:a,tableId:s,keySchema:d,valueSchema:u}});return l("found",t.length,"tables for",o.address),t}import Qt from"p-retry";import{wait as Xt}from"@latticexyz/common/utils";async function _e({client:e,worldDeploy:o,tables:n}){let r=(await Ue({client:e,worldDeploy:o})).map(a=>a.tableId),s=n.filter(a=>r.includes(a.tableId));s.length&&l("existing tables",s.map(de).join(", "));let i=n.filter(a=>!r.includes(a.tableId));return i.length?(l("registering tables",i.map(de).join(", ")),await Promise.all(i.map(a=>Qt(()=>qt(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerTable",args:[a.tableId,Yt(a.valueSchema),Gt(a.keySchema),Zt(a.valueSchema),Object.keys(a.keySchema),Object.keys(a.valueSchema)]}),{retries:3,onFailedAttempt:async m=>{let c=m.attemptNumber*500;l(`failed to register table ${de(a)}, retrying in ${c}ms...`),await Xt(c)}})))):[]}import{getAddress as j}from"viem";import{writeContract as ce,resourceToLabel as V}from"@latticexyz/common";import{parseAbiItem as er}from"viem";import{getLogs as or}from"viem/actions";import{storeSpliceStaticDataEvent as tr}from"@latticexyz/store";async function Q({client:e,worldDeploy:o}){l("looking up resource IDs for",o.address);let t=(await or(e,{strict:!0,address:o.address,fromBlock:o.deployBlock,toBlock:o.stateBlock,event:er(tr),args:{tableId:W.store_ResourceIds.tableId}})).map(r=>r.args.keyTuple[0]);return l("found",t.length,"resource IDs for",o.address),t}import{hexToResource as br,resourceToLabel as hr}from"@latticexyz/common";import{decodeValueArgs as rr,encodeKey as nr}from"@latticexyz/protocol-parser/internal";import{readContract as sr}from"viem/actions";async function P({client:e,worldDeploy:o,table:n,key:t}){let[r,s,i]=await sr(e,{blockNumber:o.stateBlock,address:o.address,abi:D,functionName:"getRecord",args:[n.tableId,nr(n.keySchema,t)]});return rr(n.valueSchema,{staticData:r,encodedLengths:s,dynamicData:i})}import{toFunctionSelector as ar,parseAbiItem as ir}from"viem";import{storeSetRecordEvent as dr}from"@latticexyz/store";import{getLogs as cr}from"viem/actions";import{decodeValueArgs as lr}from"@latticexyz/protocol-parser/internal";import{hexToResource as mr}from"@latticexyz/common";async function X({client:e,worldDeploy:o}){l("looking up function signatures for",o.address);let t=(await cr(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:ir(dr),args:{tableId:v.world_FunctionSignatures.tableId}})).map(s=>lr(v.world_FunctionSignatures.valueSchema,s.args).functionSignature);return l("found",t.length,"function signatures for",o.address),await Promise.all(t.map(async s=>{let i=ar(s),{systemId:a,systemFunctionSelector:m}=await P({client:e,worldDeploy:o,table:v.world_FunctionSelectors,key:{worldFunctionSelector:i}}),{namespace:c,name:f}=mr(a),y=c===""?s:s.replace(`${c}_${f}_`,"");return{signature:s,selector:i,systemId:a,systemFunctionSignature:y,systemFunctionSelector:m}}))}import{parseAbiItem as pr,getAddress as fr}from"viem";import{storeSpliceStaticDataEvent as yr}from"@latticexyz/store";import{getLogs as ur}from"viem/actions";import{decodeKey as gr}from"@latticexyz/protocol-parser/internal";async function ee({client:e,worldDeploy:o}){l("looking up resource access for",o.address);let t=(await ur(e,{strict:!0,fromBlock:o.deployBlock,toBlock:o.stateBlock,address:o.address,event:pr(yr),args:{tableId:v.world_ResourceAccess.tableId}})).map(s=>gr(v.world_ResourceAccess.keySchema,s.args.keyTuple)),r=(await Promise.all(t.map(async s=>[s,await P({client:e,worldDeploy:o,table:v.world_ResourceAccess,key:s})]))).filter(([,s])=>s.access).map(([s])=>({resourceId:s.resourceId,address:fr(s.caller)}));return l("found",r.length,"resource<>address access pairs"),r}async function Ke({client:e,worldDeploy:o}){let[n,t,r]=await Promise.all([Q({client:e,worldDeploy:o}),X({client:e,worldDeploy:o}),ee({client:e,worldDeploy:o})]),s=n.map(br).filter(i=>i.type==="system");return l("looking up systems",s.map(hr).join(", ")),await Promise.all(s.map(async i=>{let{system:a,publicAccess:m}=await P({client:e,worldDeploy:o,table:v.world_Systems,key:{systemId:i.resourceId}}),c=t.filter(f=>f.systemId===i.resourceId);return{address:a,namespace:i.namespace,name:i.name,systemId:i.resourceId,allowAll:m,allowedAddresses:r.filter(({resourceId:f})=>f===i.resourceId).map(({address:f})=>f),functions:c}}))}import{wait as le}from"@latticexyz/common/utils";import me from"p-retry";async function Je({client:e,deployerAddress:o,libraries:n,worldDeploy:t,systems:r}){let[s,i]=await Promise.all([Ke({client:e,worldDeploy:t}),ee({client:e,worldDeploy:t})]),a=r.filter(p=>s.some(g=>g.systemId===p.systemId&&j(g.address)===j(p.prepareDeploy(o,n).address)));a.length&&l("existing systems",a.map(V).join(", "));let m=a.map(p=>p.systemId),c=r.filter(p=>!m.includes(p.systemId));if(!c.length)return[];let f=c.filter(p=>s.some(g=>g.systemId===p.systemId&&j(g.address)!==j(p.prepareDeploy(o,n).address)));f.length&&l("upgrading systems",f.map(V).join(", "));let y=c.filter(p=>!s.some(g=>g.systemId===p.systemId));y.length&&l("registering new systems",y.map(V).join(", ")),await B({client:e,deployerAddress:o,contracts:c.map(p=>({bytecode:p.prepareDeploy(o,n).bytecode,deployedBytecodeSize:p.deployedBytecodeSize,label:`${V(p)} system`}))});let x=await Promise.all(c.map(p=>me(()=>ce(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"registerSystem",args:[p.systemId,p.prepareDeploy(o,n).address,p.allowAll]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;l(`failed to register system ${V(p)}, retrying in ${b}ms...`),await le(b)}}))),C=r.map(p=>p.systemId),d=i.filter(({resourceId:p})=>C.includes(p)),u=[...r.flatMap(p=>p.allowedAddresses.map(g=>({resourceId:p.systemId,address:g}))),...r.flatMap(p=>p.allowedSystemIds.map(g=>({resourceId:p.systemId,address:s.find(b=>b.systemId===g)?.address??r.find(b=>b.systemId===g)?.prepareDeploy(o,n).address})).filter(g=>g.address!=null))],w=u.filter(p=>!d.some(({resourceId:g,address:b})=>g===p.resourceId&&j(b)===j(p.address))),h=d.filter(p=>!u.some(({resourceId:g,address:b})=>g===p.resourceId&&j(b)===j(p.address)));h.length&&l("revoking",h.length,"access grants"),w.length&&l("adding",w.length,"access grants");let S=await Promise.all([...h.map(p=>me(()=>ce(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"revokeAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;l(`failed to revoke access, retrying in ${b}ms...`),await le(b)}})),...w.map(p=>me(()=>ce(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"grantAccess",args:[p.resourceId,p.address]}),{retries:3,onFailedAttempt:async g=>{let b=g.attemptNumber*500;l(`failed to grant access, retrying in ${b}ms...`),await le(b)}}))]);return[...x,...S]}import{waitForTransactionReceipt as ao}from"viem/actions";import{getAddress as wr,parseAbi as xr}from"viem";import{getBlockNumber as Sr,getLogs as Cr}from"viem/actions";var qe=new Map;async function Ye(e,o){let n=wr(o),t=qe.get(n);if(t!=null)return t;l("looking up world deploy for",n);let r=await Sr(e),s=await Cr(e,{strict:!0,address:n,events:xr(Y),fromBlock:"earliest",toBlock:r});return t={...Z(s),stateBlock:r},qe.set(n,t),l("found world deploy for",n,"at block",t.deployBlock),t}import{hexToResource as Dr,writeContract as Ge}from"@latticexyz/common";import Ze from"p-retry";import{wait as Qe}from"@latticexyz/common/utils";async function Xe({client:e,worldDeploy:o,functions:n}){let t=await X({client:e,worldDeploy:o}),r=Object.fromEntries(t.map(a=>[a.selector,a])),s=n.filter(a=>r[a.selector]),i=n.filter(a=>!s.includes(a));if(s.length){l("functions already registered:",s.map(m=>m.signature).join(", "));let a=s.filter(m=>m.systemId!==r[m.selector]?.systemId);a.length&&console.warn("found",a.length,"functions already registered but pointing at a different system ID:",a.map(m=>m.signature).join(", "))}return i.length?(l("registering functions:",i.map(a=>a.signature).join(", ")),Promise.all(i.map(a=>{let{namespace:m}=Dr(a.systemId);return m===""?Ze(()=>Ge(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerRootFunctionSelector",args:[a.systemId,a.systemFunctionSignature,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async c=>{let f=c.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${f}ms...`),await Qe(f)}}):Ze(()=>Ge(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerFunctionSelector",args:[a.systemId,a.systemFunctionSignature]}),{retries:3,onFailedAttempt:async c=>{let f=c.attemptNumber*500;l(`failed to register function ${a.signature}, retrying in ${f}ms...`),await Qe(f)}})}))):[]}import{BaseError as Tr}from"viem";import{writeContract as eo}from"@latticexyz/common";import{isDefined as vr,wait as Ar}from"@latticexyz/common/utils";import kr from"p-retry";async function oo({client:e,deployerAddress:o,libraries:n,worldDeploy:t,modules:r}){return r.length?(await B({client:e,deployerAddress:o,contracts:r.map(s=>({bytecode:s.prepareDeploy(o,n).bytecode,deployedBytecodeSize:s.deployedBytecodeSize,label:`${s.name} module`}))}),l("installing modules:",r.map(s=>s.name).join(", ")),(await Promise.all(r.map(s=>kr(async()=>{try{let i=s.prepareDeploy(o,n).address;return s.installAsRoot?await eo(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"installRootModule",args:[i,s.installData]}):await eo(e,{chain:e.chain??null,address:t.address,abi:D,functionName:"installModule",args:[i,s.installData]})}catch(i){if(i instanceof Tr&&i.message.includes("Module_AlreadyInstalled")){l(`module ${s.name} already installed`);return}throw i}},{retries:3,onFailedAttempt:async i=>{let a=i.attemptNumber*500;l(`failed to install module ${s.name}, retrying in ${a}ms...`),await Ar(a)}})))).filter(vr)):[]}import{getAddress as to}from"viem";import{hexToResource as ro,resourceToHex as no,writeContract as Ir}from"@latticexyz/common";async function so({client:e,worldDeploy:o,resourceIds:n}){let t=Array.from(new Set(n.map(y=>ro(y).namespace))),r=await Q({client:e,worldDeploy:o}),s=new Set(r.map(y=>ro(y).namespace));s.size&&l("found",s.size,"existing namespaces:",Array.from(s).map(y=>y===""?"<root>":y).join(", "));let i=t.filter(y=>s.has(y)),m=(await Promise.all(i.map(async y=>{let{owner:x}=await P({client:e,worldDeploy:o,table:v.world_NamespaceOwner,key:{namespaceId:no({type:"namespace",namespace:y,name:""})}});return[y,x]}))).filter(([,y])=>to(y)!==to(e.account.address)).map(([y])=>y);if(m.length)throw new Error(`You are attempting to deploy to namespaces you do not own: ${m.join(", ")}`);let c=t.filter(y=>!s.has(y));return c.length>0&&l("registering namespaces",Array.from(c).join(", ")),Promise.all(c.map(y=>Ir(e,{chain:e.chain??null,address:o.address,abi:D,functionName:"registerNamespace",args:[no({namespace:y,type:"namespace",name:""})]})))}import{resourceToLabel as Br}from"@latticexyz/common";import{randomBytes as Pr}from"crypto";async function io({client:e,config:o,salt:n,worldAddress:t,deployerAddress:r}){let s=Object.values(o.tables),i=r??await ke(e);await G(e,i),await B({client:e,deployerAddress:i,contracts:[...o.libraries.map(d=>({bytecode:d.prepareDeploy(i,o.libraries).bytecode,deployedBytecodeSize:d.deployedBytecodeSize,label:`${d.path}:${d.name} library`})),...o.systems.map(d=>({bytecode:d.prepareDeploy(i,o.libraries).bytecode,deployedBytecodeSize:d.deployedBytecodeSize,label:`${Br(d)} system`})),...o.modules.map(d=>({bytecode:d.prepareDeploy(i,o.libraries).bytecode,deployedBytecodeSize:d.deployedBytecodeSize,label:`${d.name} module`}))]});let a=t?await Ye(e,t):await Ne(e,i,n??`0x${Pr(32).toString("hex")}`);if(!Be.includes(a.storeVersion))throw new Error(`Unsupported Store version: ${a.storeVersion}`);if(!Pe.includes(a.worldVersion))throw new Error(`Unsupported World version: ${a.worldVersion}`);let m=await so({client:e,worldDeploy:a,resourceIds:[...s.map(d=>d.tableId),...o.systems.map(d=>d.systemId)]});l("waiting for all namespace registration transactions to confirm");for(let d of m)await ao(e,{hash:d});let c=await _e({client:e,worldDeploy:a,tables:s}),f=await Je({client:e,deployerAddress:i,libraries:o.libraries,worldDeploy:a,systems:o.systems}),y=await Xe({client:e,worldDeploy:a,functions:o.systems.flatMap(d=>d.functions)}),x=await oo({client:e,deployerAddress:i,libraries:o.libraries,worldDeploy:a,modules:o.modules}),C=[...c,...f,...y,...x];l("waiting for all transactions to confirm");for(let d of C)await ao(e,{hash:d});return l("deploy complete"),a}import{createWalletClient as en,http as on,isHex as tn}from"viem";import{privateKeyToAccount as rn}from"viem/accounts";import{loadConfig as nn}from"@latticexyz/config/node";import{worldToV1 as sn}from"@latticexyz/world/config/v2";import{getOutDirectory as an,getRpcUrl as dn,getSrcDirectory as cn}from"@latticexyz/common/foundry";import F from"chalk";import{MUDError as go}from"@latticexyz/common/errors";import Er from"path";import{resolveWorldConfig as Nr}from"@latticexyz/world/internal";import{resourceToHex as pe}from"@latticexyz/common";import{resolveWithContext as zr}from"@latticexyz/config/library";import{encodeField as Lr}from"@latticexyz/protocol-parser/internal";import{hexToBytes as Vr,bytesToHex as Ur,toFunctionSelector as po,toFunctionSignature as fo}from"viem";import oe from"@latticexyz/world-modules/out/KeysWithValueModule.sol/KeysWithValueModule.json"assert{type:"json"};import te from"@latticexyz/world-modules/out/KeysInTableModule.sol/KeysInTableModule.json"assert{type:"json"};import re from"@latticexyz/world-modules/out/UniqueEntityModule.sol/UniqueEntityModule.json"assert{type:"json"};import ne from"@latticexyz/world-modules/out/Unstable_CallWithSignatureModule.sol/Unstable_CallWithSignatureModule.json"assert{type:"json"};import{size as se}from"viem";function M(e){return Object.entries(e).flatMap(([o,n])=>Object.entries(n).flatMap(([t,r])=>r.map(s=>({path:o,name:t,start:s.start,length:s.length}))))}var co=[{name:"KeysWithValueModule",abi:oe.abi,bytecode:oe.bytecode.object,placeholders:M(oe.bytecode.linkReferences),deployedBytecodeSize:se(oe.deployedBytecode.object)},{name:"KeysInTableModule",abi:te.abi,bytecode:te.bytecode.object,placeholders:M(te.bytecode.linkReferences),deployedBytecodeSize:se(te.deployedBytecode.object)},{name:"UniqueEntityModule",abi:re.abi,bytecode:re.bytecode.object,placeholders:M(re.bytecode.linkReferences),deployedBytecodeSize:se(re.deployedBytecode.object)},{name:"Unstable_CallWithSignatureModule",abi:ne.abi,bytecode:ne.bytecode.object,placeholders:M(ne.bytecode.linkReferences),deployedBytecodeSize:se(ne.deployedBytecode.object)}];import{readFileSync as jr}from"fs";import Or from"path";import{MUDError as ae}from"@latticexyz/common/errors";import{size as Rr}from"viem";function U(e,o,n){let t,r=Or.join(n,e,o+".json");try{t=JSON.parse(jr(r,"utf8"))}catch{throw new ae(`Error reading file at ${r}`)}let s=t?.bytecode?.object;if(!s)throw new ae(`No bytecode found in ${r}`);let i=t?.deployedBytecode?.object;if(!i)throw new ae(`No deployed bytecode found in ${r}`);let a=t?.abi;if(!a)throw new ae(`No ABI found in ${r}`);let m=M(t?.bytecode?.linkReferences??{});return{abi:a,bytecode:s,placeholders:m,deployedBytecodeSize:Rr(i)}}import{groupBy as _r}from"@latticexyz/common/utils";import{readFileSync as Wr}from"fs";import $r from"glob";import Mr from"toposort";function lo(e,o,n){let t=Mr(e.flatMap(r=>n(r).map(s=>[o(r),s])));return[...e].sort((r,s)=>t.indexOf(o(r))-t.indexOf(o(s)))}function mo(e){let n=$r.sync(`${e}/**/*.json`,{ignore:"**/*.abi.json"}).map(t=>JSON.parse(Wr(t,"utf8"))).flatMap(t=>{if(!t.metadata)return[];let r=Object.keys(t.metadata.settings.compilationTarget)[0],s=t.metadata.settings.compilationTarget[r],i=t.bytecode.linkReferences;return Object.entries(i).flatMap(([a,m])=>Object.keys(m).map(c=>({path:a,name:c,dependentPath:r,dependentName:s})))});return lo(n,t=>`${t.path}:${t.name}`,t=>[`${t.dependentPath}:${t.dependentName}`])}import{spliceHex as Hr}from"@latticexyz/common";import{getCreate2Address as Fr}from"viem";function ie(e,o){return function(t,r){let s=e;for(let i of o){let a=r.find(m=>m.path===i.path&&m.name===i.name);if(!a)throw new Error(`Could not find library for bytecode placeholder ${i.path}:${i.name}`);s=Hr(s,i.start,i.length,a.prepareDeploy(t,r).address)}return{bytecode:s,address:Fr({from:t,bytecode:s,salt:T})}}}function yo({config:e,forgeSourceDir:o,forgeOutDir:n}){let t=mo(n).map(d=>{let u=U(Er.basename(d.path),d.name,n);return{path:d.path,name:d.name,abi:u.abi,prepareDeploy:ie(u.bytecode,u.placeholders),deployedBytecodeSize:u.deployedBytecodeSize}}),r=z(e),s=I(o).map(({basename:d})=>d),i=Nr(e,s),m=U("System.sol","System",n).abi.filter(d=>d.type==="function").map(fo),c=Object.entries(i.systems).map(([d,u])=>{let w=e.namespace,h=u.name,S=pe({type:"system",namespace:w,name:h}),p=U(`${d}.sol`,d,n),g=p.abi.filter(b=>b.type==="function").map(fo).filter(b=>!m.includes(b)).map(b=>{let be=w===""?b:`${w}__${b}`;return{signature:be,selector:po(be),systemId:S,systemFunctionSignature:b,systemFunctionSelector:po(b)}});return{namespace:w,name:h,systemId:S,allowAll:u.openAccess,allowedAddresses:u.accessListAddresses,allowedSystemIds:u.accessListSystems.map(b=>pe({type:"system",namespace:w,name:i.systems[b].name})),prepareDeploy:ie(p.bytecode,p.placeholders),deployedBytecodeSize:p.deployedBytecodeSize,abi:p.abi,functions:g}}),f=_r(c,d=>d.systemId),y=Array.from(f.values()).filter(d=>d.length>1).flat();if(y.length){let d=y.map(u=>u.name);throw new Error(`Found systems with overlapping system ID: ${d.join(", ")}.
|
14
14
|
|
15
|
-
System IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`)}let x={tableIds:Object.fromEntries(Object.entries(e.tables).map(([d,u])=>[d,Vr(pe({type:u.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:u.name}))]))},C=e.modules.map(d=>{let u=
|
15
|
+
System IDs are generated from the first 16 bytes of the name, so you may need to rename them to avoid the overlap.`)}let x={tableIds:Object.fromEntries(Object.entries(e.tables).map(([d,u])=>[d,Vr(pe({type:u.offchainOnly?"offchainTable":"table",namespace:e.namespace,name:u.name}))]))},C=e.modules.map(d=>{let u=co.find(h=>h.name===d.name)??U(`${d.name}.sol`,d.name,n),w=d.args.map(h=>zr(h,x)).map(h=>{let S=h.value instanceof Uint8Array?Ur(h.value):h.value;return Lr(h.type,S)});if(w.length>1)throw new Error(`${d.name} module should only have 0-1 args, but had ${w.length} args.`);return{name:d.name,installAsRoot:d.root,installData:w.length===0?"0x":w[0],prepareDeploy:ie(u.bytecode,u.placeholders),deployedBytecodeSize:u.deployedBytecodeSize,abi:u.abi}});return{tables:r,systems:c,modules:C,libraries:t}}import{getChainId as ln}from"viem/actions";import{existsSync as Kr}from"fs";import Jr from"path";import qr from"chalk";import{getScriptDirectory as Yr,forge as Gr}from"@latticexyz/common/foundry";async function uo(e,o,n,t){let r=Jr.join(await Yr(),e+".s.sol");Kr(r)?(console.log(qr.blue(`Executing post deploy script at ${r}`)),await Gr(["script",e,"--sig","run(address)",o,"--broadcast","--rpc-url",n,"-vvv"],{profile:t})):console.log(`No script at ${r}, skipping post deploy hook`)}var k={configPath:{type:"string",desc:"Path to the 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"},srcDir:{type:"string",desc:"Source directory. Defaults to foundry src directory."},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."},salt:{type:"string",desc:"The deployment salt to use. Defaults to a random salt."}};async function E(e){let o=e.salt;if(o!=null&&!tn(o))throw new go("Expected hex string for salt");let n=e.profile??process.env.FOUNDRY_PROFILE,t=await nn(e.configPath),r=sn(t);e.printConfig&&console.log(F.green(`
|
16
16
|
Resolved config:
|
17
17
|
`),JSON.stringify(r,null,2));let s=e.srcDir??await cn(n),i=await an(n),a=e.rpc??await dn(n);console.log(F.bgBlue(F.whiteBright(`
|
18
18
|
Deploying MUD contracts${n?" with profile "+n:""} to RPC ${a}
|
19
|
-
`))),e.skipBuild||await J({config:t,srcDir:s,foundryProfile:n});let m=process.env.PRIVATE_KEY;if(!m)throw new
|
19
|
+
`))),e.skipBuild||await J({config:t,srcDir:s,foundryProfile:n});let m=process.env.PRIVATE_KEY;if(!m)throw new go(`Missing PRIVATE_KEY environment variable.
|
20
20
|
Run 'echo "PRIVATE_KEY=0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" > .env'
|
21
|
-
in your contracts directory to use the default anvil private key.`);let c=
|
21
|
+
in your contracts directory to use the default anvil private key.`);let c=yo({config:r,forgeSourceDir:s,forgeOutDir:i}),f=en({transport:on(a,{batch:e.rpcBatch?{batchSize:100,wait:1e3}:void 0}),account:rn(m)});console.log("Deploying from",f.account.address);let y=Date.now(),x=await io({deployerAddress:e.deployerAddress,salt:o,worldAddress:e.worldAddress,client:f,config:c});(e.worldAddress==null||e.alwaysRunPostDeploy)&&await uo(r.postDeployScript,x.address,a,n),console.log(F.green("Deployment completed in",(Date.now()-y)/1e3,"seconds"));let C={worldAddress:x.address,blockNumber:Number(x.deployBlock)};if(e.saveDeployment){let d=await ln(f),u=fe.join(r.deploysDirectory,d.toString());Qr(u,{recursive:!0}),ye(fe.join(u,"latest.json"),JSON.stringify(C,null,2)),ye(fe.join(u,Date.now()+".json"),JSON.stringify(C,null,2));let w=[1337,31337],h=Zr(r.worldsFile)?JSON.parse(Xr(r.worldsFile,"utf-8")):{};h[d]={address:C.worldAddress,blockNumber:w.includes(d)?void 0:C.blockNumber},ye(r.worldsFile,JSON.stringify(h,null,2)),console.log(F.bgGreen(F.whiteBright(`
|
22
22
|
Deployment result (written to ${r.worldsFile} and ${u}):
|
23
|
-
`)))}return console.log(C),x}var mn={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(k)},async handler(e){try{await E(e)}catch(o){K(o),process.exit(1)}process.exit(0)}},
|
23
|
+
`)))}return console.log(C),x}var mn={command:"deploy",describe:"Deploy MUD contracts",builder(e){return e.options(k)},async handler(e){try{await E(e)}catch(o){K(o),process.exit(1)}process.exit(0)}},bo=mn;import{loadConfig as pn}from"@latticexyz/config/node";import{worldgen as fn}from"@latticexyz/world/node";import{getSrcDirectory as yn}from"@latticexyz/common/foundry";import ho from"path";import{rmSync as un}from"fs";var gn={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 config file"},clean:{type:"boolean",desc:"Clear the worldgen directory before generating new interfaces (defaults to true)",default:!0}})},async handler(e){await bn(e),process.exit(0)}};async function bn(e){let o=e.srcDir??await yn(),n=I(o),t=e.config??await pn(e.configPath),r=ho.join(o,t.codegen.outputDirectory);e.clean&&un(ho.join(r,t.codegen.worldgenDirectory),{recursive:!0,force:!0}),await fn(t,n,r)}var wo=gn;import _ from"chalk";import{readFileSync as Cn,writeFileSync as Dn}from"fs";import ge from"path";import{MUDError as N}from"@latticexyz/common/errors";var xo={name:"@latticexyz/cli",version:"2.0.6",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"},types:"src/index.ts",bin:{mud:"./dist/mud.js"},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":"rimraf dist","clean:test-tables":"rimraf src/codegen",dev:"tsup --watch",lint:"eslint . --ext .ts",prepare:"mkdir -p ./dist && touch ./dist/mud.js",test:"tsc --noEmit && forge test","test:ci":"pnpm run test"},dependencies:{"@ethersproject/abi":"^5.7.0","@ethersproject/providers":"^5.7.2","@improbable-eng/grpc-web":"^0.15.0","@improbable-eng/grpc-web-node-http-transport":"^0.15.0","@latticexyz/abi-ts":"workspace:*","@latticexyz/common":"workspace:*","@latticexyz/config":"workspace:*","@latticexyz/gas-report":"workspace:*","@latticexyz/protocol-parser":"workspace:*","@latticexyz/schema-type":"workspace:*","@latticexyz/services":"workspace:*","@latticexyz/store":"workspace:*","@latticexyz/utils":"workspace:*","@latticexyz/world":"workspace:*","@latticexyz/world-modules":"workspace:*",chalk:"^5.0.1",chokidar:"^3.5.3",debug:"^4.3.4",dotenv:"^16.0.3",ejs:"^3.1.8",ethers:"^5.7.2",execa:"^7.0.0",glob:"^8.0.3","nice-grpc-web":"^2.0.1",openurl:"^1.1.1","p-retry":"^5.1.2",path:"^0.12.7",rxjs:"7.5.5","throttle-debounce":"^5.0.0",toposort:"^2.0.2",typescript:"5.4.2",viem:"2.9.20",yargs:"^17.7.1",zod:"^3.21.4","zod-validation-error":"^1.3.0"},devDependencies:{"@types/debug":"^4.1.7","@types/ejs":"^3.1.1","@types/glob":"^7.2.0","@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",tsx:"^3.12.6",vitest:"0.34.6"}};import Tn from"glob";import{ZodError as wn,z as So}from"zod";var xn=So.object({MUD_PACKAGES:So.string().transform(e=>JSON.parse(e))});function Sn(){try{return xn.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/faucet":{"localPath":"packages/faucet"},"@latticexyz/gas-report":{"localPath":"packages/gas-report"},"@latticexyz/protocol-parser":{"localPath":"packages/protocol-parser"},"@latticexyz/query":{"localPath":"packages/query"},"@latticexyz/react":{"localPath":"packages/react"},"@latticexyz/recs":{"localPath":"packages/recs"},"@latticexyz/schema-type":{"localPath":"packages/schema-type"},"@latticexyz/services":{"localPath":"packages/services"},"solhint-config-mud":{"localPath":"packages/solhint-config-mud"},"solhint-plugin-mud":{"localPath":"packages/solhint-plugin-mud"},"@latticexyz/store-indexer":{"localPath":"packages/store-indexer"},"@latticexyz/store-sync":{"localPath":"packages/store-sync"},"@latticexyz/store":{"localPath":"packages/store"},"@latticexyz/utils":{"localPath":"packages/utils"},"@latticexyz/world-modules":{"localPath":"packages/world-modules"},"@latticexyz/world":{"localPath":"packages/world"}}'})}catch(e){if(e instanceof wn){let{...o}=e.format();console.error(`
|
24
24
|
Missing or invalid environment variables:
|
25
25
|
|
26
26
|
${Object.keys(o).join(`
|
27
27
|
`)}
|
28
|
-
`),process.exit(1)}throw e}}var ue=Sn().MUD_PACKAGES;var vn={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"],n=o.reduce((r,s)=>e[s]?r+1:r,0);if(n===0)throw new N(`You need to provide one these options: ${o.join(", ")}`);if(n>1)throw new N(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await An(e));let t=Tn.sync("**/package.json").filter(r=>!r.includes("node_modules"));for(let r of t)kn(r,e)}catch(o){K(o)}finally{process.exit(0)}}};async function An(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(_.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${
|
29
|
-
`),console.log(`Updating ${e}`),
|
28
|
+
`),process.exit(1)}throw e}}var ue=Sn().MUD_PACKAGES;var vn={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"],n=o.reduce((r,s)=>e[s]?r+1:r,0);if(n===0)throw new N(`You need to provide one these options: ${o.join(", ")}`);if(n>1)throw new N(`These options are mutually exclusive: ${o.join(", ")}`);e.link||(e.mudVersion=await An(e));let t=Tn.sync("**/package.json").filter(r=>!r.includes("node_modules"));for(let r of t)kn(r,e)}catch(o){K(o)}finally{process.exit(0)}}};async function An(e){e.mudVersion==="canary"&&(e.tag="main");let o;try{console.log(_.blue("Fetching available versions")),o=await(await fetch(`https://registry.npmjs.org/${xo.name}`)).json()}catch{throw new N("Could not fetch available MUD versions")}if(e.tag){let n=o["dist-tags"][e.tag];if(!n)throw new N(`Could not find npm version with tag "${e.tag}"`);return console.log(_.green(`Latest version with tag ${e.tag}: ${n}`)),n}if(e.commit){let n=e.commit.substring(0,8),t=Object.keys(o.versions).find(r=>r.includes(n));if(!t)throw new N(`Could not find npm version based on commit "${e.commit}"`);return console.log(_.green(`Version from commit ${e.commit}: ${t}`)),t}return e.mudVersion}function kn(e,o){let{link:n}=o,{mudVersion:t}=o,r=In(e),s=Object.keys(ue),i={};for(let c in r.dependencies)s.includes(c)&&(i[c]=r.dependencies[c]);let a={};for(let c in r.devDependencies)s.includes(c)&&(a[c]=r.devDependencies[c]);for(let c in r.dependencies)s.includes(c)&&(r.dependencies[c]=m(c,"dependencies"));for(let c in r.devDependencies)s.includes(c)&&(r.devDependencies[c]=m(c,"devDependencies"));return Dn(e,JSON.stringify(r,null,2)+`
|
29
|
+
`),console.log(`Updating ${e}`),Co(i,r.dependencies),Co(a,r.devDependencies),r;function m(c,f){return n&&(t=Bn(e,n,c)),t||r[f][c]}}function In(e){try{let o=Cn(e,"utf8");return JSON.parse(o)}catch{throw new N("Could not read JSON at "+e)}}function Co(e,o){for(let n in e)e[n]!==o[n]&&console.log(`${n}: ${_.red(e[n])} -> ${_.green(o[n])}`)}function Bn(e,o,n){let t=ge.relative(ge.dirname(e),process.cwd());return"link:"+ge.join(t,o,ue[n].localPath)}var Do=vn;import{anvil as Pn,forge as jn,getRpcUrl as On}from"@latticexyz/common/foundry";import Rn from"chalk";var Mn={...k,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"}},Wn={command:"test",describe:"Run tests in MUD contracts",builder(e){return e.options(Mn)},async handler(e){if(!e.worldAddress){let r=["--block-base-fee-per-gas","0","--port",String(e.port)];Pn(r)}let o=e.worldAddress?await On(e.profile):`http://127.0.0.1:${e.port}`,n=e.worldAddress??(await E({...e,saveDeployment:!1,rpc:o})).address;console.log(Rn.blue("World address",n));let t=e.forgeOptions?.replaceAll("\\","").split(" ")??[];try{await jn(["test","--fork-url",o,...t],{profile:e.profile,env:{WORLD_ADDRESS:n}}),process.exit(0)}catch(r){console.error(r),process.exit(1)}}},To=Wn;import{existsSync as $n,readFileSync as Hn}from"fs";import{ethers as vo}from"ethers";import{loadConfig as Fn}from"@latticexyz/config/node";import{MUDError as Ao}from"@latticexyz/common/errors";import{cast as En,getRpcUrl as Nn,getSrcDirectory as zn}from"@latticexyz/common/foundry";import{resolveWorldConfig as Ln}from"@latticexyz/world/internal";import Vn from"@latticexyz/world/out/IBaseWorld.sol/IBaseWorld.abi.json"assert{type:"json"};import ko from"@latticexyz/world/mud.config";import{resourceToHex as Bo}from"@latticexyz/common";import{createClient as Un,http as _n}from"viem";import{getChainId as Kn}from"viem/actions";import{worldToV1 as Jn}from"@latticexyz/world/config/v2";var Io=Bo({type:"system",namespace:ko.namespace,name:ko.tables.world__Systems.name}),qn={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 config file"},profile:{type:"string",description:"The foundry profile to use"},srcDir:{type:"string",description:"Source directory. Defaults to foundry src directory."},rpc:{type:"string",description:"json rpc endpoint. Defaults to foundry's configured eth_rpc_url"}})},async handler(e){e.profile??=process.env.FOUNDRY_PROFILE;let{profile:o}=e;e.srcDir??=await zn(o),e.rpc??=await Nn(o);let{tx:n,configPath:t,srcDir:r,rpc:s}=e,i=I(r),a=await Fn(t),m=Jn(a),c=Ln(m,i.map(({basename:S})=>S)),f=e.worldAddress??await Yn(m.worldsFile,s),y=new vo.providers.StaticJsonRpcProvider(s),x=new vo.Contract(f,Vn,y),C=m.namespace,d=Object.values(c.systems).map(({name:S})=>S),u=await x.getFieldLayout(Io),w=[];for(let S of d){let p=Bo({type:"system",namespace:C,name:S}),g=await x.getField(Io,[p],0,u);w.push({name:S,address:g})}let h=await En(["run","--label",`${f}:World`,...w.map(({name:S,address:p})=>["--label",`${p}:${S}`]).flat(),`${n}`]);console.log(h),process.exit(0)}},Po=qn;async function Yn(e,o){if($n(e)){let n=Un({transport:_n(o)}),t=await Kn(n),r=JSON.parse(Hn(e,"utf-8"));if(!r[t])throw new Ao(`chainId ${t} is missing in worldsFile "${e}"`);return r[t].address}else throw new Ao("worldAddress is not specified and worldsFile is missing")}import{anvil as Gn,getScriptDirectory as Zn,getSrcDirectory as Qn}from"@latticexyz/common/foundry";import O from"chalk";import Xn from"chokidar";import{loadConfig as es,resolveConfigPath as os}from"@latticexyz/config/node";import ts from"path";import{homedir as rs}from"os";import{rmSync as ns}from"fs";import{BehaviorSubject as ss,debounceTime as as,exhaustMap as is,filter as ds}from"rxjs";import{isDefined as cs}from"@latticexyz/common/utils";var ls={rpc:k.rpc,configPath:k.configPath,alwaysRunPostDeploy:k.alwaysRunPostDeploy,worldAddress:k.worldAddress},ms={command:"dev-contracts",describe:"Start a development server for MUD contracts",builder(e){return e.options(ls)},async handler(e){let o=e.rpc,n=e.configPath??await os(e.configPath),t=await Qn(),r=await Zn(),s=await es(n);if(!e.rpc){console.log(O.gray("Cleaning devnode cache"));let c=rs();ns(ts.join(c,".foundry","anvil","tmp"),{recursive:!0,force:!0}),Gn(["--block-time","1","--block-base-fee-per-gas","0"]),o="http://127.0.0.1:8545"}let i=new ss(Date.now());Xn.watch([n,t,r],{ignoreInitial:!0}).on("all",async(c,f)=>{f.includes(n)&&(console.log(O.blue("Config changed, queuing deploy\u2026")),i.next(Date.now())),(f.includes(t)||f.includes(r))&&(f.includes(s.codegen.outputDirectory)||(console.log(O.blue("Contracts changed, queuing deploy\u2026")),i.next(Date.now())))});let a=e.worldAddress;i.pipe(as(200),is(async c=>{a&&console.log(O.blue("Rebuilding and upgrading world\u2026"));try{let f=await E({...e,configPath:n,rpc:o,rpcBatch:!1,skipBuild:!1,printConfig:!1,profile:void 0,saveDeployment:!0,deployerAddress:void 0,worldAddress:a,srcDir:t,salt:"0x"});return a=f.address,c<i.value?i.next(i.value):console.log(O.gray(`
|
30
30
|
Waiting for file changes\u2026
|
31
31
|
`)),f}catch(f){console.error(O.bgRed(O.whiteBright(`
|
32
32
|
Error while attempting deploy
|
33
33
|
`))),console.error(f),console.log(O.gray(`
|
34
34
|
Waiting for file changes\u2026
|
35
|
-
`))}}),ds(cs)).subscribe()}},
|
36
|
-
//# sourceMappingURL=commands-
|
35
|
+
`))}}),ds(cs)).subscribe()}},jo=ms;var Np=[he,bo,we,Se,ps,Ce,De,wo,Do,To,Po,jo,fs];export{Np as commands};
|
36
|
+
//# sourceMappingURL=commands-2FAWZS5F.js.map
|