Allow wallet to be instantiated with a PrivateKey

This commit is contained in:
Mark Spanbroek 2023-07-05 14:55:14 +02:00 committed by markspanbroek
parent 5ed3f15706
commit 2b181aa0f7
2 changed files with 14 additions and 11 deletions

View File

@ -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 =

View File

@ -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)