From 2b181aa0f7749692943b266c5753c1dcc6c88d5c Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Wed, 5 Jul 2023 14:55:14 +0200 Subject: [PATCH] Allow wallet to be instantiated with a PrivateKey --- ethers/wallet.nim | 23 ++++++++++++----------- testmodule/testWallet.nim | 2 ++ 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/ethers/wallet.nim b/ethers/wallet.nim index d22b835..d53b8b9 100644 --- a/ethers/wallet.nim +++ b/ethers/wallet.nim @@ -21,17 +21,18 @@ type Wallet* = ref object of Signer address*: Address provider*: ?Provider -proc new*(_: type Wallet, pk: string, provider: Provider): Wallet = - result = Wallet() - result.privateKey = PrivateKey.fromHex(pk).value - result.publicKey = result.privateKey.toPublicKey() - result.address = Address.init(result.publicKey.toCanonicalAddress()) - result.provider = some provider -proc new*(_: type Wallet, pk: string): Wallet = - result = Wallet() - result.privateKey = PrivateKey.fromHex(pk).value - result.publicKey = result.privateKey.toPublicKey() - result.address = Address.init(result.publicKey.toCanonicalAddress()) +proc new*(_: type Wallet, privateKey: PrivateKey): Wallet = + let publicKey = privateKey.toPublicKey() + let address = Address.init(publicKey.toCanonicalAddress()) + Wallet(privateKey: privateKey, publicKey: publicKey, address: address) +proc new*(_: type Wallet, privateKey: PrivateKey, provider: Provider): Wallet = + let wallet = Wallet.new(privateKey) + wallet.provider = some provider + wallet +proc new*(_: type Wallet, privateKey: string): Wallet = + Wallet.new(PrivateKey.fromHex(privateKey).value) +proc new*(_: type Wallet, privateKey: string, provider: Provider): Wallet = + Wallet.new(PrivateKey.fromHex(privateKey).value, provider) proc connect*(wallet: Wallet, provider: Provider) = wallet.provider = some provider proc createRandom*(_: type Wallet): Wallet = diff --git a/testmodule/testWallet.nim b/testmodule/testWallet.nim index 366a489..6b60f1d 100644 --- a/testmodule/testWallet.nim +++ b/testmodule/testWallet.nim @@ -27,6 +27,7 @@ suite "Wallet": test "Can create Wallet with private key": discard Wallet.new(pk1) + discard Wallet.new(PrivateKey.fromHex(pk1).value) test "Private key can start with 0x": discard Wallet.new("0x" & pk1) @@ -34,6 +35,7 @@ suite "Wallet": test "Can create Wallet with provider": let provider = JsonRpcProvider.new() discard Wallet.new(pk1, provider) + discard Wallet.new(PrivateKey.fromHex(pk1).value) test "Can connect Wallet to provider": let wallet = Wallet.new(pk1)