如何为Umi实例定义mySigner以使用signerIdentity插件?
如何定义Umi实例所需的mySigner常量
你的代码中mySigner的定义方式取决于具体使用场景,以下是几种常见实现方案:
1. 本地脚本/后端:从密钥对生成签名者
适合后端服务或本地离线脚本,可通过生成新密钥对或导入已有私钥创建:
import { createUmi } from "@metaplex-foundation/umi-bundle-defaults"; import { mplCandyMachine } from "@metaplex-foundation/mpl-candy-machine"; import { publicKey, signerIdentity, generateSigner, createSignerFromKeypair } from "@metaplex-foundation/umi"; // 方式一:生成全新的密钥对签名者 const umi = createUmi(endpoint); const mySigner = generateSigner(umi); // 方式二:从已有的私钥创建(注意:私钥切勿硬编码到前端代码) // const myKeypair = umi.eddsa.createKeypairFromSecretKey(new Uint8Array([/* 你的私钥字节数组 */])); // const mySigner = createSignerFromKeypair(umi, myKeypair); export const umiInstance = umi .use(signerIdentity(mySigner)) .use(mplCandyMachine());
2. 前端场景:从浏览器钱包获取签名者
如果是前端应用,建议用钱包适配器(比如Phantom)让用户授权,避免暴露私钥:
import { createUmi } from "@metaplex-foundation/umi-bundle-defaults"; import { mplCandyMachine } from "@metaplex-foundation/mpl-candy-machine"; import { signerIdentity } from "@metaplex-foundation/umi"; import { walletAdapterIdentity } from "@metaplex-foundation/umi-signer-wallet-adapters"; import { PhantomWalletAdapter } from "@solana/wallet-adapter-phantom"; // 初始化Phantom钱包适配器 const wallet = new PhantomWalletAdapter(); // 触发钱包连接 await wallet.connect(); export const umi = createUmi(endpoint) .use(walletAdapterIdentity(wallet)) .use(mplCandyMachine());
3. 只读场景:创建只读签名者
如果仅需执行查询操作、不需要发起交易,可以用只读签名者(仅需提供公钥):
import { createUmi } from "@metaplex-foundation/umi-bundle-defaults"; import { mplCandyMachine } from "@metaplex-foundation/mpl-candy-machine"; import { publicKey, signerIdentity, createReadOnlySigner } from "@metaplex-foundation/umi"; // 传入目标公钥创建只读签名者 const mySigner = createReadOnlySigner(publicKey("替换为你的公钥地址")); export const umi = createUmi(endpoint) .use(signerIdentity(mySigner)) .use(mplCandyMachine());
注意事项
- 前端绝对不要硬编码私钥,必须通过钱包适配器让用户自主授权
- 私钥属于敏感信息,泄露会导致资产损失,务必妥善保管
内容的提问来源于stack exchange,提问作者Miles Donald
相关产品推荐
相关产品推荐

