Skip to content

锁定和解锁

我们可以对 Wallet 实例执行的操作类型取决于我们是否可以访问钱包的私钥。

为了区分已知私钥的Wallet 实例和未知私钥的实例,我们分别使用WalletUnlockedWalletLocked类型。

钱包状态

WalletUnlocked 表示一个钱包,其私钥是已知的并且存储在内存中。必须使用WalletUnlocked类型的钱包才能执行涉及签名消息或交易的操作。

WalletLocked 类型表示私钥未知或未存储在内存中的钱包。相反,WalletLocked 只知道它的公共地址。 WalletLocked无法用于签名交易,但仍然可以执行一系列有用的操作,如列出交易、资产、查询余额等。

请注意,WalletUnlocked 类型实现了WalletLocked类型上的大多数方法。换句话说,WalletUnlocked可以视为WalletLocked的薄包装器,通过其私钥提供更大的访问权限。

基本示例

ts
// #import { Wallet, WalletLocked, WalletUnlocked };

// We can use the `generate` to create a new unlocked wallet.
const myWallet: WalletUnlocked = Wallet.generate({ provider });

// or use an Address to create a wallet
const someWallet: WalletLocked = Wallet.fromAddress(myWallet.address, provider);

可选的 Provider

在构建 Wallet 时,你可以选择不传递provider参数:

ts
// #context import { Wallet, WalletUnlocked } from 'fuels';

// You can create a wallet, without a provider
let unlockedWallet: WalletUnlocked = Wallet.generate();
unlockedWallet = Wallet.fromPrivateKey(unlockedWallet.privateKey);

// All non-provider dependent methods are available
unlockedWallet.lock();

// All provider dependent methods will throw
await expect(() => unlockedWallet.getCoins()).rejects.toThrow(/Provider not set/);

转换状态

WalletLocked 实例可以通过提供私钥来解锁:

ts
// #import { Wallet, WalletLocked, WalletUnlocked };

// Lock an existing wallet
const lockedWallet: WalletLocked = Wallet.fromAddress(myWallet.address, provider);

// Unlock an existing wallet
const unlockedWallet: WalletUnlocked = lockedWallet.unlock(PRIVATE_KEY);

WalletUnlocked 实例可以使用lock方法锁定:

ts
const newlyLockedWallet = unlockedWallet.lock();

大多数创建或生成新钱包的 Wallet 构造函数都位于WalletUnlocked类型上。在处理完新的私钥后,考虑使用lock方法锁定钱包,以减少私钥在内存中存储的时间和范围。

设计指南

当设计接受钱包作为输入的API时,我们需要仔细考虑所需的访问级别。API开发者应尽量减少使用WalletUnlocked,以确保私钥在内存中存储的时间尽可能短,从而减少下游库和应用程序的安全风险区域。