repo_id
stringclasses
563 values
file_path
stringlengths
40
166
content
stringlengths
1
2.94M
__index_level_0__
int64
0
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/reveal/reveal.ts
import { getCmCreatorMetadataAccounts, getMetaplex, loadCache, loadConfigData, } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgTerminal, PgWeb3 } from "../../../../utils/pg"; export const processReveal = async (rpcUrl: string | undefined) => { const term = await PgTerminal.get(); term.println(`[1/4] ${Emoji.LOOKING_GLASS} Loading items from the cache`); const configData = await loadConfigData(); if (!configData.hiddenSettings) { throw new Error("Candy machine is not a Hidden Settings mint."); } const cache = await loadCache(); const candyMachinePkStr = cache.program.candyMachine; let candyMachinePk; try { candyMachinePk = new PgWeb3.PublicKey(candyMachinePkStr); } catch { throw new Error(`Failed to parse candy machine id: ${candyMachinePkStr}`); } term.println( `\n[2/4] ${Emoji.LOOKING_GLASS} Getting minted NFTs for candy machine ${candyMachinePkStr}` ); const metaplex = await getMetaplex(rpcUrl); const creatorPda = metaplex .candyMachines() .pdas() .authority({ candyMachine: candyMachinePk }); const metadataAccounts = await getCmCreatorMetadataAccounts( metaplex, creatorPda.toBase58() ); if (!metadataAccounts.length) { throw new Error( `No minted NFTs found for candy machine ${candyMachinePkStr}` ); } term.println(`Found ${metadataAccounts.length} account(s)`); // Not necessary but keeping it just to have the same output as sugar cli term.println(`\n[3/4] ${Emoji.LOOKING_GLASS} Matching NFTs to cache values`); term.println(`\n[4/4] ${Emoji.UPLOAD} Updating NFT URIs from cache values`); // Show progress bar PgTerminal.setProgress(0.1); let progressCount = 0; let errorCount = 0; const CONCURRENT = 4; const nftNumberRegex = /#(\d+)/; await Promise.all( new Array(CONCURRENT).fill(null).map(async (_, i) => { for (let j = 0; j + i < metadataAccounts.length; j += CONCURRENT) { try { const nft = await metaplex .nfts() .findByMetadata({ metadata: metadataAccounts[j + i].publicKey }); const regexResult = nftNumberRegex.exec(nft.name); if (!regexResult) { throw new Error( `NFT (${nft.address}) is not numbered. Your hidden settings are not set up correctly.` ); } // Don't update if the uri is the same(re-run) const cacheMetadataLink = cache.items[`${+regexResult[1] - 1}`].metadata_link; if (nft.uri === cacheMetadataLink) continue; await metaplex.nfts().update({ nftOrSft: nft, uri: cacheMetadataLink, }); } catch (e: any) { console.log(e.message); errorCount++; } finally { progressCount++; PgTerminal.setProgress( (progressCount / metadataAccounts.length) * 100 ); } } }) ); // Hide progress bar setTimeout(() => PgTerminal.setProgress(0), 1000); if (errorCount) { term.println( `${PgTerminal.error( `${Emoji.WARNING} Some reveals failed.` )} ${errorCount} items failed.` ); throw new Error( `${PgTerminal.error("Revealed")} ${ metadataAccounts.length - errorCount }/${metadataAccounts.length} ${PgTerminal.error("of the items")}` ); } else { term.println(PgTerminal.secondary(`${Emoji.CONFETTI} Reveal complete!`)); } };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/reveal/index.ts
export * from "./reveal";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/show/index.ts
export * from "./show";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/show/show.ts
import { Creator } from "@metaplex-foundation/js"; import { NULL_STRING } from "../../constants"; import { getMetaplex, loadCache, printWithStyle } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgCommon, PgTerminal, PgWeb3 } from "../../../../utils/pg"; export const processShow = async ( rpcUrl: string | undefined, candyMachine: string | undefined, unminted: boolean ) => { const term = await PgTerminal.get(); term.println( `[1/${unminted ? "2" : "1"}] ${ Emoji.LOOKING_GLASS } Looking up candy machine` ); // The candy machine id specified takes precedence over the one from the cache const candyMachinePkStr = candyMachine ?? (await loadCache()).program.candyMachine; if (!candyMachinePkStr) { throw new Error("Missing candy machine id."); } let candyMachinePk; try { candyMachinePk = new PgWeb3.PublicKey(candyMachinePkStr); } catch { throw new Error(`Failed to parse candy machine id: ${candyMachinePkStr}`); } const candyClient = (await getMetaplex(rpcUrl)).candyMachines(); const candyState = await candyClient.findByAddress({ address: candyMachinePk, }); term.println( `\n${Emoji.CANDY} ${PgTerminal.secondaryText( "Candy machine ID:" )} ${candyMachinePkStr}` ); // Candy machine state and data term.println(` ${PgTerminal.secondaryText(":")}`); printWithStyle("", "authority", candyState.authorityAddress.toString()); printWithStyle( "", "mint authority", candyState.mintAuthorityAddress.toString() ); printWithStyle( "", "collection mint", candyState.collectionMintAddress.toString() ); printWithStyle("", "max supply", candyState.maxEditionSupply.toString()); printWithStyle("", "items redeemed", candyState.itemsMinted.toString()); printWithStyle("", "items available", candyState.itemsAvailable.toString()); if (candyState.featureFlags.reduce((f) => (f ? 1 : 0), 0) > 0) { printWithStyle("", "features", candyState.featureFlags); } else { printWithStyle("", "features", "none"); } printWithStyle("", "symbol", candyState.symbol.replaceAll(NULL_STRING, "")); printWithStyle( "", "seller fee basis points", `${candyState.sellerFeeBasisPoints / 100}% (${ candyState.sellerFeeBasisPoints })` ); printWithStyle("", "is mutable", candyState.isMutable); printWithStyle("", "creators", ""); const creators = candyState.creators; for (const i in creators) { const creator = creators[i] as Creator; printWithStyle( ": ", +i + 1, `${creator.address} (${creator.share}%${ creator.verified ? ", verified" : "" })` ); } // Hidden settings const itemType = candyState.itemSettings.type; if (itemType === "hidden") { const hiddenSettings = candyState.itemSettings; printWithStyle("", "hidden settings", ""); printWithStyle(": ", "name", hiddenSettings.name); printWithStyle(": ", "uri", hiddenSettings.uri); printWithStyle( ": ", "hash", PgCommon.decodeBytes(Uint8Array.from(hiddenSettings.hash)) ); } else { printWithStyle("", "hidden settings", "none"); } // Config line settings if (itemType === "configLines") { const configLineSettings = candyState.itemSettings; printWithStyle("", "config line settings", ""); const prefixName = !configLineSettings.prefixName ? PgTerminal.secondaryText("<empty>") : configLineSettings.prefixName; printWithStyle(" ", "prefix_name", prefixName); printWithStyle(" ", "name_length", configLineSettings.nameLength); const prefixUri = !configLineSettings.prefixUri ? PgTerminal.secondaryText("<empty>") : configLineSettings.prefixUri; printWithStyle(" ", "prefix_uri", prefixUri); printWithStyle(" ", "uri_length", configLineSettings.uriLength); printWithStyle( " ", "is_sequential", configLineSettings.isSequential ? true : false ); } else { printWithStyle("", "config line settings", "none"); } // Unminted indices if (unminted) { term.println(`\n[2/2] ${Emoji.LOOKING_GLASS} Retrieving unminted indices`); const indices = []; for (const configLine of candyState.items) { if (!configLine.minted) indices.push(configLine.index); } if (!indices.length) { term.println( `\n${Emoji.PAPER} ${PgTerminal.secondaryText( "All items of the candy machine have been minted." )}` ); } else { // Makes sure all items are in order indices.sort(); term.println( `\n${Emoji.PAPER} ${PgTerminal.bold( `Unminted list (${indices.length} total):` )}` ); let current = 0; for (const i of indices) { if (!current) { term.println(PgTerminal.secondaryText(" :")); term.print(PgTerminal.secondaryText(" :.. ")); } current += 1; if (current === 11) { current = 0; term.print( `${PgCommon.string(i.toString(), { addSpace: { amount: 5 } })}\n` ); } else { term.print( `${PgCommon.string(i.toString(), { addSpace: { amount: 5 } })} ` ); } } // Just adds a new line break term.println(""); } } };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/guard/remove.ts
import { getMetaplex, loadCache } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgTerminal, PgWeb3 } from "../../../../utils/pg"; export const processGuardRemove = async ( rpcUrl: string | undefined, candyMachine: string | undefined, candyGuard: string | undefined ) => { const term = await PgTerminal.get(); term.println(`[1/1] ${Emoji.UNWRAP} Unwrapping`); // The candy machine id specified takes precedence over the one from the cache const candyMachinePkStr = candyMachine ?? (await loadCache()).program.candyMachine; if (!candyMachinePkStr) { throw new Error("Missing candy machine id."); } let candyMachinePk; try { candyMachinePk = new PgWeb3.PublicKey(candyMachinePkStr); } catch { throw new Error(`Failed to parse candy machine id: ${candyMachinePkStr}`); } // The candy guard id specified takes precedence over the one from the cache const candyGuardPkStr = candyGuard ?? (await loadCache()).program.candyGuard; if (!candyGuardPkStr) { throw new Error("Missing candy machine guard id."); } let candyGuardPk; try { candyGuardPk = new PgWeb3.PublicKey(candyGuardPkStr); } catch { throw new Error( `Failed to parse candy machine guard id: ${candyGuardPkStr}` ); } // Remove the candy guard as mint authority const metaplex = await getMetaplex(rpcUrl); const { response } = await metaplex.candyMachines().unwrapCandyGuard({ candyGuard: candyGuardPk, candyMachine: candyMachinePk, }); term.println(`Signature: ${response.signature}`); term.println( "\nThe candy guard is no longer the mint authority of the candy machine." ); term.println( ` -> New mint authority: ${PgTerminal.bold( metaplex.identity().publicKey.toBase58() )}`, { noColor: true } ); };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/guard/index.ts
export * from "./add"; export * from "./remove"; export * from "./show"; export * from "./update"; export * from "./withdraw";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/guard/add.ts
import { CandyCache, getMetaplex, loadCache, loadConfigData, } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgTerminal, PgWeb3 } from "../../../../utils/pg"; export const processGuardAdd = async ( rpcUrl: string | undefined, candyMachine: string | undefined, candyGuard: string | undefined ) => { const term = await PgTerminal.get(); term.println(`[1/3] ${Emoji.LOOKING_GLASS} Looking up candy machine`); // The candy machine id specified takes precedence over the one from the cache let candyInfo: [string, CandyCache | null]; if (candyMachine) { candyInfo = [candyMachine, null]; } else { const cache = await loadCache(); candyInfo = [cache.program.candyMachine, cache]; } const [candyMachinePkStr, cache] = candyInfo; if (!candyMachinePkStr) { throw new Error("Missing candy machine id."); } let candyMachinePk: PgWeb3.PublicKey; try { candyMachinePk = new PgWeb3.PublicKey(candyMachinePkStr); } catch { throw new Error(`Failed to parse candy machine id: ${candyMachinePkStr}`); } term.println(`\nCandy machine ID: ${candyMachinePkStr}`); // Decide whether to create a new candy guard or use an existing one let candyGuardPkStr = ""; if (candyGuard) { candyGuardPkStr = candyGuard; } else if (cache) { candyGuardPkStr = cache.program.candyGuard; } const metaplex = await getMetaplex(rpcUrl); const configData = await loadConfigData(); if (!configData.guards) { throw new Error("Missing guards configuration."); } let candyGuardPk; if (!candyGuardPkStr) { term.println(`\n[2/3] ${Emoji.GUARD} Initializing a candy guard`); const { response, candyGuardAddress } = await metaplex .candyMachines() .createCandyGuard({ guards: configData.guards.default, groups: configData.guards.groups ?? undefined, }); candyGuardPk = candyGuardAddress; term.println(`Signature: ${response.signature}`); } else { term.println(`\n[2/3] ${Emoji.COMPUTER} Loading candy guard`); try { candyGuardPk = new PgWeb3.PublicKey(candyGuardPkStr); } catch { throw new Error(`Failed to parse candy guard id: ${candyGuardPkStr}`); } // Synchronizes the guards config with the on-chain account await metaplex.candyMachines().updateCandyGuard({ candyGuard: candyGuardPk, guards: configData.guards.default, groups: configData.guards.groups ?? undefined, }); } term.println(`\nCandy guard ID: ${candyGuardPk.toBase58()}`); // Wrap the candy machine term.println(`\n[3/3] ${Emoji.WRAP} Wrapping`); const { response } = await metaplex.candyMachines().wrapCandyGuard({ candyGuard: candyGuardPk, candyMachine: candyMachinePk, candyGuardAuthority: metaplex.identity(), candyMachineAuthority: metaplex.identity(), }); term.println(`Signature: ${response.signature}`); term.println( "\nThe candy guard is now the mint authority of the candy machine." ); // If we created a new candy guard from the candy machine on the cache file, // we store the reference of the candy guard on the cache if (cache) { cache.program.candyGuard = candyGuardPk.toBase58(); await cache.syncFile(); } };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/guard/withdraw.ts
import { getMetaplex, loadCache, loadConfigData } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgTerminal, PgWeb3 } from "../../../../utils/pg"; export const processGuardWithdraw = async ( rpcUrl: string | undefined, candyGuard: string | undefined ) => { const term = await PgTerminal.get(); term.println(`[1/2] ${Emoji.LOOKING_GLASS} Loading candy guard`); // The candy guard id specified takes precedence over the one from the cache const candyGuardPkStr = candyGuard ?? (await loadCache()).program.candyGuard; if (!candyGuardPkStr) { throw new Error("Missing candy machine guard id."); } let candyGuardPk; try { candyGuardPk = new PgWeb3.PublicKey(candyGuardPkStr); } catch { throw new Error( `Failed to parse candy machine guard id: ${candyGuardPkStr}` ); } term.println(`Candy guard ID: ${candyGuardPkStr}`); term.println(`\n[2/2] ${Emoji.COMPUTER} Updating configuration`); const { guards } = await loadConfigData(); if (!guards) { throw new Error("Missing guards configuration."); } const metaplex = await getMetaplex(rpcUrl); const { response } = await metaplex.candyMachines().deleteCandyGuard({ candyGuard: candyGuardPk, }); term.println(`Signature: ${response.signature}`); };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/guard/show.ts
import { DefaultCandyGuardSettings } from "@metaplex-foundation/js"; import { getMetaplex, loadCache, printWithStyle } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgCommon, PgTerminal, PgWeb3 } from "../../../../utils/pg"; export const processGuardShow = async ( rpcUrl: string | undefined, candyGuard: string | undefined ) => { const term = await PgTerminal.get(); term.println(`[1/1] ${Emoji.LOOKING_GLASS} Loading candy guard`); // The candy guard id specified takes precedence over the one from the cache const candyGuardPkStr = candyGuard ?? (await loadCache()).program.candyGuard; if (!candyGuardPkStr) { throw new Error("Missing candy machine guard id."); } let candyGuardPk; try { candyGuardPk = new PgWeb3.PublicKey(candyGuardPkStr); } catch { throw new Error( `Failed to parse candy machine guard id: ${candyGuardPkStr}` ); } const metaplex = await getMetaplex(rpcUrl); const candyGuardAccount = await metaplex .candyMachines() .findCandyGuardByAddress({ address: candyGuardPk }); term.println( `\n${Emoji.GUARD} ${PgTerminal.secondaryText( "Candy Guard ID:" )} ${candyGuardPkStr}` ); // Candy guard configuration term.println(` ${PgTerminal.secondaryText(":")}`); printWithStyle("", "base", candyGuardAccount.baseAddress.toBase58()); printWithStyle("", "bump", candyGuardAccount.address.bump); printWithStyle( "", "authority", candyGuardAccount.authorityAddress.toBase58() ); printWithStyle("", "data"); // Default guard set printWithStyle(" ", "default"); printGuardSet(candyGuardAccount.guards, " : "); // Groups if (Object.keys(candyGuardAccount.groups).length) { term.println(` ${PgTerminal.secondaryText(":")}`); printWithStyle(" ", "groups"); const groups = candyGuardAccount.groups; for (const i in groups) { if (i !== "0") { // Padding between groups term.println(` ${PgTerminal.secondaryText(":")}`); } const group = groups[i]; printWithStyle(" ", "label", group.label); printGuardSet( group.guards, +i === groups.length - 1 ? " " : " : " ); } } else { printWithStyle(" ", "groups", "none"); } }; const printGuardSet = ( guardSet: DefaultCandyGuardSettings, padding: string ) => { const innerPadding = `${padding}: `; // Bot tax if (guardSet.botTax) { printWithStyle(padding, "bot tax"); printWithStyle( innerPadding, "lamports", `${guardSet.botTax.lamports.basisPoints.toString()} (${Emoji.SOL} ${ guardSet.botTax.lamports.basisPoints.toNumber() / PgWeb3.LAMPORTS_PER_SOL })` ); printWithStyle( innerPadding, "last instruction", guardSet.botTax.lastInstruction ); } else { printWithStyle(padding, "bot tax", "none"); } // Sol payment if (guardSet.solPayment) { printWithStyle(padding, "sol payment"); printWithStyle( innerPadding, "lamports", `${guardSet.solPayment.amount.basisPoints.toString()} (${Emoji.SOL} ${ guardSet.solPayment.amount.basisPoints.toNumber() / PgWeb3.LAMPORTS_PER_SOL })` ); printWithStyle( innerPadding, "destination", guardSet.solPayment.destination.toBase58() ); } else { printWithStyle(padding, "sol payment", "none"); } // Token payment if (guardSet.tokenPayment) { printWithStyle(padding, "token payment"); printWithStyle( innerPadding, "amount", guardSet.tokenPayment.amount.basisPoints.toNumber() / 10 ** guardSet.tokenPayment.amount.currency.decimals ); printWithStyle( innerPadding, "token mint", guardSet.tokenPayment.mint.toBase58() ); } else { printWithStyle(padding, "token payment", "none"); } // Start date if (guardSet.startDate) { printWithStyle(padding, "start date"); printWithStyle( innerPadding, "date", PgCommon.getFormattedDateFromUnixTimestamp( guardSet.startDate.date.toNumber() ) ); } else { printWithStyle(padding, "start date", "none"); } // Third party signer if (guardSet.thirdPartySigner) { printWithStyle(padding, "third party signer"); printWithStyle( innerPadding, "signer key", guardSet.thirdPartySigner.signerKey.toBase58() ); } else { printWithStyle(padding, "third party signer", "none"); } // Token gate if (guardSet.tokenGate) { printWithStyle(padding, "token gate"); printWithStyle( innerPadding, "amount", guardSet.tokenGate.amount.basisPoints.toNumber() / 10 ** guardSet.tokenGate.amount.currency.decimals ); printWithStyle(innerPadding, "mint", guardSet.tokenGate.mint.toBase58()); } else { printWithStyle(padding, "token gate", "none"); } // Gatekeeper if (guardSet.gatekeeper) { printWithStyle(padding, "gatekeeper"); printWithStyle( innerPadding, "gatekeeper network", guardSet.gatekeeper.network ); printWithStyle( innerPadding, "expire on use", guardSet.gatekeeper.expireOnUse ); } else { printWithStyle(padding, "gatekeeper", "none"); } // End date if (guardSet.endDate) { printWithStyle(padding, "end date"); printWithStyle( innerPadding, "date", PgCommon.getFormattedDateFromUnixTimestamp( guardSet.endDate.date.toNumber() ) ); } else { printWithStyle(padding, "end date", "none"); } // Allow list if (guardSet.allowList) { printWithStyle(padding, "allow list"); printWithStyle( innerPadding, "merkle root", PgCommon.decodeBytes(guardSet.allowList.merkleRoot) ); } else { printWithStyle(padding, "allow list", "none"); } // Mint limit if (guardSet.mintLimit) { printWithStyle(padding, "mint limit"); printWithStyle(innerPadding, "id", guardSet.mintLimit.id); printWithStyle(innerPadding, "amount", guardSet.mintLimit.limit); } else { printWithStyle(padding, "mint limit", "none"); } // Nft payment if (guardSet.nftPayment) { printWithStyle(padding, "nft payment"); printWithStyle( innerPadding, "required collection", guardSet.nftPayment.requiredCollection.toBase58() ); printWithStyle( innerPadding, "destination", guardSet.nftPayment.destination.toBase58() ); } else { printWithStyle(padding, "nft payment", "none"); } // Redeemed amount if (guardSet.redeemedAmount) { printWithStyle(padding, "redeemed amount"); printWithStyle( innerPadding, "amount", guardSet.redeemedAmount.maximum.toString() ); } else { printWithStyle(padding, "redeemed amount", "none"); } // Address gate if (guardSet.addressGate) { printWithStyle(padding, "address gate"); printWithStyle( innerPadding, "address", guardSet.addressGate.address.toBase58() ); } else { printWithStyle(padding, "address gate", "none"); } // Nft gate if (guardSet.nftGate) { printWithStyle(padding, "nft gate"); printWithStyle( innerPadding, "required collection", guardSet.nftGate.requiredCollection.toBase58() ); } else { printWithStyle(padding, "nft gate", "none"); } // Nft burn if (guardSet.nftBurn) { printWithStyle(padding, "nft burn"); printWithStyle( innerPadding, "required collection", guardSet.nftBurn.requiredCollection.toBase58() ); } else { printWithStyle(padding, "nft burn", "none"); } // Token burn if (guardSet.tokenBurn) { printWithStyle(padding, "token burn"); printWithStyle( innerPadding, "amount", guardSet.tokenBurn.amount.basisPoints.toNumber() / 10 ** guardSet.tokenBurn.amount.currency.decimals ); printWithStyle(innerPadding, "mint", guardSet.tokenBurn.mint.toBase58()); } else { printWithStyle(padding, "token burn", "none"); } };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/guard/update.ts
import { getMetaplex, loadCache, loadConfigData } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgTerminal, PgWeb3 } from "../../../../utils/pg"; export const processGuardUpdate = async ( rpcUrl: string | undefined, candyGuard: string | undefined ) => { const term = await PgTerminal.get(); term.println(`[1/2] ${Emoji.LOOKING_GLASS} Loading candy guard`); // The candy guard id specified takes precedence over the one from the cache const candyGuardPkStr = candyGuard ?? (await loadCache()).program.candyGuard; if (!candyGuardPkStr) { throw new Error("Missing candy machine guard id."); } let candyGuardPk; try { candyGuardPk = new PgWeb3.PublicKey(candyGuardPkStr); } catch { throw new Error( `Failed to parse candy machine guard id: ${candyGuardPkStr}` ); } term.println(`Candy guard ID: ${candyGuardPkStr}`); term.println(`\n[2/2] ${Emoji.COMPUTER} Updating configuration`); const { guards } = await loadConfigData(); if (!guards) { throw new Error("Missing guards configuration."); } const metaplex = await getMetaplex(rpcUrl); const { response } = await metaplex.candyMachines().updateCandyGuard({ candyGuard: candyGuardPk, guards: guards.default, groups: guards.groups ?? undefined, }); term.println(`Signature: ${response.signature}`); };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/withdraw/index.ts
export * from "./withdraw";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/withdraw/withdraw.ts
import { Metaplex } from "@metaplex-foundation/js"; import { getMetaplex } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgCommon, PgTerminal, PgWeb3 } from "../../../../utils/pg"; export const processWithdraw = async ( candyMachine: string | undefined, rpcUrl: string | undefined, list: boolean ) => { // (1) Setting up connection const term = await PgTerminal.get(); term.println(`[1/2] ${Emoji.COMPUTER} Initializing connection`); const metaplex = await getMetaplex(rpcUrl); term.println( `\n[2/2] ${Emoji.WITHDRAW} ${list ? "Listing" : "Retrieving"} funds` ); // the --list flag takes precedence; even if a candy machine id is passed // as an argument, we will list the candy machines (no draining happens) const candyMachinePkStr = list ? null : candyMachine; // (2) Retrieving data for listing/draining if (candyMachinePkStr) { const candyMachinePk = new PgWeb3.PublicKey(candyMachinePkStr); await doWithdraw(metaplex, candyMachinePk); } else { const candyAccounts = await metaplex.connection.getProgramAccounts( metaplex.programs().getCandyMachine().address, { filters: [ { memcmp: { offset: 16, // authority bytes: metaplex.identity().publicKey.toString(), }, }, ], encoding: "base64", commitment: "confirmed", } ); const totalLamports = candyAccounts.reduce( (acc, cur) => acc + cur.account.lamports, 0 ); term.println( `\nFound ${candyAccounts.length} candy machine(s), total amount: ${ Emoji.SOL } ${totalLamports / PgWeb3.LAMPORTS_PER_SOL}`, { noColor: true } ); if (candyAccounts.length) { if (list) { term.println( `\n${PgCommon.string("Candy Machine ID", { addSpace: { amount: 48, position: "right" }, })} Balance` ); term.println(PgCommon.string("-", { repeat: { amount: 61 } })); for (const accountInfo of candyAccounts) { term.println( `${PgCommon.string(accountInfo.pubkey.toBase58(), { addSpace: { amount: 48, position: "right" }, })} ${PgCommon.string( ( accountInfo.account.lamports / PgWeb3.LAMPORTS_PER_SOL ).toString(), { addSpace: { amount: 8 } } )}` ); } } else { term.println( PgTerminal.warning( [ "\n+-----------------------------------------------------+", `| ${Emoji.WARNING} WARNING: This will drain ALL your Candy Machines |`, "+-----------------------------------------------------+", ].join("\n") ), { noColor: true } ); if ( !(await term.waitForUserInput("Do you want to continue?", { confirm: true, default: "yes", })) ) { throw new Error("Withdraw aborted"); } let notDrained = 0; const errors = []; for (const candyAccount of candyAccounts) { try { await doWithdraw(metaplex, candyAccount.pubkey); } catch (e: any) { notDrained++; errors.push({ candyMachine: candyAccount.pubkey.toBase58(), message: e.message, }); } } if (notDrained) { term.println( PgTerminal.error(`Could not drain ${notDrained} candy machine(s)`) ); term.println(PgTerminal.error(`Errors:`)); for (const error of errors) { term.println( `${PgTerminal.bold("Candy Machine:")} ${PgTerminal.error( error.candyMachine )}\n${PgTerminal.bold("Error:")} ${PgTerminal.error( error.message )}`, { noColor: true } ); } } } } } }; const doWithdraw = async ( metaplex: Metaplex, candyMachinePk: PgWeb3.PublicKey ) => { await metaplex.candyMachines().delete({ candyMachine: candyMachinePk }); };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/sign/sign.ts
import { Metaplex } from "@metaplex-foundation/js"; import { getCmCreatorMetadataAccounts, getMetaplex, loadCache, } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgTerminal, PgWeb3 } from "../../../../utils/pg"; export const processSign = async ( rpcUrl: string | undefined, mint: string | undefined, candyMachineId: string | undefined ) => { const term = await PgTerminal.get(); // (1) Setting up connection term.println( `[1/${mint ? "2" : "3"}] ${Emoji.COMPUTER} Initializing connection` ); const metaplex = await getMetaplex(rpcUrl); if (mint) { term.println(`\n[2/2] ${Emoji.SIGNING} Signing one NFT"`); await sign( metaplex, metaplex .nfts() .pdas() .metadata({ mint: new PgWeb3.PublicKey(mint) }) ); } else { term.println(`\n[2/3] ${Emoji.LOOKING_GLASS} Fetching mint ids`); const candyMachinePkStr = candyMachineId ?? (await loadCache()).program.candyMachine; let candyMachinePk; try { candyMachinePk = new PgWeb3.PublicKey(candyMachinePkStr); } catch { throw new Error(`Failed to parse candy machine id: ${candyMachinePkStr}`); } const creatorPda = metaplex .candyMachines() .pdas() .authority({ candyMachine: candyMachinePk }); const metadataAccounts = await getCmCreatorMetadataAccounts( metaplex, creatorPda.toBase58() ); if (!metadataAccounts.length) { throw new Error( `No NFTs found for candy machine id ${candyMachinePkStr}.` ); } else { term.println(`Found ${metadataAccounts.length} account(s)`); term.println(`\n[3/3] ${Emoji.SIGNING} Signing mint accounts`); } // Show progress bar PgTerminal.setProgress(0.1); let progressCount = 0; let errorCount = 0; const CONCURRENT = 4; await Promise.all( new Array(CONCURRENT).fill(null).map(async (_, i) => { for (let j = 0; j + i < metadataAccounts.length; j += CONCURRENT) { try { await sign( metaplex, new PgWeb3.PublicKey(metadataAccounts[j + i].data.slice(33, 65)) ); } catch (e: any) { console.log(e.message); errorCount++; } finally { progressCount++; PgTerminal.setProgress( (progressCount / metadataAccounts.length) * 100 ); } } }) ); // Hide progress bar setTimeout(() => PgTerminal.setProgress(0), 1000); if (errorCount) { throw new Error( `Failed to sign ${errorCount}/${metadataAccounts.length} NFTs.` ); } term.println( PgTerminal.secondary(`${Emoji.CONFETTI} All NFTs signed successfully.`) ); } }; const sign = async (metaplex: Metaplex, mintPk: PgWeb3.PublicKey) => { await metaplex.nfts().verifyCreator({ mintAddress: mintPk }); };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/sign/index.ts
export * from "./sign";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/upload/assets.ts
import { JsonMetadata } from "@metaplex-foundation/js"; import { SugarUploadScreen } from "./SugarUploadScreen"; import { CacheItem } from "../../utils"; import { PgBytes, PgCommon, PgView } from "../../../../utils/pg"; class AssetPair { name: string; metadata: string; metadata_hash: string; image: string; image_hash: string; animation?: string; animation_hash?: string; constructor( name: string, metadata: string, metadataHash: string, image: string, imageHash: string, animation?: string, animationHash?: string ) { this.name = name; this.metadata = metadata; this.metadata_hash = metadataHash; this.image = image; this.image_hash = imageHash; this.animation = animation; this.animation_hash = animationHash; } intoCacheItem() { return new CacheItem({ name: this.name, metadata_link: this.metadata, metadata_hash: this.metadata_hash, image_link: this.image, image_hash: this.image_hash, animation_link: this.animation, animation_hash: this.animation_hash, onChain: false, }); } } type GetAssetPairsResult = { assetPairs: [number, AssetPair][]; files: File[] }; const COLLECTION_FILENAME = "collection"; export const getAssetPairs = async (): Promise<GetAssetPairsResult> => { const files: File[] | null = await PgView.setModal(SugarUploadScreen, { title: "Upload Assets", }); if (!files) throw new Error("You haven't selected files."); // Sort files based on their name files.sort((a, b) => a.name.localeCompare(b.name)); const fileNames = files.map((f) => f.name); const animationExistsRegex = /^(.+)\.((mp3)|(mp4)|(mov)|(webm)|(glb))$/; // Since there doesn't have to be video for each image/json pair, need to get rid of // invalid file fileNames before entering metadata filename loop for (const fileName in fileNames) { const exec = animationExistsRegex.exec(fileName); if (exec && exec[1] !== COLLECTION_FILENAME && PgCommon.isInt(exec[1])) { throw new Error( `Couldn't parse filename '${fileName}' to a valid index number.` ); } } const metadatafileNames = fileNames.filter((f) => f.toLowerCase().endsWith(".json") ); if (!metadatafileNames.length) { throw new Error("Could not find any metadata .json files."); } const result: GetAssetPairsResult = { assetPairs: [], files }; for (const metadataFileName of metadatafileNames) { const i = metadataFileName.split(".")[0]; const isCollectionIndex = i === COLLECTION_FILENAME; let index; if (isCollectionIndex) index = -1; else if (PgCommon.isInt(i)) index = parseInt(i); else { throw new Error( `Couldn't parse filename '${metadataFileName}' to a valid index number.,` ); } const imgRegex = new RegExp(`^${i}\\.(jpg|jpeg|gif|png)$`, "i"); const imgFileNames = fileNames.filter((f) => imgRegex.test(f)); if (imgFileNames.length !== 1) { throw new Error( isCollectionIndex ? "Couldn't find the collection image filename." : `Couldn't find an image filename at index ${i}.` ); } const imgFileName = imgFileNames[0]; const imgHash = encode(imgFileName); // Need a similar check for animation as above, this one checking if there is // animation on specific index const animationRegex = new RegExp(`^${i}\\.(mp3|mp4|mov|webm|glb)$`, "i"); const animationfileNames = fileNames.filter((f) => animationRegex.test(f)); const animationFileName = animationfileNames.length === 1 ? animationfileNames[0] : undefined; const animationHash = animationFileName ? encode(animationFileName) : undefined; const metadataHash = encode(metadataFileName); const metadata: JsonMetadata = JSON.parse( await files.find((f) => f.name === metadataFileName)!.text() ); const name = metadata.name; if (!name) { throw new Error( `'name' is not specified in metadata file ${metadataFileName}` ); } result.assetPairs.push([ index, new AssetPair( name, metadataFileName, metadataHash, imgFileName, imgHash, animationFileName, animationHash ), ]); } return result; }; /** Encode with SHA-256 hash algorithm. */ const encode = PgBytes.hashSha256;
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/upload/index.ts
export { SugarUploadScreen } from "./SugarUploadScreen"; export * from "./upload";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/upload/upload.ts
import { BundlrStorageDriver, JsonMetadata, sol, toMetaplexFileFromBrowser, UploadMetadataInput, } from "@metaplex-foundation/js"; import { getAssetPairs } from "./assets"; import { loadConfigData, getMetaplex, loadCache } from "../../utils"; import { Emoji } from "../../../../constants"; import { PgCommon, PgTerminal, PgWeb3 } from "../../../../utils/pg"; interface AssetType { image: number[]; metadata: number[]; animation: number[]; } const MAX_TRY = 3; export const processUpload = async (rpcUrl: string | undefined) => { const configData = await loadConfigData(); const term = await PgTerminal.get(); term.println(`[1/3] ${Emoji.ASSETS} Loading assets`); // Get asset pairs const { assetPairs, files } = await getAssetPairs(); // Create/load cache const cache = await loadCache(); // List of indices to upload const indices: AssetType = { image: [], metadata: [], animation: [], }; for (const [index, pair] of assetPairs) { const item = cache.items[index]; if (item) { const imageChanged = item.image_hash !== pair.image_hash || !PgCommon.isUrl(item.image_link); const animationChanged = item.animation_hash !== pair.animation_hash || (!PgCommon.isUrl(item.animation_link ?? "") && pair.animation); const metadataChanged = item.metadata_hash !== pair.metadata_hash || !PgCommon.isUrl(item.metadata_link); if (imageChanged) { // Triggers the image upload item.image_hash = pair.image_hash; item.image_link = ""; indices.image.push(index); } if (animationChanged) { // Triggers the animation upload item.animation_hash = pair.animation_hash; item.animation_link = undefined; indices.animation.push(index); } if (metadataChanged || imageChanged || animationChanged) { // Triggers the metadata upload item.metadata_hash = pair.metadata_hash; item.metadata_link = ""; item.onChain = false; // We need to upload metadata only indices.metadata.push(index); } } else { cache.items[index] = pair.intoCacheItem(); // We need to upload both image/metadata indices.image.push(index); indices.metadata.push(index); // And we might need to upload the animation if (pair.animation) { indices.animation.push(index); } } // Sanity check: verifies that both symbol and seller-fee-basis-points are the // same as the ones in the config file const currentFile = files.find((f) => f.name === pair.metadata); if (!currentFile) throw new Error(`Metadata file ${pair.metadata} not found.`); const metadata: JsonMetadata = JSON.parse(await currentFile.text()); // Symbol check, but only if the asset actually has the value if (metadata.symbol && configData.symbol !== metadata.symbol) { throw new Error( `Mismatch between symbols in config file and metadata file. '${configData.symbol}' != '${metadata.symbol}'` ); } // Seller fee basis points check, but only if the asset actually has the value if ( metadata.sellerFeeBasisPoints && configData.royalties !== metadata.sellerFeeBasisPoints ) { throw new Error( `Mismatch between sellerFeeBasisPoints in config file and metadata file. ${configData.royalties} != ${metadata.sellerFeeBasisPoints}` ); } } term.println(`Found ${assetPairs.length} asset pair(s), uploading files:`); term.println("+--------------------+"); term.println( `| images | ${PgCommon.string(indices.image.length.toString(), { addSpace: { amount: 6 }, })} |` ); term.println( `| metadata | ${PgCommon.string(indices.metadata.length.toString(), { addSpace: { amount: 6 }, })} |` ); if (indices.animation.length) { term.println( `| animation | ${PgCommon.string(indices.animation.length.toString(), { addSpace: { amount: 6 }, })} |` ); } term.println("+--------------------+"); // This should never happen, since every time we update the image file we // need to update the metadata if (indices.image.length > indices.metadata.length) { throw new Error( `There are more image files (${indices.image.length}) to upload than metadata (${indices.metadata.length})` ); } const needUpload = indices.image.length || indices.metadata.length || indices.animation.length; // Ready to upload data if (needUpload) { term.println(`\n[2/3] ${Emoji.COMPUTER} Initializing upload`); // Get metaplex const metaplex = await getMetaplex(rpcUrl); // Upload files term.println( `\n[3/3] ${Emoji.UPLOAD} Uploading files ${ !indices.metadata.length ? "(skipping)" : "" }` ); // Periodically save the cache const saveCacheIntervalId = setInterval(() => cache.syncFile(false), 5000); // Show progress bar PgTerminal.setProgress(0.1); let progressCount = 0; const CONCURRENT = 4; await Promise.all( new Array(CONCURRENT).fill(null).map(async (_, i) => { for (let j = 0; ; j += CONCURRENT) { const currentIndex = indices.metadata[j + i]; if (currentIndex === undefined) break; let metadataIndex = currentIndex !== -1 ? 2 * currentIndex : files.length - 2; let imgIndex = metadataIndex + 1; // metadata and image files could be in reverse order if (!files[metadataIndex].name.endsWith(".json")) { metadataIndex++; imgIndex--; } const metadata: UploadMetadataInput = JSON.parse( await files[metadataIndex].text() ); const imgMetaplexFile = await toMetaplexFileFromBrowser( files[imgIndex] ); // Edit metadata.image = imgMetaplexFile; if (metadata.properties?.files) { for (const k in metadata.properties.files) { metadata.properties.files[k] = { ...metadata.properties.files[k], // TODO: handle animations uri: imgMetaplexFile, }; } } let maxTryIndex = 0; while (true) { try { const { uri, metadata: resultMetadata } = await metaplex .nfts() .uploadMetadata(metadata); // Update and save cache cache.updateItemAtIndex(currentIndex, { image_link: resultMetadata.image, metadata_link: uri, }); progressCount++; PgTerminal.setProgress( (progressCount / indices.metadata.length) * 100 ); break; } catch (e: any) { console.log(e.message); // There is a bug where the amount automatically calculated and sent by the sdk // is not enough and it throws not enough funds error. We are funding it extra // 10_000 lamports and users are able to withdraw their extra balance with // `sugar bundlr withdraw` if ((e.message = "Not enough funds to send data")) { ( (await metaplex.storage().driver()) as BundlrStorageDriver ).fund(sol(10_000 / PgWeb3.LAMPORTS_PER_SOL)); } maxTryIndex++; if (maxTryIndex === MAX_TRY) { cache.updateItemAtIndex(currentIndex, { image_link: "", metadata_link: "", }); await cache.syncFile(); progressCount++; PgTerminal.setProgress( (progressCount / indices.metadata.length) * 100 ); break; } await PgCommon.sleep(500); } } } }) ); // Hide progress bar setTimeout(() => PgTerminal.setProgress(0), 1000); // Sync and refresh the file if it's already open clearInterval(saveCacheIntervalId); await cache.syncFile(); } else { term.println("\n...no files need uploading, skipping remaining steps."); } // Sanity check let count = 0; for (const i in cache.items) { const item = cache.items[i]; const assetPair = assetPairs.find((ap) => ap[0] === parseInt(i))?.[1]; if (!assetPair) throw new Error(`Asset pair at index ${i} not found.`); // We first check that the asset has an animation file; if there is one, // we need to check that the cache item has the link and the link is not empty const missingAnimationLink = assetPair.animation && !item.animation_link; // Only increment the count if the cache item is complete (all links are present) if (!(!item.image_link || !item.metadata_link || missingAnimationLink)) { count++; } } term.println( PgTerminal.bold(`\n${count}/${assetPairs.length} asset pair(s) uploaded.`) ); if (count !== assetPairs.length) { throw new Error("Not all files were uploaded."); } };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/upload/SugarUploadScreen.tsx
import { FC, useCallback, useState } from "react"; import Modal from "../../../../components/Modal"; import UploadArea from "../../../../components/UploadArea"; import { PgCommon } from "../../../../utils/pg"; interface SugarUploadScreenProps { title: string; } export const SugarUploadScreen: FC<SugarUploadScreenProps> = ({ title }) => { const [files, setFiles] = useState<FileList>(); const [error, setError] = useState(""); const onDrop = useCallback(async (uploadFiles: FileList) => { if (uploadFiles.length % 2 === 1) { setError( `Please upload image-metadata pairs. You've selected ${ uploadFiles.length } ${PgCommon.makePlural("file", uploadFiles.length)}.` ); } else { setError(""); } setFiles(uploadFiles); }, []); return ( <Modal buttonProps={{ text: "Continue", disabled: !files || files.length % 2 === 1, onSubmit: () => files, }} title={title} > <UploadArea onDrop={onDrop} error={error} filesLength={files?.length} /> </Modal> ); };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/bundlr/bundlr.ts
import Bundlr from "@bundlr-network/client"; import { BundlrEnpoints } from "../../constants"; import { Emoji } from "../../../../constants"; import { PgConnection, PgSettings, PgTerminal, PgWallet, PgWeb3, } from "../../../../utils/pg"; enum BundlrAction { Balance = 0, Withraw = 1, } // The minimum amount of lamports required for withdraw const LIMIT = 5000; export const processBundlr = async ( rpcUrl: string = PgSettings.connection.endpoint, action: BundlrAction ) => { // Get balance PgTerminal.log( `${BundlrAction.Withraw ? "[1/2]" : "[1/1]"} ${ Emoji.COMPUTER } Retrieving balance` ); const pkStr = PgWallet.current!.publicKey.toBase58(); const cluster = await PgConnection.getCluster(rpcUrl); const bundlr = new Bundlr( cluster === "mainnet-beta" ? BundlrEnpoints.MAINNET : BundlrEnpoints.DEVNET, "solana", PgWallet, { providerUrl: rpcUrl } ); const balance = await bundlr.getBalance(pkStr); PgTerminal.log("\nFunding address:"); PgTerminal.log(` -> pubkey: ${pkStr}`); PgTerminal.log( ` -> lamports: ${balance} (${Emoji.SOL} ${balance.div( PgWeb3.LAMPORTS_PER_SOL )})` ); // Withdraw funds if (action === BundlrAction.Withraw) { PgTerminal.log(`\n${"[2/2]"} ${Emoji.WITHDRAW} Withdrawing funds`); if (balance.isZero()) { PgTerminal.log!("\nNo funds to withdraw."); } else if (balance.minus(LIMIT).gt(0)) { const withdrawBalance = balance.minus(LIMIT); const response = await bundlr.withdrawBalance(withdrawBalance); if (response.status === 200) { PgTerminal.log("Withdraw completed."); } else { PgTerminal.log(`\n${PgTerminal.error("Withdraw failed.")}`); throw new Error(`Failed to complete withdraw (${response.data})`); } } else { PgTerminal.log( `\n${PgTerminal.error("Insufficient balance for withdraw:")}` ); PgTerminal.log( ` -> required balance > ${LIMIT.toString()} (${Emoji.SOL} ${ LIMIT / PgWeb3.LAMPORTS_PER_SOL })` ); } } };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/sugar/commands/bundlr/index.ts
export * from "./bundlr";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/prettier/prettier.ts
import { EventName } from "../../constants"; import { PgCommon } from "../../utils/pg"; import { createCmd } from "../create"; export const prettier = createCmd({ name: "prettier", description: "Format the current file with prettier", run: async () => { await PgCommon.sendAndReceiveCustomEvent(EventName.EDITOR_FORMAT, { lang: "TypeScript", fromTerminal: true, }); }, });
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/prettier/index.ts
export { prettier } from "./prettier";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/deploy/index.ts
export { deploy } from "./deploy";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/deploy/deploy.ts
import { BpfLoaderUpgradeable } from "../../utils/bpf-upgradeable-browser"; import { PgCommand, PgCommon, PgConnection, PgGlobal, PgProgramInfo, PgServer, PgTerminal, PgTx, PgWallet, PgWeb3, } from "../../utils/pg"; import { createCmd } from "../create"; export const deploy = createCmd({ name: "deploy", description: "Deploy your program", run: async () => { PgGlobal.update({ deployState: "loading" }); PgTerminal.log( `${PgTerminal.info( "Deploying..." )} This could take a while depending on the program size and network conditions.` ); PgTerminal.setProgress(0.1); let msg; try { const startTime = performance.now(); const { txHash, closeBuffer } = await processDeploy(); if (txHash) { const timePassed = (performance.now() - startTime) / 1000; PgTx.notify(txHash); msg = `${PgTerminal.success( "Deployment successful." )} Completed in ${PgCommon.secondsToTime(timePassed)}.`; } else if (closeBuffer) { const term = await PgTerminal.get(); const shouldCloseBufferAccount = await term.waitForUserInput( PgTerminal.warning("Cancelled deployment.") + " Would you like to close the buffer account and reclaim SOL?", { confirm: true, default: "yes" } ); if (shouldCloseBufferAccount) { await closeBuffer(); PgTerminal.log(PgTerminal.success("Reclaim successful.")); } else { PgTerminal.log( `${PgTerminal.error( "Reclaim rejected." )} Run \`solana program close --buffers\` to close unused buffer accounts and reclaim SOL.` ); } } } catch (e: any) { const convertedError = PgTerminal.convertErrorMessage(e.message); msg = `Deployment error: ${convertedError}`; return 1; // To indicate error } finally { if (msg) PgTerminal.log(msg + "\n"); PgTerminal.setProgress(0); PgGlobal.update({ deployState: "ready" }); } }, preCheck: [checkWallet, checkProgram], }); /** Check whether the wallet is connected (playground or standard). */ async function checkWallet() { if (!PgWallet.current) { PgTerminal.log("Warning: Wallet is not connected."); PgTerminal.log(PgTerminal.info("Connecting...")); const needsSetup = PgWallet.state === "setup"; const connected = await PgCommand.connect.run(); if (!connected) throw new Error("Wallet must be connected."); PgTerminal.log(""); // When it's the first ever deployment, add extra sleep to give time for // the automatic airdrop request to confirm if (needsSetup) await PgCommon.sleep(2000); } } /** Check whether the state is valid for deployment. */ async function checkProgram() { if (!PgProgramInfo.uuid && !PgProgramInfo.importedProgram?.buffer.length) { PgTerminal.log("Warning: Program is not built."); await PgCommand.build.run(); } if (!PgProgramInfo.pk) { throw new Error( "Program ID not found. Go to 'Build & Deploy' tab and set the program ID." ); } if (!PgProgramInfo.onChain) { throw new Error( `Could not fetch on-chain data. Try using a different RPC provider with '${PgTerminal.bold( "solana config set -u <RPC_URL>" )}' command.` ); } if (!PgProgramInfo.onChain.upgradable) { throw new Error("The program is not upgradable."); } const authority = PgProgramInfo.onChain.authority; const hasAuthority = !authority || authority.equals(PgWallet.current!.publicKey); if (!hasAuthority) { throw new Error(`You don't have the authority to upgrade this program. Program ID: ${PgProgramInfo.pk} Program authority: ${authority} Your address: ${PgWallet.current!.publicKey}`); } } /** Maximum amount of transaction retries */ const MAX_RETRIES = 5; /** Sleep amount multiplier each time a transaction fails */ const SLEEP_MULTIPLIER = 1.8; /** * Deploy the current program. * * @returns the deployment transaction signature if the deployment succeeds */ const processDeploy = async () => { const programPk = PgProgramInfo.pk!; const programBuffer = PgProgramInfo.importedProgram?.buffer ?? (await PgServer.deploy(PgProgramInfo.uuid!)); // Get connection const connection = PgConnection.current; // Create buffer const bufferKp = PgWeb3.Keypair.generate(); const programLen = programBuffer.length; const bufferSize = BpfLoaderUpgradeable.getBufferAccountSize(programLen); const bufferBalance = await connection.getMinimumBalanceForRentExemption( bufferSize ); const wallet = PgWallet.current!; const [pgWallet, standardWallet] = wallet.isPg ? [wallet, null] : [PgWallet.create(PgWallet.accounts[0]), wallet]; // Decide whether it's an initial deployment or an upgrade and calculate // how much SOL user needs before creating the buffer. const [programExists, userBalance] = await Promise.all([ connection.getAccountInfo(programPk), connection.getBalance(wallet.publicKey), ]); // Balance required to deploy/upgrade (without fees) const requiredBalanceWithoutFees = programExists ? bufferBalance : 3 * bufferBalance; if (userBalance < requiredBalanceWithoutFees) { const airdropAmount = PgCommon.getAirdropAmount(connection.rpcEndpoint); if (airdropAmount !== null) { const term = await PgTerminal.get(); const msg = programExists ? `Initial deployment costs ${PgTerminal.bold( PgCommon.lamportsToSol(requiredBalanceWithoutFees).toFixed(2) )} SOL but you have ${PgTerminal.bold( PgCommon.lamportsToSol(userBalance).toFixed(2) )} SOL. ${PgTerminal.bold( PgCommon.lamportsToSol(bufferBalance).toFixed(2) )} SOL will be refunded at the end.` : `Upgrading costs ${PgTerminal.bold( PgCommon.lamportsToSol(bufferBalance).toFixed(2) )} SOL but you have ${PgTerminal.bold( PgCommon.lamportsToSol(userBalance).toFixed(2) )} SOL. ${PgTerminal.bold( PgCommon.lamportsToSol(bufferBalance).toFixed(2) )} SOL will be refunded at the end.`; term.println(`Warning: ${msg}`); const confirmed = await term.waitForUserInput( "You don't have enough SOL to complete the deployment. Would you like to request an airdrop?", { confirm: true, default: "yes" } ); if (!confirmed) throw new Error("Insufficient balance"); await PgCommand.solana.run("airdrop", airdropAmount.toString()); } } // If deploying from a standard wallet, transfer the required lamports for // deployment to the first playground wallet, which allows to deploy without // asking for approval. if (standardWallet) { // Transfer extra 0.1 SOL for fees (doesn't have to get used) const requiredBalance = requiredBalanceWithoutFees + PgWeb3.LAMPORTS_PER_SOL / 10; const transferIx = PgWeb3.SystemProgram.transfer({ fromPubkey: standardWallet.publicKey, toPubkey: pgWallet.publicKey, lamports: requiredBalance, }); const transferTx = new PgWeb3.Transaction().add(transferIx); await sendAndConfirmTxWithRetries( () => PgTx.send(transferTx), async () => { const currentBalance = await connection.getBalance( standardWallet.publicKey ); return currentBalance < userBalance - requiredBalance; } ); } // Create buffer await sendAndConfirmTxWithRetries( async () => { return await BpfLoaderUpgradeable.createBuffer( bufferKp, bufferBalance, programLen, { wallet: pgWallet } ); }, async () => { const bufferAcc = await connection.getAccountInfo(bufferKp.publicKey); return !!bufferAcc; } ); console.log("Buffer pk:", bufferKp.publicKey.toBase58()); const closeBuffer = async () => { await BpfLoaderUpgradeable.closeBuffer(bufferKp.publicKey); }; // Load buffer const loadBufferResult = await loadBufferWithControl( bufferKp.publicKey, programBuffer, { wallet: pgWallet, onWrite: (offset) => PgTerminal.setProgress((offset / programLen) * 100), onMissing: (missingCount) => { PgTerminal.log( `Warning: ${PgTerminal.bold( missingCount.toString() )} ${PgCommon.makePlural( "transaction", missingCount )} not confirmed, retrying...` ); }, } ); if (loadBufferResult.cancelled) { return { closeBuffer: async () => { await BpfLoaderUpgradeable.closeBuffer(bufferKp.publicKey, { wallet: pgWallet, }); }, }; } // If deploying from a standard wallet, transfer the buffer authority // to the standard wallet before deployment, otherwise it doesn't // pass on-chain checks. if (standardWallet) { await sendAndConfirmTxWithRetries( async () => { return await BpfLoaderUpgradeable.setBufferAuthority( bufferKp.publicKey, standardWallet.publicKey, { wallet: pgWallet } ); }, async () => { const bufferAcc = await connection.getAccountInfo(bufferKp.publicKey); const isBufferAuthority = bufferAcc?.data .slice(5, 37) .equals(standardWallet.publicKey.toBuffer()); return !!isBufferAuthority; } ); } // Deploy/upgrade let txHash; try { txHash = await sendAndConfirmTxWithRetries( async () => { if (!programExists) { // First deploy needs keypair const programKp = PgProgramInfo.kp; if (!programKp) { // TODO: Break out of the retries throw new Error( "Initial deployment needs a keypair but you've only provided a public key." ); } // Check whether customPk and programPk matches if (!programKp.publicKey.equals(programPk)) { // TODO: Break out of the retries throw new Error( [ "Entered program id doesn't match program id derived from program's keypair. Initial deployment can only be done from a keypair.", "You can fix this in 3 different ways:", `1. Remove the custom program id from ${PgTerminal.bold( "Program Credentials" )}`, "2. Import the program keypair for the current program id", "3. Create a new program keypair", ].join("\n") ); } const programSize = BpfLoaderUpgradeable.getBufferAccountSize( BpfLoaderUpgradeable.BUFFER_PROGRAM_SIZE ); const programBalance = await connection.getMinimumBalanceForRentExemption(programSize); return await BpfLoaderUpgradeable.deployProgram( programKp, bufferKp.publicKey, programBalance, programLen * 2 ); } else { // Upgrade return await BpfLoaderUpgradeable.upgradeProgram( programPk, bufferKp.publicKey ); } }, async () => { // Also check whether the buffer account was closed because // `PgTx.confirm` can be unreliable const bufferAcc = await connection.getAccountInfo(bufferKp.publicKey); return !bufferAcc; } ); } catch (e) { await closeBuffer(); throw e; } console.log("Deploy/upgrade tx hash:", txHash); return { txHash }; }; /** Load buffer with the ability to pause, resume and cancel on demand. */ const loadBufferWithControl = ( ...args: Parameters<typeof BpfLoaderUpgradeable["loadBuffer"]> ) => { return new Promise< | { cancelled: true; success?: never; } | { cancelled?: never; success: true; } >(async (res) => { const abortController = new AbortController(); args[2] = { ...args[2], abortController }; const term = await PgTerminal.get(); const handle = async () => { if (abortController.signal.aborted) { await term.executeFromStr("yes"); } else { abortController.abort(); const shouldContinue = await term.waitForUserInput( "Continue deployment?", { confirm: true, default: "yes" } ); dispose(); if (shouldContinue) { PgGlobal.deployState = "loading"; loadBufferWithControl(...args).then(res); } else { PgGlobal.deployState = "cancelled"; res({ cancelled: true }); } } }; let prevState = PgGlobal.deployState; const { dispose } = PgGlobal.onDidChangeDeployState((state) => { if ( prevState !== state && (prevState === "paused" || state === "paused") ) { handle(); } prevState = state; }); await BpfLoaderUpgradeable.loadBuffer(...args); if (!abortController.signal.aborted) { dispose(); res({ success: true }); } }); }; /** * Send and confirm transaction with retries based on `checkConfirmation` * condition. * * @param sendTx send transaction callback * @param checkConfirmation only confirm the transaction if this callback returns truthy * @returns the transaction signature */ const sendAndConfirmTxWithRetries = async ( sendTx: () => Promise<string>, checkConfirmation: () => Promise<boolean> ) => { let sleepAmount = 1000; let errMsg; for (let i = 0; i < MAX_RETRIES; i++) { try { const txHash = await sendTx(); const result = await PgTx.confirm(txHash); if (!result?.err) return txHash; if (await checkConfirmation()) return txHash; } catch (e: any) { errMsg = e.message; console.log(errMsg); await PgCommon.sleep(sleepAmount); sleepAmount *= SLEEP_MULTIPLIER; } } throw new Error( `Exceeded maximum amount of retries (${PgTerminal.bold( MAX_RETRIES.toString() )}). This might be an RPC related issue. Consider changing the endpoint from the settings. Reason: ${errMsg}` ); };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/spl-token/spl-token.ts
import { PgPackage } from "../../utils/pg"; import { createCmd } from "../create"; import { isPgConnected } from "../validation"; export const splToken = createCmd({ name: "spl-token", description: "Commands for interacting with SPL Tokens", run: async (input) => { const { runSplToken } = await PgPackage.import("spl-token-cli", { log: true, }); await runSplToken(input.raw); }, preCheck: isPgConnected, });
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/spl-token/index.ts
export { splToken } from "./spl-token";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/solana/solana.ts
import { PgPackage } from "../../utils/pg"; import { createCmd } from "../create"; import { isPgConnected } from "../validation"; export const solana = createCmd({ name: "solana", description: "Commands for interacting with Solana", run: async (input) => { const { runSolana } = await PgPackage.import("solana-cli", { log: true, }); await runSolana(input.raw); }, preCheck: isPgConnected, });
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/solana/index.ts
export { solana } from "./solana";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/clear/index.ts
export { clear } from "./clear";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/clear/clear.ts
import { PgTerminal } from "../../utils/pg"; import { createCmd } from "../create"; export const clear = createCmd({ name: "clear", description: "Clear terminal", run: () => PgTerminal.run({ clear: [{ full: true }] }), });
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/run-and-test/run-and-test.ts
import { PgClientImporter, PgCommon, PgExplorer, PgLanguage, PgTerminal, } from "../../utils/pg"; import { createArgs, createCmd } from "../create"; /** * Crate common arguments. * * @param parentPath path that is expected to be run inside of * @returns the common arguments */ const createCommonArgs = (parentPath: string) => createArgs([ { name: "paths", optional: true, multiple: true, values: () => { return PgExplorer.getAllFiles() .map(([path]) => path) .filter(PgLanguage.getIsPathJsLike) .map(PgExplorer.getRelativePath) .filter((path) => path.startsWith(parentPath)) .map((path) => path.replace(PgCommon.appendSlash(parentPath), "")); }, }, ]); export const run = createCmd({ name: "run", description: "Run script(s)", args: createCommonArgs(PgExplorer.PATHS.CLIENT_DIRNAME), run: (input) => processCommon({ paths: input.args.paths, isTest: false }), }); export const test = createCmd({ name: "test", description: "Run test(s)", args: createCommonArgs(PgExplorer.PATHS.TESTS_DIRNAME), run: (input) => processCommon({ paths: input.args.paths, isTest: true }), }); /** * Process `run` or `test` command. * * @param params - * - `paths`: File paths to run or test * - `isTest`: Whether to execute as test */ const processCommon = async (params: { paths: string[] | undefined; isTest: boolean; }) => { const { paths, isTest } = params; PgTerminal.log(PgTerminal.info(`Running ${isTest ? "tests" : "client"}...`)); const { PgClient } = await PgClientImporter.import(); const folderPath = isTest ? PgExplorer.PATHS.TESTS_DIRNAME : PgExplorer.PATHS.CLIENT_DIRNAME; // Run the script only at the given path if (paths?.length) { // The path can be a file name that's expected to run inside the `client` // or `tests` directory based on the command that's running for (const path of paths) { const code = PgExplorer.getFileContent(path) ?? PgExplorer.getFileContent(PgCommon.joinPaths(folderPath, path)); if (!code) throw new Error(`File '${path}' doesn't exist`); const fileName = PgExplorer.getItemNameFromPath(path); if (!PgLanguage.getIsPathJsLike(fileName)) { throw new Error(`File '${fileName}' is not a script file`); } await PgClient.execute({ fileName, code, isTest }); } return; } // Create default client/test if the folder is empty const folder = PgExplorer.getFolderContent(folderPath); if (!folder.files.length && !folder.folders.length) { let DEFAULT; if (isTest) { PgTerminal.log(PgTerminal.info("Creating default test...")); DEFAULT = DEFAULT_TEST; } else { PgTerminal.log(PgTerminal.info("Creating default client...")); DEFAULT = DEFAULT_CLIENT; } const [fileName, code] = DEFAULT; await PgExplorer.newItem(PgCommon.joinPaths(folderPath, fileName), code); return await PgClient.execute({ fileName, code, isTest }); } // Run all files inside the folder for (const fileName of folder.files.filter(PgLanguage.getIsPathJsLike)) { const code = PgExplorer.getFileContent( PgCommon.joinPaths(folderPath, fileName) )!; await PgClient.execute({ fileName, code, isTest }); } }; /** Default client files*/ const DEFAULT_CLIENT = [ "client.ts", `// Client console.log("My address:", pg.wallet.publicKey.toString()); const balance = await pg.connection.getBalance(pg.wallet.publicKey); console.log(\`My balance: \${balance / web3.LAMPORTS_PER_SOL} SOL\`); `, ]; /** Default test files */ const DEFAULT_TEST = [ "index.test.ts", `describe("Test", () => { it("Airdrop", async () => { // Fetch my balance const balance = await pg.connection.getBalance(pg.wallet.publicKey); console.log(\`My balance is \${balance} lamports\`); // Airdrop 1 SOL const airdropAmount = 1 * web3.LAMPORTS_PER_SOL; const txHash = await pg.connection.requestAirdrop( pg.wallet.publicKey, airdropAmount ); // Confirm transaction await pg.connection.confirmTransaction(txHash); // Fetch new balance const newBalance = await pg.connection.getBalance(pg.wallet.publicKey); console.log(\`New balance is \${newBalance} lamports\`); // Assert balances assert(balance + airdropAmount === newBalance); }); }); `, ];
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/run-and-test/index.ts
export { run, test } from "./run-and-test";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/anchor/anchor.ts
import { PgPackage } from "../../utils/pg"; import { createCmd } from "../create"; import { isPgConnected } from "../validation"; export const anchor = createCmd({ name: "anchor", description: "Anchor CLI", run: async (input) => { const { runAnchor } = await PgPackage.import("anchor-cli", { log: true, }); await runAnchor(input.raw); }, preCheck: isPgConnected, });
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/anchor/index.ts
export { anchor } from "./anchor";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/build/index.ts
export { build } from "./build";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/build/build.ts
import { ExplorerFiles, PgCommon, PgExplorer, PgGlobal, PgPackage, PgProgramInfo, PgServer, PgSettings, PgTerminal, PgWeb3, TupleFiles, } from "../../utils/pg"; import { createCmd } from "../create"; export const build = createCmd({ name: "build", description: "Build your program", run: async () => { PgGlobal.update({ buildLoading: true }); PgTerminal.log(PgTerminal.info("Building...")); let msg; try { const output = await processBuild(); msg = improveOutput(output.stderr); } catch (e: any) { const convertedError = PgTerminal.convertErrorMessage(e.message); msg = `Build error: ${convertedError}`; } finally { PgTerminal.log(msg + "\n"); PgGlobal.update({ buildLoading: false }); } }, }); /** * Compile the current project. * * @returns build output from stderr(not only errors) */ const processBuild = async () => { const buildFiles = getBuildFiles(); const pythonFiles = buildFiles.filter(([fileName]) => fileName.toLowerCase().endsWith(".py") ); if (pythonFiles.length > 0) { return await buildPython(pythonFiles); } return await buildRust(buildFiles); }; /** * Build rust files and return the output. * * @param files Rust files from `src/` * @returns Build output from stderr(not only errors) */ const buildRust = async (files: TupleFiles) => { if (!files.length) throw new Error("Couldn't find any Rust files."); const resp = await PgServer.build({ files, uuid: PgProgramInfo.uuid, flags: PgSettings.build.flags, }); // Update program info PgProgramInfo.update({ uuid: resp.uuid ?? undefined, idl: resp.idl, }); return { stderr: resp.stderr }; }; /** * Convert Python files into Rust with seahorse-compile-wasm and run `_buildRust`. * * @param pythonFiles Python files in `src/` * @returns Build output from stderr(not only errors) */ const buildPython = async (pythonFiles: TupleFiles) => { const { compileSeahorse } = await PgPackage.import("seahorse-compile"); const rustFiles = pythonFiles.flatMap(([path, content]) => { const seahorseProgramName = PgExplorer.getItemNameFromPath(path).split(".py")[0]; const compiledContent = compileSeahorse(content, seahorseProgramName); if (compiledContent.length === 0) { throw new Error("Seahorse compile failed"); } // Seahorse compile outputs a flattened array like [filepath, content, filepath, content] const files: TupleFiles = []; for (let i = 0; i < compiledContent.length; i += 2) { const path = compiledContent[i]; let content = compiledContent[i + 1]; // The build server detects #[program] to determine if Anchor // Seahorse (without rustfmt) outputs # [program] content = content.replace("# [program]", "#[program]"); files.push([path, content]); } return files; }); return await buildRust(rustFiles); }; /** * Get the files necessary for the build process. * * @returns the necessary data for the build request */ const getBuildFiles = () => { let programPkStr = PgProgramInfo.getPkStr(); if (!programPkStr) { const kp = PgWeb3.Keypair.generate(); PgProgramInfo.update({ kp }); programPkStr = kp.publicKey.toBase58(); } const updateIdRust = (content: string) => { let updated = false; const rustDeclareIdRegex = /^(([\w]+::)*)declare_id!\("(\w*)"\)/gm; const newContent = content.replace(rustDeclareIdRegex, (match) => { const res = rustDeclareIdRegex.exec(match); if (!res) return match; updated = true; // res[1] could be solana_program:: or undefined return (res[1] ?? "\n") + `declare_id!("${programPkStr}")`; }); return { content: newContent, updated }; }; const updateIdPython = (content: string) => { let updated = false; const pythonDeclareIdRegex = /^declare_id\(("|')(\w*)("|')\)/gm; const newContent = content.replace(pythonDeclareIdRegex, (match) => { const res = pythonDeclareIdRegex.exec(match); if (!res) return match; updated = true; return `declare_id('${programPkStr}')`; }); return { content: newContent, updated }; }; const getUpdatedProgramIdContent = (path: string) => { let content = files[path].content; let updated = false; if (content) { if (path.endsWith(".rs")) { const updateIdResult = updateIdRust(content); content = updateIdResult.content; updated = updateIdResult.updated; } else if (path.endsWith(".py")) { const updateIdResult = updateIdPython(content); content = updateIdResult.content; updated = updateIdResult.updated; } } return { content, updated }; }; // Prioritise files where we are likely to find a rust `declare_id!` const prioritiseFilePaths = (files: ExplorerFiles) => { const prioritised: Array<string> = []; for (const path in files) { if (path.endsWith("lib.rs") || path.endsWith("id.rs")) { prioritised.unshift(path); } else { prioritised.push(path); } } return prioritised; }; const files = PgExplorer.files; const prioritisedFilePaths = prioritiseFilePaths(files); const buildFiles: TupleFiles = []; let alreadyUpdatedId = false; for (const path of prioritisedFilePaths) { if (!path.startsWith(PgExplorer.getCurrentSrcPath())) continue; let content = files[path].content; if (!alreadyUpdatedId) { const updateIdResult = getUpdatedProgramIdContent(path); content = updateIdResult.content; alreadyUpdatedId = updateIdResult.updated; } if (!content) continue; // Remove the workspace from path because build only needs /src const buildPath = PgCommon.joinPaths( PgExplorer.PATHS.ROOT_DIR_PATH, PgExplorer.getRelativePath(path) ); buildFiles.push([buildPath, content]); } return buildFiles; }; /** * Improve build output that is returned from the build request. * * @param output build output(stderr) * @returns the improved output */ const improveOutput = (output: string) => { output = output // Blocking "waiting for file lock on package cache" .replaceAll("Blocking waiting for file lock on package cache\n", "") // Remove full paths .replace(/(\S*\/)src/gm, (match, head) => match.replace(head, "")) .replace(/\s\(\/home.+?(?=\s)/gm, "") .replace(/(\/home\/\w+)\//gm, (match, home) => match.replace(home, "~")) // Remove compiling output .replace(/\s*Compiling\ssolpg.*/, "") // Replace `solpg` name with the current workspace name .replaceAll("solpg", PgExplorer.currentWorkspaceName ?? "solpg") // Remove stack size error .replace(/^\s*Error:\sFunction.*\n/gm, "") // Remove nightly macro backtrace .replaceAll( "(in Nightly builds, run with -Z macro-backtrace for more info)", "" ) // Remove `Some errors have detailed explanations: E0412, E0432, E0433.` .replace(/Some\serrors\shave\sdetailed\sexplanations:.*/, ""); // Remove uuid from folders const uuid = PgProgramInfo.uuid; if (uuid) output = output.replace(new RegExp(`${uuid}\\/?`, "gm"), ""); // Remove `rustc` error line let startIndex = output.indexOf("For more"); if (startIndex !== -1) { const endIndex = output.indexOf("\n", startIndex); output = output.substring(0, startIndex) + output.substring(endIndex + 1); } // Remove whitespace before `rustc` finished text startIndex = output.indexOf("Finished release"); if (startIndex !== -1) { const whiteSpaceStartIndex = startIndex - 7; // 7 is the most amount of whitespace output = output.substring(0, whiteSpaceStartIndex) + // Until whitespace start output.substring(whiteSpaceStartIndex, startIndex).replaceAll(" ", "") + PgTerminal.success("Build successful. ") + "Completed" + output.substring(output.indexOf(" in", startIndex)).replace("\n", ".\n"); // Time passed } output = output.substring(0, output.length - 1); // Improve errors if (PgSettings.build.improveErrors) { const MAX_ERROR_AMOUNT = 3; const errorIndices = PgCommon.matchAll(output, /error[:[]/) .map((match) => match.index) .filter(PgCommon.isNonNullish); if (errorIndices.length) { const errors = errorIndices .map((errorIndex, i) => output.slice(errorIndex, errorIndices[i + 1])) .filter((err) => !err.includes("could not compile")); // Hide common useless errors i.e. some errors such as: // ``` // error[E0432]: unresolved import `crate` // --> src/lib.rs:7:1 // | // 7 | #[program] // | ^^^^^^^^^^ could not find `__client_accounts_initialize` in the crate root // ``` // // Macro errors like the above are not the cause of the error, they are a // symptom of another error. const HIDDEN_PATTERNS = [ "__client_accounts", "__cpi_client_accounts", /`\S*Bumps`/, ]; const hiddenErrors = errors.reduce((acc, cur) => { const isHidden = HIDDEN_PATTERNS.some((pat) => { return typeof pat === "string" ? cur.includes(pat) : pat.test(cur); }); if (isHidden) acc.push(cur); return acc; }, [] as string[]); // Prioritize the most common errors, order matters const prioritizedErrors: string[] = []; for (const error of errors) { if (hiddenErrors.includes(error)) continue; if (error.includes("cannot find")) prioritizedErrors.unshift(error); } prioritizedErrors.reverse(); const remainingErrors = errors.filter( (err) => !prioritizedErrors.includes(err) && !hiddenErrors.includes(err) ); const displayErrors = prioritizedErrors.concat(remainingErrors); // Output should be overridden only in the case of display errors length // being non-zero if (displayErrors.length) { output = displayErrors.reduce( (acc, cur, i) => (i < MAX_ERROR_AMOUNT ? acc + cur : acc), "" ); if (displayErrors.length > MAX_ERROR_AMOUNT) { output += [ "Note: This is a shorter version of the error logs to make it easier to debug.", `Currently ${PgTerminal.bold( MAX_ERROR_AMOUNT.toString() )} errors are displayed but there are ${PgTerminal.bold( displayErrors.length.toString() )} errors.`, 'Disable "Improve build errors" setting to see the full error output.', ].join(" "); } } } } return output; };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/rustfmt/rustfmt.ts
import { EventName } from "../../constants"; import { PgCommon } from "../../utils/pg"; import { createCmd } from "../create"; export const rustfmt = createCmd({ name: "rustfmt", description: "Format the current file with rustfmt", run: async () => { await PgCommon.sendAndReceiveCustomEvent(EventName.EDITOR_FORMAT, { lang: "Rust", fromTerminal: true, }); }, });
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/rustfmt/index.ts
export { rustfmt } from "./rustfmt";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/connect/connect.ts
import { PgCommon, PgTerminal, PgView, PgWallet } from "../../utils/pg"; import { createArgs, createCmd } from "../create"; export const connect = createCmd({ name: "connect", description: "Toggle connection to Playground Wallet", args: createArgs([ { name: "wallet", optional: true, values: () => PgWallet.standardWallets.map((w) => w.adapter.name.toLowerCase()), }, ]), run: async (input) => { switch (PgWallet.state) { case "pg": { const isOther = await toggleStandardIfNeeded(input.args.wallet); if (!isOther) { PgWallet.state = "disconnected"; PgTerminal.log(PgTerminal.bold("Disconnected.")); } await confirmDisconnect(); return true; } case "sol": { if (!PgWallet.current) { throw new Error("Not connected"); } if (PgWallet.current.isPg) { throw new Error("Current wallet is not a Solana wallet"); } const isOther = await toggleStandardIfNeeded(input.args.wallet); if (!isOther) { await PgWallet.current.disconnect(); PgWallet.state = "pg"; PgTerminal.log( PgTerminal.bold(`Disconnected from ${PgWallet.current.name}.`) ); } await confirmDisconnect(); return true; } case "disconnected": { const isOther = await toggleStandardIfNeeded(input.args.wallet); if (!isOther) { PgWallet.state = "pg"; PgTerminal.log(PgTerminal.success("Connected.")); } await confirmConnect(); return true; } case "setup": { const { Setup } = await import("../../components/Wallet/Modals/Setup"); const setupCompleted = await PgView.setModal<boolean>(Setup); if (setupCompleted) { const isOther = await toggleStandardIfNeeded(input.args.wallet); if (!isOther) PgWallet.state = "pg"; PgTerminal.log(PgTerminal.success("Setup completed.")); await confirmConnect(); } else { PgTerminal.log(PgTerminal.error("Setup rejected.")); } return !!setupCompleted; } } }, }); /** * Connect to or disconnect from a standard wallet based on given input. * * @param inputWalletName wallet name from the command input * @returns whether the connected to a standard wallet */ const toggleStandardIfNeeded = async (inputWalletName: string | undefined) => { if (!inputWalletName) return false; const wallet = PgWallet.standardWallets.find((wallet) => { return wallet.adapter.name.toLowerCase() === inputWalletName.toLowerCase(); }); if (!wallet) { throw new Error(`Given wallet '${inputWalletName}' is not detected`); } // The given wallet name could be different, e.g. lowercase const walletName = wallet.adapter.name; // Check whether the wallet is already connected if (!wallet.adapter.connected) { await wallet.adapter.connect(); // Set the standard wallet name to derive the standard wallet PgWallet.standardName = walletName; PgWallet.state = "sol"; PgTerminal.log(PgTerminal.success(`Connected to ${walletName}.`)); } else { await wallet.adapter.disconnect(); PgWallet.state = "pg"; PgTerminal.log(PgTerminal.bold(`Disconnected from ${walletName}.`)); } return true; }; /** Wait until the wallet is connected. */ const confirmConnect = async () => { await PgCommon.tryUntilSuccess(() => { if (!PgWallet.current) throw new Error(); }, 50); }; /** Wait until the wallet is disconnected. */ const confirmDisconnect = async () => { await PgCommon.tryUntilSuccess(() => { if (PgWallet.current) throw new Error(); }, 50); };
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/connect/index.ts
export { connect } from "./connect";
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/help/help.ts
import { formatList, PgCommandManager, PgTerminal } from "../../utils/pg"; import { createCmd } from "../create"; export const help = createCmd({ name: "help", description: "Print help message", run: () => { const cmds = Object.values(PgCommandManager.all); PgTerminal.log("Commands:\n\n" + formatList(cmds)); }, });
0
solana_public_repos/solana-playground/solana-playground/client/src/commands
solana_public_repos/solana-playground/solana-playground/client/src/commands/help/index.ts
export { help } from "./help";
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/common.ts
import { ClientPackageName, MergeUnion, PgCommon, PgLanguage, PgView, TupleFiles, ValueOf, } from "../utils/pg"; import { SelectProgram } from "./SelectProgram"; /** Map of dependency name -> version */ type Dependencies = { [dependencyName: string]: string }; /** Import statement regular expression with multi-line support */ export const IMPORT_STATEMENT_REGEX = /import(.|\n)*?["|'].*["|'](;?)/; /** * Add the given content after the regular expression. * * @param content original content * @param afterRegex add after this regular expression * @param newContent new content to add * @param opts options * - `firstOccurance`: Add after the first occurance of the regex(defaults to last) * @returns the content with the new content added */ export const addAfter = ( content: string, afterRegex: RegExp, newContent: string, opts?: { firstOccurance?: boolean } ) => { const occuranceIndex = opts?.firstOccurance ? 0 : -1; const match = PgCommon.matchAll(content, afterRegex).at(occuranceIndex); const afterStartIndex = (match?.index ?? 0) + (match?.at(0)?.length ?? 0) + 1; content = content.slice(0, afterStartIndex) + newContent + "\n" + content.slice(afterStartIndex); return content; }; /** * Get `Cargo.toml` dependencies from the given files. * * @param files all files * @returns the dependency list */ export const getRustDependencies = async (files: TupleFiles) => { const versions = await getVersions("crates"); const getVersion = (crateName: string) => versions[crateName] ?? "*"; const dependencies: Dependencies = {}; const rustContents = files .filter(([path]) => path.endsWith(".rs")) .map(([_, content]) => content); for (const content of rustContents) { for (const crateName of CRATES.importable) { const dependencyName = PgCommon.toKebabFromSnake(crateName); if ( !dependencies[dependencyName] && new RegExp(`${crateName}::`, "gm").test(content) ) { dependencies[dependencyName] = getVersion(dependencyName); } } } return Object.entries(dependencies).reduce((acc, [name, version]) => { return acc + `\n${name} = "${version}"`; }, "[dependencies]"); }; /** * Get `package.json` dependencies from the given files. * * @param files all files * @returns the dependency list */ export const getJSDependencies = async (files: TupleFiles) => { const versions = await getVersions("packages"); const getVersion = (packageName: string) => versions[packageName] ?? "*"; const dependencies: Dependencies = {}; const jsContents = files .filter(([path]) => PgLanguage.getIsPathJsLike(path)) .map(([_, content]) => content); for (const content of jsContents) { // Importables for (const packageName of PACKAGES.importable) { if ( !dependencies[packageName] && new RegExp(`("|')${packageName}("|')`, "gm").test(content) ) { dependencies[packageName] = getVersion(packageName); } } // Globals for (const packageName of Object.keys(getGlobalPackages(content))) { dependencies[packageName] = getVersion(packageName); } } const devDependencies: Dependencies = { "@types/bn.js": "^5.1.1", "@types/chai": "^4.3.5", "@types/mocha": "^10.0.1", chai: "^4.3.8", mocha: "^10.2.0", prettier: "^3.0.2", "ts-mocha": "^10.0.0", typescript: "^5.2.2", }; return PgCommon.prettyJSON({ dependencies, devDependencies }).slice(2, -2); }; /** * Get a map of names to versions. * * @param kind `crates` or `packages` * @returns versions map */ const getVersions = async ( kind: "crates" | "packages" ): Promise<Record<string, string>> => { return await PgCommon.fetchJSON(`/${kind}/versions.json`); }; /** * Add imports for files that use Playground globals. * * @param content JS/TS code * @returns the content with the added imports */ export const addImports = (content: string) => { // Remove the "No imports needed:..." comment const noImportsStartIndex = content.indexOf("// No imports needed"); if (noImportsStartIndex !== -1) { const noImportsEndIndex = noImportsStartIndex + content.slice(noImportsStartIndex).indexOf("\n"); content = content.slice(0, noImportsStartIndex) + content.slice(noImportsEndIndex + 1); } // Add imports for Playground globals const globalPackages = getGlobalPackages(content); for (const [packageName, importStyle] of Object.entries(globalPackages)) { const style = importStyle as Partial<MergeUnion<typeof importStyle>>; const importStyleText = style.as ? `* as ${style.as}` : style.named ? `{ ${style.named} }` : style.default; content = `import ${importStyleText} from "${packageName}";\n` + content; } return content; }; /** * Get global packages that are used in the given content. * * @param content JS/TS code * @returns a map of package name to import style */ const getGlobalPackages = (content: string) => { const packages: Record<string, ValueOf<typeof PACKAGES["global"]>> = {}; for (const [_packageName, importStyle] of PgCommon.entries(PACKAGES.global)) { if (PACKAGES_MAP[_packageName] === null) continue; const packageName = PACKAGES_MAP[_packageName] ?? _packageName; const style = importStyle as Partial<MergeUnion<typeof importStyle>>; const name = style.as ?? style.named ?? style.default; const accessors = [name + ".", name + "("]; for (const accessor of accessors) { if (!packages[packageName] && content.includes(accessor)) { packages[packageName] = importStyle; } } } return packages; }; /** Map packages to a different package on exports or completely ignore them */ const PACKAGES_MAP: { [K in ClientPackageName]?: ClientPackageName | null } = { buffer: null, // No need to import }; /** * Show select program modal. * * @param programNames program names to select from * @throws if the user cancels the selection * @returns the selected program name */ export const selectProgram = async (programNames: string[]) => { const programName: string | null = await PgView.setModal(SelectProgram, { programNames, }); if (!programName) throw new Error("Program not selected"); return programName; }; /** * Convert the given `files` to playground layout. * * @param files files with the framework layout * @returns the files with playground layout */ export const convertToPlaygroundCommon = (files: TupleFiles) => { const pgFiles: TupleFiles = []; for (const [path, content] of files) { // */programs/*/src/**/*.rs -> src/**/*.rs const programPathResult = /(src)(?!.*src\/).*\.rs$/.exec(path); if (programPathResult) { const programFilePath = programPathResult[0]; pgFiles.push([programFilePath, content]); continue; } // */client/**/*.ts -> client/**/*.ts const clientPathResult = /(client)(?!.*client\/).*\.(js|ts)$/.exec(path); if (clientPathResult) { const clientFilePath = clientPathResult[0]; pgFiles.push([clientFilePath, content]); continue; } // */tests/**/*.ts -> tests/**/*.test.ts const testPathResult = /(tests)(?!.*tests\/).*\.(js|ts)$/.exec(path); if (testPathResult) { const testPath = testPathResult[0].replace( /(\.test)?\.(js|ts)$/, ".test.ts" ); pgFiles.push([testPath, content]); continue; } } return pgFiles; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/index.ts
import { anchor } from "./anchor"; import { native } from "./native"; import { seahorse } from "./seahorse"; /** All available program frameworks, order matters */ export const FRAMEWORKS = [native, anchor, seahorse];
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/create.ts
import { Framework, FrameworkImpl, PgCommon } from "../utils/pg"; /** * Create a framework with inferred types. * * @param framework framework to create * @returns the framework with inferred types */ export const createFramework = <N extends string>( framework: FrameworkImpl<N> ) => { const folderPath = `./${PgCommon.toKebabFromTitle(framework.name)}/`; framework.importFiles ??= () => import(folderPath + "files"); framework.importFromPlayground ??= async () => { const { convertFromPlayground } = await import(folderPath + "from"); const { default: readme } = await import(folderPath + "from.md"); return { convertFromPlayground, readme }; }; framework.importToPlayground ??= () => import(folderPath + "to"); return framework as Framework<N>; };
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/SelectProgram.tsx
import { FC, useState } from "react"; import styled, { css } from "styled-components"; import Modal from "../components/Modal"; import Text from "../components/Text"; import { Info } from "../components/Icons"; interface SelectProgramProps { /** Program names to select from */ programNames: string[]; } export const SelectProgram: FC<SelectProgramProps> = ({ programNames }) => { const [selected, setSelected] = useState<string | null>(null); return ( <Modal title="Select the program to import" buttonProps={{ text: "Select", onSubmit: () => selected, }} > <Content> <Text icon={<Info color="info" />}> Multiple programs have been found but playground currently supports one program per project. </Text> <ProgramsWrapper> {programNames.map((name) => ( <Program key={name} isSelected={name === selected} onClick={() => setSelected((s) => (s === name ? null : name))} > {name} </Program> ))} </ProgramsWrapper> </Content> </Modal> ); }; const Content = styled.div` max-width: 32rem; `; const ProgramsWrapper = styled.div` margin-top: 1rem; `; const Program = styled.div<{ isSelected: boolean }>` ${({ theme, isSelected }) => css` margin: 0.75rem 0; padding: 0.5rem 1rem; border: 1px solid ${theme.colors.default.border}; border-radius: ${theme.default.borderRadius}; color: ${theme.colors.default.textSecondary}; font-weight: bold; transition: all ${theme.default.transition.duration.medium} ${theme.default.transition.type}; &:hover { cursor: pointer; border-color: ${!isSelected && theme.colors.default.textPrimary}; color: ${theme.colors.default.textPrimary}; } ${isSelected && ` border-color: ${theme.colors.default.primary}; color: ${theme.colors.default.textPrimary}; `} `} `;
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/from.ts
import { PgCommon, PgExplorer, TupleFiles } from "../../utils/pg"; import { convertFromPlayground as convertToAnchor } from "../anchor/from"; import { addAfter } from "../common"; /** * {@link Framework.importFromPlayground} */ export const convertFromPlayground = async (files: TupleFiles) => { // Seahorse program name comes from the file name const programName = files .find(([path]) => /^src.*\.py$/.test(path))?.[0] .replace(/src\/(.*)\.py$/, (_, programName) => programName) .replace(/.*/, PgCommon.toSnakeCase); if (!programName) throw new Error("Program file not found"); // Seahorse's layout is the same as Anchor's layout with a couple of small // differences. Mimic what Seahorse generates by adding a dummy Anchor program // with the expected program name as the program module name so that we can // convert the files to Anchor to avoid duplicating file generation logic. files.push([ PgCommon.joinPaths(PgExplorer.PATHS.SRC_DIRNAME, "lib.rs"), `use anchor_lang::prelude::*;\n#[program] mod ${programName} {}`, ]); const anchorFiles = await convertToAnchor(files); const frameworkFiles = anchorFiles.map((file) => { // programs/<program-name>/src/**/*.py -> programs_py/<program-name>.py file[0] = file[0].replace(/programs\/.*\/src\/(.*\.py)/, (_, name) => { return PgCommon.joinPaths("programs_py", name); }); // Update manifest dependencies if (/programs\/.*Cargo\.toml/.test(file[0])) { file[1] = addAfter( file[1], /anchor-lang.*/, [ `anchor-spl = "*"`, `pyth-sdk-solana = { version = "*", optional = true }`, ].join("\n") ); } return file; }); // Add Seahorse prelude const SEAHORSE_PATH = PgCommon.joinPaths("programs_py", "seahorse"); frameworkFiles.push( [PgCommon.joinPaths(SEAHORSE_PATH, "__init__.py"), ""], [ PgCommon.joinPaths(SEAHORSE_PATH, "prelude.py"), await PgCommon.fetchText( "https://raw.githubusercontent.com/solana-developers/seahorse/main/data/const/seahorse_prelude.py" ), ] ); return frameworkFiles; };
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/to.ts
import { convertToPlayground as convertFromAnchor } from "../anchor/to"; import { PgCommon, PgExplorer, TupleFiles } from "../../utils/pg"; /** * {@link Framework.importToPlayground} */ export const convertToPlayground = async (files: TupleFiles) => { // Seahorse is a wrapper around Anchor, only difference is the Python files. // We convert to Anchor files and replace the Rust files with Python. const anchorFiles = await convertFromAnchor(files); const seahorseFiles = anchorFiles .filter(([path]) => !path.endsWith(".rs")) .concat( files.reduce((acc, file) => { const result = /.*programs_py\/([\w\d]+\.py)/.exec(file[0]); if (result) { file[0] = PgCommon.joinPaths(PgExplorer.PATHS.SRC_DIRNAME, result[1]); acc.push(file); } return acc; }, [] as TupleFiles) ); return seahorseFiles; };
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/index.ts
export { seahorse } from "./seahorse";
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/seahorse.ts
import { createFramework } from "../create"; export const seahorse = createFramework({ name: "Seahorse", language: "Python", icon: "https://pbs.twimg.com/profile_images/1556384244598964226/S3cx06I2_400x400.jpg", circleImage: true, githubExample: { name: "Transfer SOL", url: "https://github.com/solana-developers/program-examples/tree/main/basics/transfer-sol/seahorse", }, getIsCurrent: (files) => { for (const [path, content] of files) { if (!path.endsWith(".py")) continue; const isSeahorse = content.includes("seahorse.prelude"); if (isSeahorse) return true; } return false; }, });
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/files/index.ts
import type { TupleFiles } from "../../../utils/pg"; export const files: TupleFiles = [ ["src/fizzbuzz.py", require("./src/fizzbuzz.py")], ["client/client.ts", require("./client/client.ts.raw")], ["tests/seahorse.test.ts", require("./tests/seahorse.test.ts.raw")], ];
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/files
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/files/tests/seahorse.test.ts.raw
// No imports needed: web3, anchor, pg and more are globally available describe("FizzBuzz", async () => { // Generate the fizzbuzz account public key from its seeds const [fizzBuzzAccountPk] = await web3.PublicKey.findProgramAddress( [Buffer.from("fizzbuzz"), pg.wallet.publicKey.toBuffer()], pg.PROGRAM_ID ); it("init", async () => { // Send transaction const txHash = await pg.program.methods .init() .accounts({ fizzbuzz: fizzBuzzAccountPk, owner: pg.wallet.publicKey, systemProgram: web3.SystemProgram.programId, }) .rpc(); console.log(`Use 'solana confirm -v ${txHash}' to see the logs`); // Confirm transaction await pg.connection.confirmTransaction(txHash); // Fetch the created account const fizzBuzzAccount = await pg.program.account.fizzBuzz.fetch( fizzBuzzAccountPk ); console.log("Fizz:", fizzBuzzAccount.fizz); console.log("Buzz:", fizzBuzzAccount.buzz); console.log("N:", fizzBuzzAccount.n.toString()); }); it("doFizzbuzz", async () => { // Send transaction const txHash = await pg.program.methods .doFizzbuzz(new BN(6000)) .accounts({ fizzbuzz: fizzBuzzAccountPk, }) .rpc(); // Confirm transaction await pg.connection.confirmTransaction(txHash); // Fetch the fizzbuzz account const fizzBuzzAccount = await pg.program.account.fizzBuzz.fetch( fizzBuzzAccountPk ); console.log("Fizz:", fizzBuzzAccount.fizz); assert(fizzBuzzAccount.fizz) console.log("Buzz:", fizzBuzzAccount.buzz); assert(fizzBuzzAccount.buzz) console.log("N:", fizzBuzzAccount.n.toString()); assert.equal(fizzBuzzAccount.n, 0); }); });
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/files
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/files/client/client.ts.raw
// Client console.log("My address:", pg.wallet.publicKey.toString()); const balance = await pg.connection.getBalance(pg.wallet.publicKey); console.log(`My balance: ${balance / web3.LAMPORTS_PER_SOL} SOL`);
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/files
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/seahorse/files/src/fizzbuzz.py
# fizzbuzz # Built with Seahorse v0.2.0 # # On-chain, persistent FizzBuzz! from seahorse.prelude import * # This is your program's public key and it will update # automatically when you build the project. declare_id('11111111111111111111111111111111') class FizzBuzz(Account): fizz: bool buzz: bool n: u64 @instruction def init(owner: Signer, fizzbuzz: Empty[FizzBuzz]): fizzbuzz.init(payer = owner, seeds = ['fizzbuzz', owner]) @instruction def do_fizzbuzz(fizzbuzz: FizzBuzz, n: u64): fizzbuzz.fizz = n % 3 == 0 fizzbuzz.buzz = n % 5 == 0 if not fizzbuzz.fizz and not fizzbuzz.buzz: fizzbuzz.n = n else: fizzbuzz.n = 0
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/from.ts
import { PgCommon, PgConnection, PgExplorer, PgProgramInfo, TupleFiles, } from "../../utils/pg"; import { addAfter, addImports, getJSDependencies, getRustDependencies, IMPORT_STATEMENT_REGEX, } from "../common"; /** * {@link Framework.importFromPlayground} */ export const convertFromPlayground = async (files: TupleFiles) => { const PROGRAM_PATH = "program"; const frameworkFiles: TupleFiles = []; for (let [path, content] of files) { // src -> program/src if (path.startsWith(PgExplorer.PATHS.SRC_DIRNAME)) { path = PgCommon.joinPaths(PROGRAM_PATH, path); } // client -> client else if (path.startsWith(PgExplorer.PATHS.CLIENT_DIRNAME)) { content = convertJS(content); } // tests/**/*.test.ts -> tests/**/*.test.ts else if (path.startsWith(PgExplorer.PATHS.TESTS_DIRNAME)) { content = convertJS(content); } // Don't include other files else continue; frameworkFiles.push([path, content]); } // Add the files that don't exist in Playground frameworkFiles.push( // Program Cargo.toml [ PgCommon.joinPaths(PROGRAM_PATH, "Cargo.toml"), `[package] name = "${PgCommon.toKebabFromTitle( PgExplorer.currentWorkspaceName ?? "solpg" )}" version = "0.1.0" description = "Native Solana Program" edition = "2021" [lib] crate-type = ["cdylib", "lib"] [features] no-entrypoint = [] ${await getRustDependencies(files)} `, ], // .gitignore [ ".gitignore", `.DS_Store target node_modules test-ledger `, ], // .prettierignore [ ".prettierignore", `.DS_Store target test-ledger `, ], // package.json [ "package.json", `{ "scripts": { "lint:fix": "prettier */*.js \\"*/**/*{.js,.ts}\\" -w", "lint": "prettier */*.js \\"*/**/*{.js,.ts}\\" --check", "client": "yarn run ts-node client/*.ts", "test": "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts" }, ${await getJSDependencies(frameworkFiles)} } `, ], // tsconfig.json [ "tsconfig.json", `{ "compilerOptions": { "types": ["mocha", "chai"], "typeRoots": ["./node_modules/@types"], "lib": ["es2015"], "module": "commonjs", "target": "es6", "esModuleInterop": true } } `, ] ); return frameworkFiles; }; /** * Try to make the JS/TS file work in a local `node` environment by making the * necessary conversions. * * @param content JS/TS code * @returns the converted content */ const convertJS = (content: string) => { // Handle imports content = addImports(content); // Define Playground globals content = addAfter( content, IMPORT_STATEMENT_REGEX, `// Manually initialize variables that are automatically defined in Playground const PROGRAM_ID = new web3.PublicKey(${ PgProgramInfo.pk ? `"${PgProgramInfo.pk.toBase58()}"` : "/* Program id */" }); const connection = new web3.Connection("${ PgConnection.current.rpcEndpoint }", "${PgConnection.current.commitment}"); const wallet = { keypair: web3.Keypair.generate() }; ` ); // Handle pg namespace content = content .replaceAll("pg.PROGRAM_ID", "PROGRAM_ID") .replaceAll("pg.connection", "connection") .replaceAll("pg.wallet.keypair", "wallet.keypair") .replaceAll("pg.wallet.publicKey", "wallet.keypair.publicKey"); return content; };
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/to.ts
import { convertToPlaygroundCommon, selectProgram } from "../common"; import type { TupleFiles } from "../../utils/pg"; /** * {@link Framework.importToPlayground} */ export const convertToPlayground = async (files: TupleFiles) => { // Get Cargo workspace if it exists const workspaceManifest = files .filter(([path, content]) => { return path.endsWith("Cargo.toml") && content.includes("[workspace]"); }) .map((file) => [...file, file[0].split("/").length] as const) .sort((a, b) => a[2] - b[2]) .at(0); // Cargo workspace const programNames: string[] = []; if (workspaceManifest) { const membersResult = /\[workspace\]members\s+=\s+(\[.*?\])/.exec( workspaceManifest[1].replaceAll("\n", "") ); if (membersResult) { const members: string[] = JSON.parse(membersResult[1].replace(",]", "]")); // Get only the program members and exclude the rest, e.g. examples, macros, tests... const programMembers = members.filter((member) => { return files .filter(([path]) => path.includes(member)) .some(([_, content]) => content.includes("entrypoint!")); }); programNames.push(...programMembers); } } // Handle multiple programs if (programNames.length > 1) { // Select the program const programName = await selectProgram(programNames); // Filter out other programs files = files.filter(([path]) => path.includes(programName)); } return convertToPlaygroundCommon(files); };
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/native.ts
import { createFramework } from "../create"; export const native = createFramework({ name: "Native", language: "Rust", icon: "/icons/platforms/solana.png", githubExample: { name: "Hello Solana", // Only import the program for now since `fs` and `os` modules are not // implemented in Playground. We could solve it by converting the code // where it reads the user keypair and the program keypair but the goal // is to make everything that works in a local Node environment work in // Playground without any modifications. // TODO: Implement `fs` and `os` modules. // url: "https://github.com/solana-developers/program-examples/tree/main/basics/hello-solana/native", url: "https://github.com/solana-developers/program-examples/tree/main/basics/hello-solana/native/program", }, getIsCurrent: (files) => { for (const [path, content] of files) { if (!path.endsWith(".rs")) continue; const hasEntryPointMacro = content.includes("entrypoint!"); if (hasEntryPointMacro) return true; } return false; }, });
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/index.ts
export { native } from "./native";
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/files/index.ts
import type { TupleFiles } from "../../../utils/pg"; export const files: TupleFiles = [ ["src/lib.rs", require("./src/lib.rs")], ["client/client.ts", require("./client/client.ts.raw")], ["tests/native.test.ts", require("./tests/native.test.ts.raw")], ];
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/files
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/files/tests/native.test.ts.raw
// No imports needed: web3, borsh, pg and more are globally available /** * The state of a greeting account managed by the hello world program */ class GreetingAccount { counter = 0; constructor(fields: { counter: number } | undefined = undefined) { if (fields) { this.counter = fields.counter; } } } /** * Borsh schema definition for greeting accounts */ const GreetingSchema = new Map([ [GreetingAccount, { kind: "struct", fields: [["counter", "u32"]] }], ]); /** * The expected size of each greeting account. */ const GREETING_SIZE = borsh.serialize( GreetingSchema, new GreetingAccount() ).length; describe("Test", () => { it("greet", async () => { // Create greetings account instruction const greetingAccountKp = new web3.Keypair(); const lamports = await pg.connection.getMinimumBalanceForRentExemption( GREETING_SIZE ); const createGreetingAccountIx = web3.SystemProgram.createAccount({ fromPubkey: pg.wallet.publicKey, lamports, newAccountPubkey: greetingAccountKp.publicKey, programId: pg.PROGRAM_ID, space: GREETING_SIZE, }); // Create greet instruction const greetIx = new web3.TransactionInstruction({ keys: [ { pubkey: greetingAccountKp.publicKey, isSigner: false, isWritable: true, }, ], programId: pg.PROGRAM_ID, }); // Create transaction and add the instructions const tx = new web3.Transaction(); tx.add(createGreetingAccountIx, greetIx); // Send and confirm the transaction const txHash = await web3.sendAndConfirmTransaction(pg.connection, tx, [ pg.wallet.keypair, greetingAccountKp, ]); console.log(`Use 'solana confirm -v ${txHash}' to see the logs`); // Fetch the greetings account const greetingAccount = await pg.connection.getAccountInfo( greetingAccountKp.publicKey ); // Deserialize the account data const deserializedAccountData = borsh.deserialize( GreetingSchema, GreetingAccount, greetingAccount.data ); // Assertions assert.equal(greetingAccount.lamports, lamports); assert(greetingAccount.owner.equals(pg.PROGRAM_ID)); assert.deepEqual(greetingAccount.data, Buffer.from([1, 0, 0, 0])); assert.equal(deserializedAccountData.counter, 1); }); });
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/files
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/files/client/client.ts.raw
// Client console.log("My address:", pg.wallet.publicKey.toString()); const balance = await pg.connection.getBalance(pg.wallet.publicKey); console.log(`My balance: ${balance / web3.LAMPORTS_PER_SOL} SOL`);
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/files
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/native/files/src/lib.rs
use borsh::{BorshDeserialize, BorshSerialize}; use solana_program::{ account_info::{next_account_info, AccountInfo}, entrypoint, entrypoint::ProgramResult, msg, program_error::ProgramError, pubkey::Pubkey, }; /// Define the type of state stored in accounts #[derive(BorshSerialize, BorshDeserialize, Debug)] pub struct GreetingAccount { /// number of greetings pub counter: u32, } // Declare and export the program's entrypoint entrypoint!(process_instruction); // Program entrypoint's implementation pub fn process_instruction( program_id: &Pubkey, // Public key of the account the hello world program was loaded into accounts: &[AccountInfo], // The account to say hello to _instruction_data: &[u8], // Ignored, all helloworld instructions are hellos ) -> ProgramResult { msg!("Hello World Rust program entrypoint"); // Iterating accounts is safer than indexing let accounts_iter = &mut accounts.iter(); // Get the account to say hello to let account = next_account_info(accounts_iter)?; // The account must be owned by the program in order to modify its data if account.owner != program_id { msg!("Greeted account does not have the correct program id"); return Err(ProgramError::IncorrectProgramId); } // Increment and store the number of times the account has been greeted let mut greeting_account = GreetingAccount::try_from_slice(&account.data.borrow())?; greeting_account.counter += 1; greeting_account.serialize(&mut *account.data.borrow_mut())?; msg!("Greeted {} time(s)!", greeting_account.counter); Ok(()) }
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/from.ts
import { PgCommon, PgExplorer, PgProgramInfo, TupleFiles, } from "../../utils/pg"; import { addAfter, addImports, getJSDependencies, getRustDependencies, IMPORT_STATEMENT_REGEX, } from "../common"; /** * {@link Framework.importFromPlayground} */ export const convertFromPlayground = async (files: TupleFiles) => { // Program manifest's lib name must match the `#[program]` module name and // Anchor.toml programs definition const libContent = files.find(([path]) => path.endsWith("lib.rs"))?.[1]; if (!libContent) throw new Error("lib.rs not found"); const programName = /(pub\s+)?mod\s+(\w+)/m.exec(libContent)?.[2] ?? PgCommon.toSnakeCase(PgExplorer.currentWorkspaceName ?? "program"); const packageName = PgCommon.toKebabFromSnake(programName); const programPath = PgCommon.joinPaths("programs", packageName); const frameworkFiles: TupleFiles = []; for (let [path, content] of files) { // src -> programs/<program-name>/src if (path.startsWith(PgExplorer.PATHS.SRC_DIRNAME)) { path = PgCommon.joinPaths(programPath, path); } // client -> client else if (path.startsWith(PgExplorer.PATHS.CLIENT_DIRNAME)) { content = convertJS(content, programName); } // tests/**/*.test.ts -> tests/**/*.ts else if (path.startsWith(PgExplorer.PATHS.TESTS_DIRNAME)) { path = path.replace(".test.ts", ".ts"); content = convertJS(content, programName, { isTest: true }); } // Don't include other files else continue; frameworkFiles.push([path, content]); } // Add the files that don't exist in Playground frameworkFiles.push( // App ["app", ""], // Migrations [ PgCommon.joinPaths("migrations", "deploy.ts"), `// Migrations are an early feature. Currently, they're nothing more than this // single deploy script that's invoked from the CLI, injecting a provider // configured from the workspace's Anchor.toml. const anchor = require("@coral-xyz/anchor"); module.exports = async function (provider) { // Configure client to use the provider. anchor.setProvider(provider); // Add your deploy script here. }; `, ], // Program Cargo.toml [ PgCommon.joinPaths(programPath, "Cargo.toml"), `[package] name = "${packageName}" version = "0.1.0" description = "Created with Anchor" edition = "2021" [lib] crate-type = ["cdylib", "lib"] name = "${programName}" [features] no-entrypoint = [] no-idl = [] no-log-ix-name = [] cpi = ["no-entrypoint"] default = [] ${await getRustDependencies(frameworkFiles)} `, ], // Program Xargo.toml [ PgCommon.joinPaths(programPath, "Xargo.toml"), `[target.bpfel-unknown-unknown.dependencies.std] features = [] `, ], // .gitignore [ ".gitignore", `.anchor .DS_Store target **/*.rs.bk node_modules test-ledger .yarn `, ], // .prettierignore [ ".prettierignore", `.anchor .DS_Store target node_modules dist build test-ledger `, ], // Anchor.toml [ "Anchor.toml", `[features] seeds = false skip-lint = false ${ PgProgramInfo.pk ? `[programs.localnet] ${programName} = "${PgProgramInfo.pk.toBase58()}"` : "" } [registry] url = "https://api.apr.dev" [provider] cluster = "Localnet" wallet = "~/.config/solana/id.json" [scripts] test = "yarn run ts-mocha -p ./tsconfig.json -t 1000000 tests/**/*.ts" client = "yarn run ts-node client/*.ts" `, ], // Workspace Cargo.toml [ "Cargo.toml", `[workspace] members = [ "programs/*" ] [profile.release] overflow-checks = true lto = "fat" codegen-units = 1 [profile.release.build-override] opt-level = 3 incremental = false codegen-units = 1 `, ], // package.json [ "package.json", `{ "scripts": { "lint:fix": "prettier */*.js \\"*/**/*{.js,.ts}\\" -w", "lint": "prettier */*.js \\"*/**/*{.js,.ts}\\" --check" }, ${await getJSDependencies(frameworkFiles)} } `, ], // tsconfig.json [ "tsconfig.json", `{ "compilerOptions": { "types": ["mocha", "chai"], "typeRoots": ["./node_modules/@types"], "lib": ["es2015"], "module": "commonjs", "target": "es6", "esModuleInterop": true } } `, ] ); // Create program keypair if it exists if (PgProgramInfo.kp) { frameworkFiles.push([ PgCommon.joinPaths("target", "deploy", `${programName}-keypair.json`), JSON.stringify(Array.from(PgProgramInfo.kp.secretKey)), ]); } return frameworkFiles; }; /** * Try to make the JS/TS file work in a local `node` environment by making the * necessary conversions. * * @param content JS/TS code * @param programName snake case program name * @param opts options * - `isTest`: whether the given file is a test file * @returns the converted content */ const convertJS = ( content: string, programName: string, opts?: { isTest?: boolean } ) => { // Handle imports content = addImports(content); if (!content.includes("anchor")) { content = `import * as anchor from "@coral-xyz/anchor";\n` + content; } // Add program const pascalCaseProgramName = PgCommon.toPascalFromSnake(programName); content = addAfter( content, IMPORT_STATEMENT_REGEX, `import type { ${pascalCaseProgramName} } from "../target/types/${programName}";` ); content = opts?.isTest ? addAfter( content, /describe\(.*/, ` // Configure the client to use the local cluster anchor.setProvider(anchor.AnchorProvider.env());\n const program = anchor.workspace.${pascalCaseProgramName} as anchor.Program<${pascalCaseProgramName}>; `, { firstOccurance: true } ) : addAfter( content, IMPORT_STATEMENT_REGEX, `\n// Configure the client to use the local cluster anchor.setProvider(anchor.AnchorProvider.env());\n const program = anchor.workspace.${pascalCaseProgramName} as anchor.Program<${pascalCaseProgramName}>; ` ); // Handle pg namespace content = content .replaceAll("pg.program", "program") .replaceAll("pg.PROGRAM_ID", "program.programId") .replaceAll("pg.connection", "program.provider.connection") .replaceAll("pg.wallet.publicKey", "program.provider.publicKey") .replaceAll("pg.wallet.keypair", "program.provider.wallet.payer"); return content; };
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/to.ts
import { PgCommon, TupleFiles } from "../../utils/pg"; import { convertToPlaygroundCommon, selectProgram } from "../common"; /** * {@link Framework.importToPlayground} */ export const convertToPlayground = async (files: TupleFiles) => { // Get program name(s) const programNames = PgCommon.toUniqueArray( files .map(([path]) => /programs\/(.*?)\/src/.exec(path)?.[1]) .filter(PgCommon.isNonNullish) ); // Handle multiple programs if (programNames.length > 1) { // Select the program const programName = await selectProgram(programNames); // Filter out other programs files = files.filter(([path]) => { if (path.includes("programs")) { return path.includes(PgCommon.joinPaths("programs", programName)); } return true; }); } return convertToPlaygroundCommon(files); };
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/anchor.ts
import { createFramework } from "../create"; export const anchor = createFramework({ name: "Anchor", language: "Rust", icon: "https://www.anchor-lang.com/_next/image?url=%2Flogo.png&w=128&q=80", githubExample: { name: "Create Account", url: "https://github.com/solana-developers/program-examples/tree/main/basics/create-account/anchor", }, getIsCurrent: (files) => { // Return false if there is a Python file(Seahorse) otherwise this will // return a false positive because every Seahorse workspace is a valid // Anchor workspace. // // TODO: Handle this check from Seahorse side. Ideally we wouldn't need to // include Seahorse related checks in any of the Anchor files. const isSeahorse = files.some(([path]) => path.endsWith(".py")); if (isSeahorse) return false; for (const [path, content] of files) { if (!path.endsWith("lib.rs")) continue; const hasProgramMacro = content.includes("#[program]"); if (hasProgramMacro) return true; } return false; }, });
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/index.ts
export { anchor } from "./anchor";
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/files/index.ts
import type { TupleFiles } from "../../../utils/pg"; export const files: TupleFiles = [ ["src/lib.rs", require("./src/lib.rs")], ["client/client.ts", require("./client/client.ts.raw")], ["tests/anchor.test.ts", require("./tests/anchor.test.ts.raw")], ];
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/files
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/files/tests/anchor.test.ts.raw
// No imports needed: web3, anchor, pg and more are globally available describe("Test", () => { it("initialize", async () => { // Generate keypair for the new account const newAccountKp = new web3.Keypair(); // Send transaction const data = new BN(42); const txHash = await pg.program.methods .initialize(data) .accounts({ newAccount: newAccountKp.publicKey, signer: pg.wallet.publicKey, systemProgram: web3.SystemProgram.programId, }) .signers([newAccountKp]) .rpc(); console.log(`Use 'solana confirm -v ${txHash}' to see the logs`); // Confirm transaction await pg.connection.confirmTransaction(txHash); // Fetch the created account const newAccount = await pg.program.account.newAccount.fetch( newAccountKp.publicKey ); console.log("On-chain data is:", newAccount.data.toString()); // Check whether the data on-chain is equal to local 'data' assert(data.eq(newAccount.data)); }); });
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/files
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/files/client/client.ts.raw
// Client console.log("My address:", pg.wallet.publicKey.toString()); const balance = await pg.connection.getBalance(pg.wallet.publicKey); console.log(`My balance: ${balance / web3.LAMPORTS_PER_SOL} SOL`);
0
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/files
solana_public_repos/solana-playground/solana-playground/client/src/frameworks/anchor/files/src/lib.rs
use anchor_lang::prelude::*; // This is your program's public key and it will update // automatically when you build the project. declare_id!("11111111111111111111111111111111"); #[program] mod hello_anchor { use super::*; pub fn initialize(ctx: Context<Initialize>, data: u64) -> Result<()> { ctx.accounts.new_account.data = data; msg!("Changed data to: {}!", data); // Message will show up in the tx logs Ok(()) } } #[derive(Accounts)] pub struct Initialize<'info> { // We must specify the space in order to initialize an account. // First 8 bytes are default account discriminator, // next 8 bytes come from NewAccount.data being type u64. // (u64 = 64 bits unsigned integer = 8 bytes) #[account(init, payer = signer, space = 8 + 8)] pub new_account: Account<'info, NewAccount>, #[account(mut)] pub signer: Signer<'info>, pub system_program: Program<'info, System>, } #[account] pub struct NewAccount { data: u64 }
0
solana_public_repos/solana-playground/solana-playground/client/src
solana_public_repos/solana-playground/solana-playground/client/src/views/index.ts
export { BOTTOM } from "./bottom"; export { MAIN_SECONDARY } from "./main"; export { SIDEBAR } from "./sidebar";
0
solana_public_repos/solana-playground/solana-playground/client/src/views
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/index.ts
export { SIDEBAR } from "./sidebar";
0
solana_public_repos/solana-playground/solana-playground/client/src/views
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/create.ts
import { PgCommon, SidebarPage, SidebarPageParam } from "../../utils/pg"; /** * Create a sidebar page. * * @param page sidebar page * @returns the page with correct types */ export const createSidebarPage = <N extends string>( page: SidebarPageParam<N> ) => { page.icon = "/icons/sidebar/" + page.icon; page.title ??= page.keybind ? `${page.name} (${page.keybind})` : page.name; page.importElement ??= () => { return import( `./${PgCommon.toKebabFromTitle(page.name.replace("& ", ""))}/Component` ); }; return page as SidebarPage<N>; };
0
solana_public_repos/solana-playground/solana-playground/client/src/views
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/sidebar.ts
import { buildDeploy } from "./build-deploy"; import { explorer } from "./explorer"; import { programs } from "./programs"; import { test } from "./test"; import { tutorials } from "./tutorials"; /** All sidebar pages in order */ export const SIDEBAR = [explorer, buildDeploy, test, tutorials, programs];
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/build-deploy.ts
import { createSidebarPage } from "../create"; export const buildDeploy = createSidebarPage({ name: "Build & Deploy", icon: "build.png", keybind: "Ctrl+Shift+B", });
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/index.ts
export { buildDeploy } from "./build-deploy";
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/BuildDeploy.tsx
import styled from "styled-components"; import Build from "./Build"; import Deploy from "./Deploy"; import ProgramSettings from "./ProgramSettings"; const BuildDeploy = () => ( <Wrapper> <Build /> <Deploy /> <ProgramSettings /> </Wrapper> ); const Wrapper = styled.div` padding: 1.5rem; border-bottom: 1px solid ${({ theme }) => theme.colors.default.border}; `; export default BuildDeploy;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/Build.tsx
import { useCallback } from "react"; import styled from "styled-components"; import Button from "../../../../components/Button"; import { useRenderOnChange } from "../../../../hooks"; import { PgCommand, PgGlobal } from "../../../../utils/pg"; const Build = () => { const buildLoading = useRenderOnChange( PgGlobal.onDidChangeBuildLoading, PgGlobal.buildLoading ); const build = useCallback(() => PgCommand.build.run(), []); return ( <Wrapper> <Button kind="secondary" onClick={build} btnLoading={buildLoading} fullWidth > {buildLoading ? "Building..." : "Build"} </Button> </Wrapper> ); }; const Wrapper = styled.div` display: flex; flex-direction: column; justify-content: center; `; export default Build;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/Deploy.tsx
import { useMemo } from "react"; import styled from "styled-components"; import Text from "../../../../components/Text"; import Button, { ButtonProps } from "../../../../components/Button"; import { PgCommand, PgGlobal } from "../../../../utils/pg"; import { useProgramInfo, useRenderOnChange, useWallet, } from "../../../../hooks"; import { Pause, Triangle } from "../../../../components/Icons"; const Deploy = () => { const buildLoading = useRenderOnChange( PgGlobal.onDidChangeBuildLoading, PgGlobal.buildLoading ); const deployState = useRenderOnChange( PgGlobal.onDidChangeDeployState, PgGlobal.deployState ); const { deployed, error, programInfo } = useProgramInfo(); const { wallet } = useWallet(); const upgradable = programInfo.onChain?.upgradable; const hasAuthority = wallet ? programInfo.onChain?.authority?.equals(wallet.publicKey) : false; const hasProgramKp = !!programInfo.kp; const hasUuid = !!programInfo.uuid; const importedProgram = programInfo.importedProgram; const isImportedProgram = !!importedProgram?.buffer.length; const deployButtonText = useMemo(() => { return deployState === "cancelled" ? "Cancelling..." : deployState === "paused" ? "Continue" : deployState === "loading" ? deployed ? "Upgrading..." : "Deploying..." : deployed ? "Upgrade" : "Deploy"; }, [deployState, deployed]); const deployButtonProps = useMemo<ButtonProps>( () => ({ kind: "primary", onClick: () => { switch (deployState) { case "ready": // TODO: Run commands without writing to terminal and handle the // `PgGlobal.deployState` inside the command implementation. The // state has to be handled outside of the command because the deploy // command is waiting for user input and re-running the command here // would overwrite the user input. return PgCommand.deploy.run(); case "loading": PgGlobal.update({ deployState: "paused" }); break; case "paused": PgGlobal.update({ deployState: "loading" }); } }, btnLoading: deployState === "cancelled", disabled: buildLoading, leftIcon: deployState === "loading" ? ( <Pause /> ) : deployState === "paused" ? ( <Triangle rotate="90deg" /> ) : null, }), [buildLoading, deployState] ); // First time state if (!deployed && !hasProgramKp) { if (isImportedProgram) return ( <Wrapper> <Text> <div> Initial deployment needs a keypair. You can import it from <Bold> Program ID</Bold> settings. </div> </Text> </Wrapper> ); return null; } if (error) return ( <Wrapper> <Text kind="error"> Connection error. Please try changing the RPC endpoint from the settings. </Text> </Wrapper> ); if (!wallet) return ( <Wrapper> <Text>Your wallet must be connected for program deployments.</Text> <Button onClick={() => PgCommand.connect.run()} kind="primary"> Connect to Playground Wallet </Button> </Wrapper> ); if (!hasUuid && !isImportedProgram) return ( <Wrapper> <Text> <div> Build the program first or import a program from <Bold> Program binary</Bold>. </div> </Text> </Wrapper> ); if (upgradable === false) return ( <Wrapper> <Text kind="warning">The program is not upgradable.</Text> </Wrapper> ); if (hasAuthority === false) return ( <Wrapper> <Text kind="warning"> You don't have the authority to upgrade this program. </Text> </Wrapper> ); // Custom(uploaded) program deploy if (isImportedProgram) { const text = deployState === "cancelled" ? `Cancelling the ${deployed ? "upgrade" : "deployment"} of ${ importedProgram.fileName }...` : deployState === "loading" ? `${deployed ? "Upgrading" : "Deploying"} ${ importedProgram.fileName }...` : ` Ready to ${deployed ? "upgrade" : "deploy"} ${ importedProgram.fileName }`; return ( <Wrapper> <Text>{text}</Text> <Button {...deployButtonProps}>{deployButtonText}</Button> </Wrapper> ); } return ( <Wrapper> <Button {...deployButtonProps}>{deployButtonText}</Button> </Wrapper> ); }; const Wrapper = styled.div` display: flex; flex-direction: column; justify-content: center; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid ${({ theme }) => theme.colors.default.border}; & div:first-child + button { margin-top: 1.5rem; } `; const Bold = styled.span` font-weight: bold; `; export default Deploy;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/index.ts
export { default } from "./BuildDeploy";
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/ProgramSettings/IDL.tsx
import { ChangeEvent, useCallback, useEffect, useMemo, useState } from "react"; import styled from "styled-components"; import Button from "../../../../../components/Button"; import ExportButton from "../../../../../components/ExportButton"; import ImportButton from "../../../../../components/ImportButton"; import { PgCommand, PgCommon, PgProgramInfo, PgWallet, } from "../../../../../utils/pg"; import { useRenderOnChange } from "../../../../../hooks"; const IDL = () => ( <Wrapper> <Import /> <Export /> <InitOrUpgrade /> </Wrapper> ); const Import = () => { const handleImport = async (ev: ChangeEvent<HTMLInputElement>) => { const files = ev.target.files; if (!files?.length) return; try { const file = files[0]; const arrayBuffer = await file.arrayBuffer(); const decodedString = PgCommon.decodeBytes(arrayBuffer); PgProgramInfo.update({ idl: JSON.parse(decodedString), }); } catch (e: any) { console.log(e.message); } }; return ( <ImportButton accept=".json" onImport={handleImport} showImportText> Import </ImportButton> ); }; const Export = () => { useRenderOnChange(PgProgramInfo.onDidChangeIdl); if (!PgProgramInfo.idl) return null; return ( <ExportButton href={PgProgramInfo.idl} fileName="idl.json"> Export </ExportButton> ); }; enum InitOrUpgradeState { HIDDEN, HAS_ERROR, INCORRECT_AUTHORITY, IS_FETCHING, IS_INITIALIZING, IS_UPGRADING, CAN_INIT, CAN_UPGRADE, } const InitOrUpgrade = () => { const [state, setState] = useState<InitOrUpgradeState>( InitOrUpgradeState.HIDDEN ); const buttonText = useMemo(() => { switch (state) { case InitOrUpgradeState.HAS_ERROR: return "Retry"; case InitOrUpgradeState.IS_FETCHING: return "Fetching"; case InitOrUpgradeState.IS_INITIALIZING: return "Initializing"; case InitOrUpgradeState.IS_UPGRADING: return "Upgrading"; case InitOrUpgradeState.CAN_INIT: return "Initialize"; case InitOrUpgradeState.CAN_UPGRADE: case InitOrUpgradeState.INCORRECT_AUTHORITY: return "Upgrade"; } }, [state]); const [loading, disabled] = useMemo(() => { switch (state) { case InitOrUpgradeState.IS_FETCHING: case InitOrUpgradeState.IS_INITIALIZING: case InitOrUpgradeState.IS_UPGRADING: return [true, true]; case InitOrUpgradeState.INCORRECT_AUTHORITY: return [false, true]; default: return [false, false]; } }, [state]); const getIdl = useCallback(async () => { try { if (!PgProgramInfo.idl || !PgProgramInfo.pk || !PgWallet.current) { setState(InitOrUpgradeState.HIDDEN); return; } setState(InitOrUpgradeState.IS_FETCHING); const idlResult = await PgCommon.transition(PgProgramInfo.fetchIdl()); if (!idlResult) { setState(InitOrUpgradeState.CAN_INIT); return; } if (idlResult.authority.equals(PgWallet.current.publicKey)) { setState(InitOrUpgradeState.CAN_UPGRADE); return; } setState(InitOrUpgradeState.INCORRECT_AUTHORITY); } catch (e: any) { console.log("Couldn't get IDL:", e.message); setState(InitOrUpgradeState.HAS_ERROR); } }, []); // Execute the `getIdl` function useEffect(() => { const { dispose } = PgCommon.batchChanges(getIdl, [ PgProgramInfo.onDidChange, PgWallet.onDidChangeCurrent, ]); return dispose; }, [getIdl]); const handleInitOrUpgrade = async () => { switch (state) { case InitOrUpgradeState.CAN_INIT: { setState(InitOrUpgradeState.IS_INITIALIZING); await PgCommand.anchor.run("idl", "init"); break; } case InitOrUpgradeState.CAN_UPGRADE: { setState(InitOrUpgradeState.IS_UPGRADING); await PgCommand.anchor.run("idl", "upgrade"); break; } } await getIdl(); }; if (state === InitOrUpgradeState.HIDDEN) return null; return ( <Button disabled={disabled} btnLoading={loading} onClick={handleInitOrUpgrade} > {buttonText} </Button> ); }; const Wrapper = styled.div` display: flex; gap: 1rem; `; export default IDL;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/ProgramSettings/ProgramSettings.tsx
import { FC, ReactNode, useState } from "react"; import styled, { css } from "styled-components"; import Foldable from "../../../../../components/Foldable"; import BuildFlags from "./BuildFlags"; import IDL from "./IDL"; import ProgramBinary from "./ProgramBinary"; import ProgramID from "./ProgramID"; import { useAsyncEffect } from "../../../../../hooks"; import { PgFramework } from "../../../../../utils/pg"; /** All program settings */ const DEFAULT_PROGRAM_SETTINGS: ProgramSettingProps[] = [ { title: "Program ID", description: "Import/export program keypair or input a public key for the program", element: <ProgramID />, isOpen: true, }, { title: "Program binary", description: "Import your program and deploy without failure", element: <ProgramBinary />, }, ]; const ProgramSettings = () => { const [settings, setSettings] = useState<ProgramSettingProps[] | null>(null); useAsyncEffect(async () => { const framework = await PgFramework.getFromFiles(); switch (framework?.name) { case "Anchor": case "Seahorse": { const anchorSettings: ProgramSettingProps[] = [ { title: "IDL", description: "Anchor IDL interactions", element: <IDL />, }, ]; if (process.env.NODE_ENV !== "production") { anchorSettings.unshift({ title: "Build flags", description: "Anchor build flags", element: <BuildFlags />, }); } setSettings(DEFAULT_PROGRAM_SETTINGS.concat(anchorSettings)); break; } case "Native": setSettings(DEFAULT_PROGRAM_SETTINGS); break; default: setSettings(null); } }, []); return ( <Wrapper> {settings?.map((setting) => ( <ProgramSetting key={setting.title} {...setting} /> ))} </Wrapper> ); }; const Wrapper = styled.div` display: flex; flex-direction: column; justify-content: center; margin-top: 1rem; border-top: 1px solid ${({ theme }) => theme.colors.default.border}; `; interface ProgramSettingProps { /** Title text that will be shown as a foldable title */ title: string; /** Description of the setting that will be shown after unfolding */ description: string; /** Component that will be shown inside the foldable and under the description */ element: ReactNode; /** Whether the foldable is open by default */ isOpen?: boolean; } const ProgramSetting: FC<ProgramSettingProps> = ({ title, description, element, isOpen, }) => ( <ProgramSettingWrapper> <Foldable isOpen={isOpen} element={<ProgramSettingTitle>{title}</ProgramSettingTitle>} > <ProgramSettingsInside> <ProgramSettingDescription>{description}</ProgramSettingDescription> <ProgramSettingContent>{element}</ProgramSettingContent> </ProgramSettingsInside> </Foldable> </ProgramSettingWrapper> ); const ProgramSettingWrapper = styled.div` margin-top: 1rem; `; const ProgramSettingTitle = styled.span``; const ProgramSettingsInside = styled.div` padding: 0 0.5rem; `; const ProgramSettingDescription = styled.div` ${({ theme }) => css` color: ${theme.colors.default.textSecondary}; font-size: ${theme.font.code.size.small}; `} `; const ProgramSettingContent = styled.div` margin-top: 0.5rem; `; export default ProgramSettings;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/ProgramSettings/ProgramID.tsx
import { ChangeEvent, useEffect, useState } from "react"; import styled, { css } from "styled-components"; import Button from "../../../../../components/Button"; import CopyButton from "../../../../../components/CopyButton"; import ExportButton from "../../../../../components/ExportButton"; import ImportButton from "../../../../../components/ImportButton"; import Input from "../../../../../components/Input"; import Modal from "../../../../../components/Modal"; import Text from "../../../../../components/Text"; import { Warning } from "../../../../../components/Icons"; import { PgProgramInfo, PgCommon, PgView, PgWeb3, } from "../../../../../utils/pg"; import { useRenderOnChange } from "../../../../../hooks"; const ProgramID = () => ( <Wrapper> <ButtonsWrapper> <New /> <Import /> <Export /> </ButtonsWrapper> <InputPk /> </Wrapper> ); const New = () => { const handleNew = async () => { if (PgProgramInfo.kp) { await PgView.setModal(NewKeypairModal); } else { PgProgramInfo.update({ kp: PgWeb3.Keypair.generate() }); } }; return <Button onClick={handleNew}>New</Button>; }; const NewKeypairModal = () => { const generateNewKeypair = () => { PgProgramInfo.update({ kp: PgWeb3.Keypair.generate(), customPk: null, }); }; return ( <Modal title buttonProps={{ text: "Generate", onSubmit: generateNewKeypair, }} > <MainContent> <MainText> Are you sure you want to create a new program keypair? </MainText> <Desc>This will create a brand new keypair for your program.</Desc> <WarningTextWrapper> <Text kind="warning" icon={<Warning color="warning" />}> The old keypair will be lost if you don't save it. </Text> </WarningTextWrapper> <ExportButton href={Array.from(PgProgramInfo.kp!.secretKey)} fileName="program-keypair.json" buttonKind="outline" > Save keypair </ExportButton> </MainContent> </Modal> ); }; const Import = () => { const handleImport = async (ev: ChangeEvent<HTMLInputElement>) => { const files = ev.target.files; if (!files?.length) return; try { const file = files[0]; const arrayBuffer = await file.arrayBuffer(); const decodedString = PgCommon.decodeBytes(arrayBuffer); const buffer = Buffer.from(JSON.parse(decodedString)); if (buffer.length !== 64) throw new Error("Invalid keypair"); // Override customPk when user imports a new keypair PgProgramInfo.update({ kp: PgWeb3.Keypair.fromSecretKey(buffer), customPk: null, }); // Reset file ev.target.value = ""; } catch (err: any) { console.log(err.message); } }; return ( <ImportButton accept=".json" onImport={handleImport}> Import </ImportButton> ); }; const Export = () => { useRenderOnChange(PgProgramInfo.onDidChangeKp); if (!PgProgramInfo.kp) return null; return ( <ExportButton href={Array.from(PgProgramInfo.kp.secretKey)} fileName="program-keypair.json" > Export </ExportButton> ); }; interface UpdateInfoProps { text?: string; error?: boolean; } const InputPk = () => { const [val, setVal] = useState(""); const [updateInfo, setUpdateInfo] = useState<UpdateInfoProps>({}); const [changed, setChanged] = useState(false); useEffect(() => { const { dispose } = PgProgramInfo.onDidChangePk((pk) => { if (pk) setVal(pk.toBase58()); }); return dispose; }, []); const handleChange = (ev: ChangeEvent<HTMLInputElement>) => { setVal(ev.target.value); setChanged(true); setUpdateInfo({}); }; const handleClick = () => { try { PgProgramInfo.update({ customPk: new PgWeb3.PublicKey(val) }); setUpdateInfo({ text: "Updated program id." }); setChanged(false); } catch { setUpdateInfo({ text: "Invalid public key.", error: true }); } }; const handleRemoveCustomProgramId = () => { PgProgramInfo.update({ customPk: null }); setUpdateInfo({ text: "Removed custom id." }); }; return ( <InputPkWrapper> <InputLabelWrapper> <InputLabel>Program ID:</InputLabel> {updateInfo.text && ( <UpdateInfo error={updateInfo?.error}>{updateInfo.text}</UpdateInfo> )} </InputLabelWrapper> <InputWrapper> <Input value={val} onChange={handleChange} validator={PgCommon.isPk} placeholder="Your program's public key" /> <CopyButton copyText={val} /> </InputWrapper> <InputWarning> <Warning color="warning" /> Note that you need to have this program's authority to upgrade </InputWarning> {changed && <Button onClick={handleClick}>Change program id</Button>} {!!PgProgramInfo.customPk && ( <Button onClick={handleRemoveCustomProgramId}> Remove custom program id </Button> )} </InputPkWrapper> ); }; const Wrapper = styled.div` & > div:first-child > * { margin-right: 1rem; } `; const ButtonsWrapper = styled.div` display: flex; `; const MainContent = styled.div` display: flex; flex-direction: column; padding: 0 1rem; & > a { margin-top: 1rem; } `; const MainText = styled.span` font-weight: bold; `; const Desc = styled.span` ${({ theme }) => css` font-size: ${theme.font.code.size.small}; color: ${theme.colors.default.textSecondary}; margin-top: 0.5rem; `} `; const WarningTextWrapper = styled.div` margin-top: 1rem; display: flex; align-items: center; & svg { height: 2rem; width: 2rem; margin-right: 1rem; } `; // Program Id input const InputPkWrapper = styled.div` margin-top: 1rem; & > button { margin-top: 0.5rem; } `; const InputLabelWrapper = styled.div` margin-bottom: 0.375rem; font-size: ${({ theme }) => theme.font.code.size.small}; `; const InputLabel = styled.span` margin-bottom: 0.375rem; font-size: ${({ theme }) => theme.font.code.size.small}; `; const UpdateInfo = styled.span<UpdateInfoProps>` ${({ theme, error }) => css` margin-left: 0.375rem; font-size: ${theme.font.code.size.small}; color: ${error ? theme.colors.state.error.color : theme.colors.state.success.color}; `} `; const InputWrapper = styled.div` display: flex; align-items: center; justify-content: center; `; const InputWarning = styled.div` ${({ theme }) => css` margin-top: 0.375rem; font-size: ${theme.font.code.size.small}; color: ${theme.colors.default.textSecondary}; & > svg { margin-right: 0.375rem; } `} `; export default ProgramID;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/ProgramSettings/BuildFlags.tsx
import styled from "styled-components"; import Checkbox from "../../../../../components/Checkbox"; import Tooltip from "../../../../../components/Tooltip"; import { PgCommon, PgSettings } from "../../../../../utils/pg"; type BuildFlag = keyof typeof PgSettings["build"]["flags"]; const BUILD_FLAGS: { [K in BuildFlag]: string } = { noDocs: "Disable documentation in IDL", safetyChecks: "Require `/// CHECK:` comments for unchecked accounts", seedsFeature: "Include seeds in IDL", }; const BuildFlags = () => ( <Wrapper> {PgCommon.entries(BUILD_FLAGS).map(([flag, details]) => ( <Row key={flag}> <Checkbox label={PgCommon.toTitleFromCamel(flag)} onChange={(ev) => { PgSettings.build.flags[flag] = ev.target.checked; }} defaultChecked={PgSettings.build.flags[flag]} /> <Tooltip help element={details} placement="right" maxWidth="15rem" /> </Row> ))} </Wrapper> ); const Wrapper = styled.div` margin-top: 0.75rem; display: flex; flex-direction: column; gap: 1rem; `; const Row = styled.div` display: flex; gap: 0.5rem; `; export default BuildFlags;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/ProgramSettings/index.ts
export { default } from "./ProgramSettings";
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/build-deploy/Component/ProgramSettings/ProgramBinary.tsx
import styled from "styled-components"; import Button from "../../../../../components/Button"; import ImportButton from "../../../../../components/ImportButton"; import { PgCommon, PgExplorer, PgProgramInfo, PgServer, } from "../../../../../utils/pg"; import { useRenderOnChange } from "../../../../../hooks"; const ProgramBinary = () => ( <Wrapper> <Import /> <Export /> </Wrapper> ); const Wrapper = styled.div` display: flex; gap: 1rem; `; const Import = () => ( <ImportButton accept=".so" onImport={async (ev) => { const files = ev.target.files; if (!files?.length) { PgProgramInfo.update({ importedProgram: null }); return; } try { const file = files[0]; const fileName = file.name; const arrayBuffer = await file.arrayBuffer(); const buffer = Buffer.from(arrayBuffer); PgProgramInfo.update({ importedProgram: { buffer, fileName } }); } catch (err: any) { console.log(err.message); } }} showImportText > Import </ImportButton> ); const Export = () => { useRenderOnChange(PgProgramInfo.onDidChangeUuid); if (!PgProgramInfo.uuid) return null; return ( <Button onClick={async () => { const programBuffer = await PgServer.deploy(PgProgramInfo.uuid!); const programName = PgExplorer.currentWorkspaceName ?? "program"; PgCommon.export(`${programName}.so`, programBuffer); }} > Export </Button> ); }; export default ProgramBinary;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/test.ts
import TestSkeleton from "./Component/TestSkeleton"; import { createSidebarPage } from "../create"; export const test = createSidebarPage({ name: "Test", icon: "test.png", keybind: "Ctrl+Shift+D", LoadingElement: TestSkeleton, });
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/index.ts
export { test } from "./test";
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/InputLabel.tsx
import { FC } from "react"; import styled, { css } from "styled-components"; interface InputLabelProps { name: string; type: string; isMut?: boolean; isSigner?: boolean; } const InputLabel: FC<InputLabelProps> = ({ name, type, isMut, isSigner }) => ( <Wrapper> <NameWrapper> <Name>{name}:</Name> </NameWrapper> <TypesWrapper> <Type>{type}</Type> {isMut && <Type isMut>mut</Type>} {isSigner && <Type isSigner>signer</Type>} </TypesWrapper> </Wrapper> ); const Wrapper = styled.div` ${({ theme }) => css` margin-bottom: 0.25rem; display: flex; align-items: center; gap: 0.5rem; font-size: ${theme.font.code.size.small}; `} `; const NameWrapper = styled.div``; const Name = styled.span` ${({ theme }) => css` color: ${theme.colors.default.textSecondary}; `} `; const TypesWrapper = styled.div` display: flex; align-items: center; gap: 0.75rem; `; const Type = styled.span<Pick<InputLabelProps, "isMut" | "isSigner">>` ${({ theme, isMut, isSigner }) => css` color: ${isMut ? theme.highlight.modifier.color : isSigner ? theme.colors.state.success.color : theme.highlight.typeName.color}; `} `; export default InputLabel;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/TestSkeleton.tsx
import styled, { css } from "styled-components"; import { Skeleton } from "../../../../components/Loading"; const TestSkeleton = () => ( <Wrapper> <ProgramNameWrapper> <Skeleton width="4rem" /> <Skeleton width="6rem" /> </ProgramNameWrapper> <Heading> <Skeleton width="6.5rem" /> </Heading> <FullWidthBg> <Skeleton width="7.5rem" /> </FullWidthBg> <Heading> <Skeleton width="4.5rem" /> </Heading> <FullWidthBg> <Skeleton width="8rem" /> </FullWidthBg> </Wrapper> ); const Wrapper = styled.div``; const ProgramNameWrapper = styled.div` display: flex; padding: 1rem 1rem 0 1rem; & > :first-child { margin-right: 0.75rem; } `; const Heading = styled.div` padding: 1.5rem 0 0 1rem; `; const FullWidthBg = styled.div` ${({ theme }) => css` padding: 1rem; margin-top: 0.75rem; background: ${theme.components.sidebar.right.default.otherBg}; border-top: 1px solid ${theme.colors.default.border}; border-bottom: 1px solid ${theme.colors.default.border}; `} `; export default TestSkeleton;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Test.tsx
import { useEffect } from "react"; import styled from "styled-components"; import BN from "bn.js"; import Account from "./Account"; import Event from "./Event"; import Instruction from "./Instruction"; import IdlProvider from "./IdlProvider"; import Text from "../../../../components/Text"; import { PgCommand, PgProgramInfo } from "../../../../utils/pg"; import { PgProgramInteraction } from "../../../../utils/pg/program-interaction"; import { useProgramInfo, useRenderOnChange } from "../../../../hooks"; const Test = () => { useRenderOnChange(PgCommand.build.onDidRunFinish); const { error, deployed } = useProgramInfo(); // Used for both accounts and events data useBigNumberJson(); // Handle instruction storage useSyncInstructionStorage(); if (!PgProgramInfo.importedProgram && !PgProgramInfo.uuid) { return ( <InitialWrapper> <Text>Program is not built.</Text> </InitialWrapper> ); } if (!PgProgramInfo.pk) { return ( <InitialWrapper> <Text>The program has no public key.</Text> </InitialWrapper> ); } const idl = PgProgramInfo.idl; if (!idl) { return ( <InitialWrapper> <Text>Anchor IDL not found.</Text> </InitialWrapper> ); } if (!idl.instructions) { return ( <InitialWrapper> <Text kind="error"> You've imported a corrupted IDL. Please double check you've imported an Anchor IDL. </Text> </InitialWrapper> ); } if (error) { return ( <InitialWrapper> <Text kind="error"> Connection error. Please try changing the RPC endpoint from the settings. </Text> </InitialWrapper> ); } if (!deployed) { return ( <InitialWrapper> <Text>Program is not deployed.</Text> </InitialWrapper> ); } return ( <IdlProvider idl={idl}> <Wrapper> <ProgramNameWrapper> Program: <ProgramName>{idl.name}</ProgramName> </ProgramNameWrapper> <ProgramInteractionWrapper> <ProgramInteractionHeader>Instructions</ProgramInteractionHeader> {idl.instructions.map((ix, i) => ( <Instruction key={JSON.stringify(ix)} index={i} idlInstruction={ix} /> ))} </ProgramInteractionWrapper> {idl.accounts && ( <ProgramInteractionWrapper> <ProgramInteractionHeader>Accounts</ProgramInteractionHeader> {idl.accounts.map((acc, i) => ( <Account key={acc.name} index={i} accountName={acc.name} /> ))} </ProgramInteractionWrapper> )} {idl.events && ( <ProgramInteractionWrapper> <ProgramInteractionHeader>Events</ProgramInteractionHeader> {idl.events.map((event, i) => ( <Event key={event.name} index={i} eventName={event.name} /> ))} </ProgramInteractionWrapper> )} </Wrapper> </IdlProvider> ); }; const InitialWrapper = styled.div` padding: 1.5rem; `; const Wrapper = styled.div` user-select: none; display: flex; flex-direction: column; gap: 1rem; padding-top: 1rem; `; const ProgramNameWrapper = styled.div` padding-left: 1rem; `; const ProgramName = styled.span` font-weight: bold; margin-left: 0.25rem; `; const ProgramInteractionWrapper = styled.div``; const ProgramInteractionHeader = styled.div` ${({ theme }) => ` margin: 0.5rem 1rem; color: ${theme.colors.default.primary}; font-size: ${theme.font.code.size.large}; font-weight: bold; `}; `; /** * Temporarily change `BN.toJSON` method to `BN.toString` in order to have * human-readable output rather than hex values. */ const useBigNumberJson = () => { useEffect(() => { const oldBNPrototypeToJSON = BN.prototype.toJSON; BN.prototype.toJSON = function (this: BN) { return this.toString(); }; // Change the toJSON prototype back on unmount return () => { BN.prototype.toJSON = oldBNPrototypeToJSON; }; }, []); }; /** Sync the instruction storage. */ const useSyncInstructionStorage = () => { useEffect(() => { const { dispose } = PgProgramInfo.onDidChangeIdl((idl) => { if (idl) PgProgramInteraction.syncAllInstructions(idl.instructions); }); return dispose; }, []); }; export default Test; // Initial thought process when implementing tests. // If we have the IDL: // 1. We can show all the callable methods. // 2. For each function we can only populate the known // accounts like system_program or clock. // This is a big problem for more complex methods if we don't // allow users to write their own ts implementation to calculate // the needed accounts. // One solution would be to implement ts support for tests so that // the users can write their own scripts to do the testing directly // on the browser. But this is also problematic since our goal is // to make this app as easy as possible to use. It would be better // for us to implement testing features with ui only so that users // can just easily do their testing without needing to write a script. // More advanced users can choose to go with the scripting route. // The ui can have a custom ix builder to build txs that require // let's say a token account creation as a preInstruction. The users // would be able to choose how to create each account or put the // publicKey manually.
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Interaction.tsx
import { FC } from "react"; import styled, { css } from "styled-components"; import Foldable from "../../../../components/Foldable"; interface InteractionProps { name: string; index: number; } const Interaction: FC<InteractionProps> = ({ name, index, children }) => ( <Wrapper index={index}> <Foldable element={<Name>{name}</Name>}>{children}</Foldable> </Wrapper> ); const Wrapper = styled.div<Pick<InteractionProps, "index">>` ${({ theme, index }) => css` padding: 1rem; border-top: 1px solid ${theme.colors.default.border}; background: ${index % 2 === 0 && theme.components.sidebar.right.default.otherBg}; &:last-child { border-bottom: 1px solid ${theme.colors.default.border}; } `} `; const Name = styled.span` font-weight: bold; `; export default Interaction;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/index.ts
export { default } from "./Test";
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/CodeResult.tsx
import styled, { css } from "styled-components"; import CodeBlock, { CodeBlockProps } from "../../../../components/CodeBlock"; interface CodeResultProps extends CodeBlockProps { index: number; } const CodeResult = (props: CodeResultProps) => ( <StyledCodeBlock lang="json" {...props} /> ); const StyledCodeBlock = styled(CodeBlock)<CodeResultProps>` ${({ theme, index }) => css` width: 100%; user-select: text; & pre { padding: 1rem 0.5rem; background: ${index % 2 === 1 ? theme.components.sidebar.right.default.otherBg : theme.components.sidebar.right.default.bg} !important; } `} `; export default CodeResult;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/IdlProvider.tsx
import { FC, createContext, useContext } from "react"; import type { Idl } from "../../../../utils/pg/program-interaction"; interface IdlProviderProps { idl: Idl; } const IdlContext = createContext<IdlProviderProps | null>(null); const IdlProvider: FC<IdlProviderProps> = ({ children, ...props }) => { return <IdlContext.Provider value={props}>{children}</IdlContext.Provider>; }; export const useIdl = () => { const ix = useContext(IdlContext); if (!ix) throw new Error("IDL provider not provided"); return ix; }; export default IdlProvider;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Instruction/InstructionProvider.tsx
import { Dispatch, FC, SetStateAction, createContext, useContext } from "react"; import type { GeneratableInstruction } from "../../../../../utils/pg/program-interaction"; interface InstructionProviderProps { instruction: GeneratableInstruction; setInstruction: Dispatch<SetStateAction<GeneratableInstruction>>; } const InstructionContext = createContext<InstructionProviderProps | null>(null); const InstructionProvider: FC<InstructionProviderProps> = ({ children, ...props }) => { return ( <InstructionContext.Provider value={props}> {children} </InstructionContext.Provider> ); }; export const useInstruction = () => { const ix = useContext(InstructionContext); if (!ix) throw new Error("Instruction provider not provided"); return ix; }; export default InstructionProvider;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Instruction/FromSeed.tsx
import { FC, useMemo, useRef, useState } from "react"; import styled from "styled-components"; import InputLabel from "../InputLabel"; import InstructionInput from "./InstructionInput"; import Button from "../../../../../components/Button"; import Tooltip from "../../../../../components/Tooltip"; import SearchBar, { SearchBarDropdownProps, SearchBarProps, } from "../../../../../components/SearchBar"; import { Edit, Plus, Trash } from "../../../../../components/Icons"; import { IdlType, PgProgramInteraction, Seed as SeedType, } from "../../../../../utils/pg/program-interaction"; import { useInstruction } from "./InstructionProvider"; import { useKeybind } from "../../../../../hooks"; type FromSeedProps = { name: string; } & SearchBarDropdownProps; const FromSeed = ({ name, search }: FromSeedProps) => { const { values } = useInstruction().instruction; const [seeds, setSeeds] = useState< Array< | ({ state: "selecting" } & Partial<SeedType>) | ({ state: "selected" } & SeedType) > >(() => { // Restore if seeds are already set const acc = values.accounts.find((acc) => acc.name === name); if (acc && acc.generator.type === "From seed") { return acc.generator.seeds.map((seed) => ({ state: "selected", ...seed, })); } return [{ state: "selecting" }]; }); // Get whether the seeds are set initially in order to decide whether to // show seed input dropdowns const [isDefault, initialSeedsLength] = useMemo( () => [seeds.at(0)?.state === "selecting", seeds.length], // eslint-disable-next-line react-hooks/exhaustive-deps [] ); const showSelectedSeedDropdown = useMemo( () => isDefault || initialSeedsLength !== seeds.length, [isDefault, initialSeedsLength, seeds.length] ); // Default to instruction program ID but create a new object in order to // avoid accidentally updating the instruction program ID const programId = useRef({ ...values.programId }); const generate = () => { try { const selectedSeeds = seeds.filter( (seed) => seed.state === "selected" ) as SeedType[]; search({ label: "Seed label", value: PgProgramInteraction.generateProgramAddressFromSeeds( selectedSeeds, PgProgramInteraction.generateValue( programId.current.generator, values ), values ).toBase58(), data: { seeds: selectedSeeds, programId: programId.current, }, }); } catch (e: any) { console.log("Failed to generate address from seeds:", e.message); } }; useKeybind("Enter", () => { if (document.activeElement?.nodeName !== "INPUT") generate(); }); return ( <Wrapper> <SeedsWrapper> {seeds.map((seed, index) => ( <SeedWrapper key={index}> <SeedLabelWrapper> <InputLabel name={`seed(${index + 1})`} type={seed.state === "selected" ? seed.type.toString() : ""} /> <SeedLabelButtonsWrapper> {seed.state === "selected" && ( <Tooltip element="Edit seed"> <Button onClick={() => { setSeeds((seeds) => seeds.map((seed, i) => { return i === index ? { ...seed, state: "selecting" } : seed; }) ); }} kind="icon" > <Edit /> </Button> </Tooltip> )} <Tooltip element="Delete seed"> <Button onClick={() => { setSeeds((seeds) => seeds.filter((_, i) => i !== index)); }} kind="icon" hoverColor="error" > <Trash /> </Button> </Tooltip> </SeedLabelButtonsWrapper> </SeedLabelWrapper> {seed.state === "selecting" ? ( <SeedSearchBar select={(value) => setSeeds((seeds) => { return seeds.map((seed, i) => { if (i === index) { return { state: "selected", type: value as IdlType, generator: { type: "Custom", value: "" }, }; } return seed; }); }) } /> ) : ( <SelectedSeed index={index} seed={seed} searchBarProps={{ showSearchOnMount: showSelectedSeedDropdown }} /> )} </SeedWrapper> ))} </SeedsWrapper> <InstructionInput type="publicKey" prefix="seed" name="program" updateInstruction={({ updateGenerator }) => { updateGenerator(programId.current); }} searchBarProps={{ items: getProgramIdItems() }} {...values.programId} /> <SeedButtonsWrapper> <Button onClick={() => { setSeeds((seeds) => [...seeds, { state: "selecting" }]); }} leftIcon={<Plus />} > Add Seed </Button> <Button onClick={generate} kind="primary-transparent"> Generate </Button> </SeedButtonsWrapper> </Wrapper> ); }; const Wrapper = styled.div` padding: 0.5rem; display: flex; flex-direction: column; gap: 1rem; `; const SeedsWrapper = styled.div` display: flex; flex-direction: column; gap: 1rem; `; const SeedWrapper = styled.div``; const SeedLabelWrapper = styled.div` display: flex; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 0.25rem; `; const SeedLabelButtonsWrapper = styled.div` display: flex; `; const SeedButtonsWrapper = styled.div` display: flex; flex-direction: column; gap: 0.5rem; `; type SeedSearchBarProps = { select: (value: string) => void; }; const SeedSearchBar: FC<SeedSearchBarProps> = ({ select }) => { const [value, setValue] = useState(""); return ( <SearchBar value={value} onChange={(ev) => setValue(ev.target.value)} items={[ "string", "publicKey", "bytes", { label: "uint", items: ["u8", "u16", "u32", "u64", "u128"] }, { label: "int", items: ["i8", "i16", "i32", "i64", "i128"] }, ]} onSearch={({ item }) => select(item.label)} showSearchOnMount placeholder="Select seed" /> ); }; type SelectedSeedProps = { seed: SeedType; index: number; searchBarProps: Partial<SearchBarProps>; }; const SelectedSeed: FC<SelectedSeedProps> = ({ seed, index, searchBarProps, }) => ( <SelectedSeedWrapper> <InstructionInput prefix="seed" name={index.toString()} updateInstruction={({ updateGenerator }) => updateGenerator(seed)} searchBarProps={searchBarProps} noLabel {...seed} /> </SelectedSeedWrapper> ); const SelectedSeedWrapper = styled.div``; const getProgramIdItems = (): NonNullable<SearchBarProps["items"]> => [ { label: "Custom", value: { current: true } }, ...PgProgramInteraction.getPrograms().map((program, i) => ({ label: i === 0 ? "Current program" : program.name, value: program.programId, })), ]; export default FromSeed;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Instruction/Instruction.tsx
import { FC, useCallback, useEffect, useReducer, useState } from "react"; import styled from "styled-components"; import InstructionInput from "./InstructionInput"; import InstructionProvider from "./InstructionProvider"; import Interaction from "../Interaction"; import Button from "../../../../../components/Button"; import Foldable from "../../../../../components/Foldable"; import { Emoji } from "../../../../../constants"; import { PgCommand, PgCommon, PgConnection, PgSettings, PgTerminal, PgTx, } from "../../../../../utils/pg"; import { IdlInstruction, PgProgramInteraction, } from "../../.././../../utils/pg/program-interaction"; import { useWallet } from "../../../../../hooks"; import { useIdl } from "../IdlProvider"; interface InstructionProps { idlInstruction: IdlInstruction; index: number; } const Instruction: FC<InstructionProps> = ({ index, idlInstruction }) => { const [instruction, setInstruction] = useState(() => PgProgramInteraction.getOrCreateInstruction(idlInstruction) ); const [disabled, setDisabled] = useState(true); const [refreshCount, refreshFields] = useReducer((r) => r + 1, 0); const { idl } = useIdl(); // Enable when there is no args and no accounts. // // This is intentionally done in a `useEffect` instead of changing the // setting the default value of the `disabled`'s `useState` in order to: // - Enable the button when `idlInstruction` changes // - Avoid flickering of the Test button i.e. the button renders as enabled // and switches to disabled state after. useEffect(() => { if (!idlInstruction.args.length && !idlInstruction.accounts.length) { setDisabled(false); } }, [idlInstruction]); // Refresh instruction in order to pass the latest generators to // `InstructionInput`, otherwise the initial values are being generated // from stale data. // eslint-disable-next-line react-hooks/exhaustive-deps const refresh = useCallback( PgCommon.debounce(() => setInstruction((ix) => ({ ...ix })), { delay: 1000, }), [] ); // Save instruction on change useEffect( () => PgProgramInteraction.saveInstruction(instruction), [instruction] ); // Fill empty fields with Random generator const fillRandom = useCallback(() => { setInstruction((ix) => PgProgramInteraction.fillRandom(ix, idl)); // Refresh fields in order to re-render mapped elements refreshFields(); }, [idl]); // Reset the current instruction and re-crate it from default values const reset = useCallback(() => { // Reset and re-crate instruction setInstruction((ix) => { PgProgramInteraction.resetInstruction(ix); return PgProgramInteraction.getOrCreateInstruction(idlInstruction); }); // Refresh fields in order to re-render mapped elements refreshFields(); }, [idlInstruction]); const handleTest = async () => { const showLogTxHash = await PgTerminal.process(async () => { PgTerminal.log(PgTerminal.info(`Testing '${instruction.name}'...`)); try { const txHash = await PgCommon.transition( PgProgramInteraction.test(instruction) ); PgTx.notify(txHash); if (PgSettings.testUi.showTxDetailsInTerminal) return txHash; const txResult = await PgTx.confirm(txHash); const msg = txResult?.err ? `${Emoji.CROSS} ${PgTerminal.error( `Test '${instruction.name}' failed` )}.` : `${Emoji.CHECKMARK} ${PgTerminal.success( `Test '${instruction.name}' passed` )}.`; PgTerminal.log(msg + "\n", { noColor: true }); } catch (e: any) { console.log(e); const convertedError = PgTerminal.convertErrorMessage(e.message); PgTerminal.log( `${Emoji.CROSS} ${PgTerminal.error( `Test '${instruction.name}' failed` )}: ${convertedError}\n`, { noColor: true } ); } }); if (showLogTxHash) { await PgCommon.sleep( PgConnection.current.rpcEndpoint.startsWith("https") ? 1500 : 200 ); await PgCommand.solana.run("confirm", showLogTxHash, "-v"); } }; const { wallet } = useWallet(); return ( <InstructionProvider instruction={instruction} setInstruction={setInstruction} > <Interaction name={instruction.name} index={index}> <ArgsAndAccountsWrapper> {instruction.values.args.length > 0 && ( <Foldable element={<ArgsText>Args</ArgsText>} isOpen> <InstructionInputsWrapper> {instruction.values.args.map((arg) => ( <InstructionInput key={arg.name + refreshCount} prefix="args" updateInstruction={({ updateGenerator, updateRefs, checkErrors, }) => { updateGenerator(arg); updateRefs(arg, "Arguments"); setDisabled(checkErrors()); refresh(); }} {...arg} /> ))} </InstructionInputsWrapper> </Foldable> )} {instruction.values.accounts.length > 0 && ( <Foldable element={<AccountsText>Accounts</AccountsText>} isOpen> <InstructionInputsWrapper> {instruction.values.accounts.map((acc) => ( <InstructionInput key={acc.name + refreshCount} prefix="accounts" type="publicKey" updateInstruction={({ updateGenerator, updateRefs, checkErrors, }) => { updateGenerator(acc); updateRefs(acc, "Accounts"); setDisabled(checkErrors()); refresh(); }} {...acc} /> ))} </InstructionInputsWrapper> </Foldable> )} </ArgsAndAccountsWrapper> <ButtonWrapper> <Button kind="primary" onClick={handleTest} disabled={!wallet || disabled} > Test </Button> {(instruction.values.accounts.length > 0 || instruction.values.args.length > 0) && ( <> <Button onClick={fillRandom}>Fill</Button> <Button onClick={reset}>Reset</Button> </> )} </ButtonWrapper> </Interaction> </InstructionProvider> ); }; const ArgsAndAccountsWrapper = styled.div` padding-left: 0.25rem; & > div { margin-top: 1rem; } `; const InstructionInputsWrapper = styled.div` display: flex; flex-direction: column; gap: 0.5rem; font-size: ${({ theme }) => theme.font.code.size.small}; `; const ArgsText = styled.span``; const AccountsText = styled.span``; const ButtonWrapper = styled.div` display: flex; justify-content: center; margin-top: 1rem; gap: 1rem; & > button { padding: 0.5rem 1.5rem; } `; export default Instruction;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Instruction/InstructionInput.tsx
import { FC, useEffect, useMemo, useRef, useState } from "react"; import styled from "styled-components"; import FromSeed from "./FromSeed"; import Label from "../InputLabel"; import CopyButton from "../../../../../components/CopyButton"; import SearchBar, { SearchBarItem, SearchBarProps, } from "../../../../../components/SearchBar"; import { PgCommon, PgWallet, PgWeb3 } from "../../../../../utils/pg"; import { GeneratableInstruction, Idl, IdlType, InstructionValueGenerator, PgProgramInteraction, } from "../../../../../utils/pg/program-interaction"; import { useInstruction } from "./InstructionProvider"; import { useIdl } from "../IdlProvider"; type InstructionValues = GeneratableInstruction["values"]; type InstructionInputAccount = InstructionValues["accounts"][number]; type InstructionInputArg = InstructionValues["args"][number]; type InstructionInputProps = { prefix: "accounts" | "args" | "seed"; updateInstruction: (props: { updateGenerator: ( data: Pick<InstructionInputArg, "generator" | "error"> ) => void; updateRefs: ( data: Omit<InstructionInputArg, "type">, refGeneratorType: Extract< InstructionValueGenerator["type"], "Accounts" | "Arguments" > ) => void; checkErrors: () => boolean; }) => void; noLabel?: boolean; searchBarProps?: Omit<SearchBarProps, "value">; } & InstructionInputArg & Partial<InstructionInputAccount>; const InstructionInput: FC<InstructionInputProps> = ({ prefix, updateInstruction, name, type, generator, searchBarProps, noLabel, ...accountProps }) => { const { instruction, setInstruction } = useInstruction(); const { idl } = useIdl(); const { displayType, parse } = useMemo( () => PgProgramInteraction.getIdlType(type, idl), [type, idl] ); const initialValue = useMemo( () => generateValueOrDefault(generator, instruction.values), // eslint-disable-next-line react-hooks/exhaustive-deps [] ); const initialError = useMemo(() => { // Don't show errors when the initial input is empty if (!initialValue) return false; try { parse(initialValue); return false; } catch { return true; } }, [initialValue, parse]); const [value, setValue] = useState(initialValue); const [error, setError] = useState(initialError); const [selectedItems, setSelectedItems] = useState<SearchBarItem[]>([]); // Handle syncing with transaction context without re-render const lastValue = useRef({ value, error, selectedItems }); useEffect(() => { const newValue = { value, error, selectedItems }; if (PgCommon.isEqual(newValue, lastValue.current)) return; lastValue.current = newValue; setInstruction((instruction) => { updateInstruction({ updateGenerator: (data) => { const generator = PgProgramInteraction.createGenerator( selectedItems, value ); // Only update the generator if there is a generator otherwise the // existing generator can be overridden if (generator) data.generator = generator; data.error = error; }, updateRefs: (data, refGeneratorType) => { if (!value) return; for (const key of ["accounts", "args"] as const) { // Default ref for (const instructionValue of instruction.values[key]) { if ( instructionValue.generator.type === refGeneratorType && instructionValue.generator.name === data.name ) { const inputEl = document.getElementById( instruction.name + key + instructionValue.name ) as HTMLInputElement; PgCommon.changeInputValue(inputEl, value); } // From seed if ( instructionValue.generator.type === "From seed" && instructionValue.generator.seeds.some( (seed) => seed.generator.type === refGeneratorType && seed.generator.name === data.name ) ) { const inputEl = document.getElementById( instruction.name + key + instructionValue.name ) as HTMLInputElement; const newValue = generateValueOrDefault( instructionValue.generator, instruction.values ); PgCommon.changeInputValue(inputEl, newValue); } } } }, checkErrors: () => { return Object.values(instruction.values).reduce((acc, value) => { if (Array.isArray(value)) { acc ||= value.some( (v) => v.error || (v.generator.type === "Custom" && v.generator.value === "") ); } return acc; }, false); }, }); return instruction; }); }, [value, error, selectedItems, updateInstruction, setInstruction]); return ( <Wrapper> {!noLabel && ( <Row> <Label name={name} type={displayType} {...accountProps} /> </Row> )} <Row> <InputWithCopyButtonWrapper> <SearchBar id={instruction.name + prefix + name} value={value} onChange={(ev) => setValue(ev.target.value)} error={error} setError={setError} setSelectedItems={setSelectedItems} restoreIfNotSelected labelToSelectOnPaste="Custom" {...getSearchBarProps( name, type, generator, accountProps, instruction, idl )} {...searchBarProps} /> <CopyButtonWrapper> <CopyButton copyText={value} /> </CopyButtonWrapper> </InputWithCopyButtonWrapper> </Row> </Wrapper> ); }; const Wrapper = styled.div` display: flex; flex-direction: column; `; const Row = styled.div` display: flex; `; const InputWithCopyButtonWrapper = styled.div` width: 100%; display: flex; & > *:first-child { flex: 1; margin-right: 0.25rem; } `; const CopyButtonWrapper = styled.div` height: 2rem; display: flex; align-items: center; `; const getSearchBarProps = ( name: string, type: IdlType, generator: InstructionValueGenerator & { name?: string; value?: string }, accountProps: Partial<Pick<InstructionInputAccount, "isMut" | "isSigner">>, instruction: GeneratableInstruction, idl: Idl ) => { const customizable = PgProgramInteraction.getIdlType(type, idl); const searchBarProps: Omit<SearchBarProps, "value"> & { noCustomOption?: boolean; } = {}; // Items searchBarProps.items = [ { label: "Random", value: customizable.generateRandom, }, ]; // Generate values via `generateValueOrDefault` method and push to items. const pushGeneratorItem = ( generator: | (Pick<Exclude<InstructionValueGenerator, { name: string }>, "type"> & { names?: never; }) | (Pick<Extract<InstructionValueGenerator, { name: string }>, "type"> & { names: string[]; }) ) => { if (!searchBarProps.items) return; if (!generator.names) { searchBarProps.items.push({ label: generator.type, value: generateValueOrDefault( generator as InstructionValueGenerator, instruction.values ), }); } else if (generator.names.length) { searchBarProps.items.push({ label: generator.type, items: generator.names.map((name) => ({ label: name, value: generateValueOrDefault( { ...generator, name }, instruction.values ), })), }); } }; if (customizable.displayType === "bool") { searchBarProps.items.push("false", "true"); searchBarProps.noCustomOption = true; } else if (customizable.displayType === "publicKey") { // Handle "Random" for "publicKey" differently in order to be able to // sign the transaction later with the generated key searchBarProps.items[0] = { label: "Random", data: Array.from(PgWeb3.Keypair.generate().secretKey), get value() { return PgWeb3.Keypair.fromSecretKey( Uint8Array.from((this as { data: number[] }).data) ).publicKey.toBase58(); }, }; // Wallet(s) if (PgWallet.current) { pushGeneratorItem({ type: "Current wallet" }); if (PgWallet.accounts.length > 1) { pushGeneratorItem({ type: "All wallets", names: PgWallet.accounts.map((acc) => acc.name), }); } } // From seed searchBarProps.items.push({ label: "From seed", DropdownComponent: (props) => <FromSeed {...props} name={name} />, closeButton: true, }); // Programs if (!(accountProps.isMut || accountProps.isSigner)) { pushGeneratorItem({ type: "All programs", names: PgProgramInteraction.getPrograms().map((p) => p.name), }); } // Pyth if (!(accountProps.isMut || accountProps.isSigner)) { searchBarProps.items.push({ label: "Pyth", items: async () => { const accounts = await PgProgramInteraction.getOrInitPythAccounts(); return Object.entries(accounts).map(([label, value]) => ({ label, value, })); }, }); } } else { // Handle enum const definedType = idl.types?.find( (t) => t.name === customizable.displayType )?.type; if (definedType?.kind === "enum") { const enumItems = definedType.variants.map((variant) => { const camelCaseName = PgCommon.toCamelCase(variant.name); // Unit if (!variant.fields?.length) return camelCaseName; const lowerCaseName = camelCaseName.toLowerCase(); const createValue = (value: string, defaultValue: string) => { if (value.toLowerCase().includes(lowerCaseName)) return value; return defaultValue; }; const matches = (value: string) => { if (!value) return true; const lowerCaseValue = value.toLowerCase(); if (lowerCaseName.includes(lowerCaseValue)) return true; return new RegExp(lowerCaseName).test(lowerCaseValue); }; // Named if ((variant.fields[0] as { name?: string }).name) { return { label: camelCaseName, value: (v: string) => createValue(v, `{ ${camelCaseName}: {...} }`), matches, }; } // Tuple return { label: camelCaseName, value: (v: string) => createValue(v, `{ ${camelCaseName}: [...] }`), matches, }; }); searchBarProps.items.push(...enumItems); searchBarProps.noCustomOption = true; } } // Add argument refs pushGeneratorItem({ type: "Arguments", names: instruction.values.args .filter((arg) => arg.name !== name && PgCommon.isEqual(arg.type, type)) .map((arg) => arg.name), }); // Add account refs pushGeneratorItem({ type: "Accounts", names: instruction.values.accounts .filter((acc) => acc.name !== name && type === "publicKey") .map((acc) => acc.name), }); // Add custom value after type overrides to get `noCustomOption` if (!searchBarProps.noCustomOption) { searchBarProps.items.unshift({ label: "Custom", value: { current: true }, onlyShowIfValid: true, }); } // Initial items to select searchBarProps.initialSelectedItems = searchBarProps.noCustomOption ? generator.type === "Custom" ? generator.value === "" ? [] : generator.value : generator.type : generator.name ? [generator.type, generator.name] : generator.type === "Random" ? { label: generator.type, data: generator.data } : generator.type; // Validator searchBarProps.validator = (...args) => { try { customizable.parse(...args); return true; } catch { return false; } }; return searchBarProps; }; /** Generate the value or default to an empty string in the case of an error. */ const generateValueOrDefault = ( generator: InstructionValueGenerator, values: InstructionValues ) => { try { return PgProgramInteraction.generateValue(generator, values); } catch (e: any) { console.log("Failed to generate:", e.message); return ""; } }; export default InstructionInput;
0
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component
solana_public_repos/solana-playground/solana-playground/client/src/views/sidebar/test/Component/Instruction/index.ts
export { default } from "./Instruction";
0