Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Support stylus contracts publish and deploy #6495

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/thirdweb/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -221,10 +221,13 @@
"@walletconnect/ethereum-provider": "2.17.5",
"@walletconnect/sign-client": "2.17.5",
"abitype": "1.0.8",
"chalk": "^5.4.1",
"cross-spawn": "7.0.6",
"fuse.js": "7.1.0",
"input-otp": "^1.4.1",
"mipd": "0.0.7",
"open": "^10.1.0",
"ora": "^8.2.0",
"ox": "0.6.10",
"uqr": "0.1.2",
"viem": "2.23.10"
Expand Down
13 changes: 13 additions & 0 deletions packages/thirdweb/src/cli/bin.ts
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,17 @@ import {
generate,
isValidChainIdAndContractAddress,
} from "./commands/generate/generate.js";
import { publishStylus } from "./commands/publish-stylus/publish-stylus.js";
// skip the first two args?
const [, , command = "", ...rest] = process.argv;

let secretKey: string | undefined;
const keyIndex = rest.indexOf("-k");
if (keyIndex !== -1 && rest.length > keyIndex + 1) {
secretKey = rest[keyIndex + 1];
rest.splice(keyIndex, 2);
}

async function main() {
switch (command) {
case "generate": {
Expand All @@ -20,6 +28,11 @@ async function main() {
break;
}

case "publish-stylus": {
await publishStylus(secretKey);
break;
}

case "login": {
// Not implemented yet
console.info(
Expand Down
175 changes: 175 additions & 0 deletions packages/thirdweb/src/cli/commands/publish-stylus/publish-stylus.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { spawnSync } from "node:child_process";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import open from "open";
import ora from "ora";
import { createThirdwebClient } from "../../../client/client.js";
import { upload } from "../../../storage/upload.js";

export const THIRDWEB_URL = "https://thirdweb.com";

export async function publishStylus(secretKey?: string) {
const spinner = ora("Checking if this is a Stylus project...").start();

if (!secretKey) {
spinner.fail("Error: Secret key is required.");
process.exit(1);
}

try {
// Step 1: Validate Stylus project
const root = process.cwd();
if (!root) {
spinner.fail("Error: No package directory found.");
process.exit(1);
}

const cargoTomlPath = join(root, "Cargo.toml");
if (!existsSync(cargoTomlPath)) {
spinner.fail("Error: No Cargo.toml found. Not a Rust project.");
process.exit(1);
}

const cargoToml = readFileSync(cargoTomlPath, "utf8");
if (!cargoToml.includes("[dependencies.stylus-sdk]")) {
// spinner.fail("Error: Not a Stylus project. Missing stylus-sdk dependency.");
// process.exit(1);
}

spinner.succeed("Stylus project detected.");

// Step 2: Run Stylus export commands
spinner.start("Exporting initcode...");
const bytecodeResult = spawnSync("cargo", ["stylus", "export-initcode"], {
stdio: "inherit",
});

if (bytecodeResult.status !== 0) {
spinner.fail("Failed to export initcode.");
process.exit(1);
}
spinner.succeed("Initcode exported.");

spinner.start("Exporting ABI...");
const abiResult = spawnSync(
"cargo",
["stylus", "export-abi", "--json", "--output", "abi.json"],
{ stdio: "inherit" },
);

if (abiResult.status !== 0) {
spinner.fail("Failed to export ABI.");
process.exit(1);
}
spinner.succeed("ABI exported.");

// Step 3: Read the output files
const bytecodePath = join(root, "./initcode");
const abiPath = join(root, "./abi.json");

if (!existsSync(bytecodePath) || !existsSync(abiPath)) {
spinner.fail("Error: Export failed. Bytecode or ABI file not found.");
process.exit(1);
}
const abiContent = readFileSync(abiPath, "utf8").trim();

const contractName = extractContractNameFromExportAbi(abiContent);
console.log("extracted contract name: ", contractName);
if (!contractName) {
spinner.fail("Error: Could not determine contract name from ABI output.");
process.exit(1);
}

let cleanedAbi = "";
try {
const jsonMatch = abiContent.match(/\[.*\]/s);
if (jsonMatch) {
cleanedAbi = jsonMatch[0];
} else {
throw new Error("No valid JSON ABI found in the file.");
}
} catch (error) {
spinner.fail("Error: ABI file contains invalid format.");
console.error(error);
process.exit(1);
}

const metadata = {
compiler: {},
language: "",
output: {
abi: JSON.parse(cleanedAbi),
devdoc: {},
userdoc: {},
},
settings: {
compilationTarget: {
"src/main.rs": contractName,
},
},
sources: {},
};
writeFileSync(abiPath, JSON.stringify(metadata), "utf8");
spinner.succeed("ABI cleaned and saved.");

spinner.succeed("Stylus contract exported successfully.");

// Step 4: Upload to IPFS (Placeholder)
spinner.start("Uploading to IPFS...");
const client = createThirdwebClient({
secretKey,
});

const metadataUri = await upload({
client,
files: [metadata],
});
console.log(metadataUri);

const bytecodeContents = readFileSync(bytecodePath, "utf8");

const bytecodeUri = await upload({
client,
files: [bytecodeContents],
});
console.log(bytecodeUri);

const publishUri = await upload({
client,
files: [
{
name: contractName,
metadataUri,
bytecodeUri,
stylus: true,
},
],
});

const url = getUrl(publishUri, "publish").toString();
spinner.succeed(`Upload complete:, ${url}`);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a small typo in the success message - the comma after "Upload complete:" is unnecessary and makes the message read awkwardly. Consider changing to:

spinner.succeed(`Upload complete: ${url}`);

This will display a cleaner message to users when their upload finishes.

Suggested change
spinner.succeed(`Upload complete:, ${url}`);
spinner.succeed(`Upload complete: ${url}`);

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.


await open(url);
} catch (error: any) {
spinner.fail(`Error: ${error}`);
process.exit(1);
}
}

function extractContractNameFromExportAbi(abiRawOutput: string): string | null {
const match = abiRawOutput.match(/<stdin>:(I[A-Za-z0-9_]+)/);
if (match && match[1]) {
return match[1].replace(/^I/, "");
}
return null;
}

export function getUrl(hash: string, command: string) {
const url = new URL(
`${THIRDWEB_URL}
/contracts/${command}/
${encodeURIComponent(hash.replace("ipfs://", ""))}`,
Comment on lines +168 to +171
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The URL template string contains newlines and whitespace that will be included in the final URL, which will cause navigation issues. This should be rewritten as a single-line string:

const url = new URL(`${THIRDWEB_URL}/contracts/${command}/${encodeURIComponent(hash.replace("ipfs://", ""))}`);
Suggested change
const url = new URL(
`${THIRDWEB_URL}
/contracts/${command}/
${encodeURIComponent(hash.replace("ipfs://", ""))}`,
const url = new URL(
`${THIRDWEB_URL}/contracts/${command}/${encodeURIComponent(hash.replace("ipfs://", ""))}`,

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

);

return url;
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ export function formatCompilerMetadata(
if ("source_metadata" in metadata) {
meta = metadata.source_metadata;
}

const compilationTarget = meta.settings.compilationTarget;
const targets = Object.keys(compilationTarget);
const name = compilationTarget[targets[0] as keyof typeof compilationTarget];
Expand Down
38 changes: 38 additions & 0 deletions packages/thirdweb/src/contract/actions/get-compiler-metadata.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import { eth_getTransactionByHash } from "../../rpc/actions/eth_getTransactionByHash.js";
import { getRpcClient } from "../../rpc/rpc.js";
import { download } from "../../storage/download.js";
import { hexToString } from "../../utils/encoding/hex.js";
import type { ThirdwebContract } from "../contract.js";
import { formatCompilerMetadata } from "./compiler-metadata.js";

Expand All @@ -21,6 +25,40 @@ import { formatCompilerMetadata } from "./compiler-metadata.js";
*/
export async function getCompilerMetadata(contract: ThirdwebContract) {
const { address, chain } = contract;

try {
const res = await fetch(
`https://contract.thirdweb-dev.com/creation/${contract.chain.id}/${contract.address}`,
);
const creationData = await res.json();

if (creationData.status === "1" && creationData.result[0]?.txHash) {
const rpcClient = getRpcClient({
client: contract.client,
chain: contract.chain,
});
const creationTx = await eth_getTransactionByHash(rpcClient, {
hash: creationData.result[0]?.txHash,
});

const initCode = creationTx.input;
const lengthHex = initCode.slice(-2);
const dataLength = Number.parseInt(lengthHex, 16) * 2;
const encodedIpfsHex = initCode.slice(-dataLength - 2, -2);
const uri = hexToString(`0x${encodedIpfsHex}`);

const res = await download({
client: contract.client,
uri,
});
const metadata = await res.json();

return formatCompilerMetadata(metadata);
}
} catch (e) {
console.debug(e);
}

const response = await fetch(
`https://contract.thirdweb.com/metadata/${chain.id}/${address}`,
{
Expand Down
55 changes: 48 additions & 7 deletions packages/thirdweb/src/contract/actions/resolve-abi.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { type Abi, formatAbi, parseAbi } from "abitype";
import { eth_getTransactionByHash } from "../../rpc/actions/eth_getTransactionByHash.js";
import { getRpcClient } from "../../rpc/rpc.js";
import { download } from "../../storage/download.js";
import { hexToString } from "../../utils/encoding/hex.js";
import { getClientFetch } from "../../utils/fetch.js";
import { withCache } from "../../utils/promise/withCache.js";
import { type ThirdwebContract, getContract } from "../contract.js";
Expand Down Expand Up @@ -43,15 +46,53 @@ export function resolveContractAbi<abi extends Abi>(
return (await resolveCompositeAbi(contract as ThirdwebContract)) as abi;
}

// try to get it from the api
try {
return (await resolveAbiFromContractApi(
contract,
contractApiBaseUrl,
)) as abi;
const res = await fetch(
`https://contract.thirdweb-dev.com/creation/${contract.chain.id}/${contract.address}`,
);
const creationData = await res.json();

if (creationData.status === "1" && creationData.result[0]?.txHash) {
const rpcClient = getRpcClient({
client: contract.client,
chain: contract.chain,
});
const creationTx = await eth_getTransactionByHash(rpcClient, {
hash: creationData.result[0]?.txHash,
});

const initCode = creationTx.input;
const lengthHex = initCode.slice(-2);
const dataLength = Number.parseInt(lengthHex, 16) * 2;
const encodedIpfsHex = initCode.slice(-dataLength - 2, -2);
const uri = hexToString(`0x${encodedIpfsHex}`);

const res = await download({
client: contract.client,
uri,
});
const metadata = await res.json();

return metadata.output.abi as abi;
} else {
return (await resolveCompositeAbi(
contract as ThirdwebContract,
)) as abi;
}
} catch {
// if that fails, try to resolve it from the bytecode
return (await resolveCompositeAbi(contract as ThirdwebContract)) as abi;
// try to get it from the api
try {
return (await resolveAbiFromContractApi(
contract,
contractApiBaseUrl,
)) as abi;
} catch {
// console.debug(e);
// if that fails, try to resolve it from the bytecode
return (await resolveCompositeAbi(
contract as ThirdwebContract,
)) as abi;
}
}
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export type PrepareDirectDeployTransactionOptions = Prettify<
abi: Abi;
bytecode: Hex;
constructorParams?: Record<string, unknown>;
extraData?: string;
}
>;

Expand Down Expand Up @@ -70,6 +71,7 @@ export function prepareDirectDeployTransaction(
constructorAbi?.inputs || [], // Leave an empty array if there's no constructor
normalizeFunctionParams(constructorAbi, options.constructorParams),
),
`0x${options.extraData}`,
]),
});
}
Expand Down Expand Up @@ -121,6 +123,7 @@ export async function deployContract(
options: PrepareDirectDeployTransactionOptions & {
account: Account;
salt?: string;
extraData?: string;
},
) {
if (await isZkSyncChain(options.chain)) {
Expand Down Expand Up @@ -160,7 +163,11 @@ export async function deployContract(
chain: options.chain,
client: options.client,
to: info.create2FactoryAddress,
data: info.initBytecodeWithsalt,
data: options.extraData
? (info.initBytecodeWithsalt.concat(
options.extraData,
) as `0x${string}`)
: info.initBytecodeWithsalt,
}),
});
return address;
Expand Down
Loading
Loading