Skip to content

Commit

Permalink
Add StandardAccount.generatePrivateKey() (#507)
Browse files Browse the repository at this point in the history
  • Loading branch information
franciszekjob authored Aug 29, 2024
1 parent 2bae98e commit 56d1665
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import com.swmansion.starknet.provider.exceptions.RequestFailedException
import com.swmansion.starknet.signer.Signer
import com.swmansion.starknet.signer.StarkCurveSigner
import java.math.BigInteger
import java.security.SecureRandom
import java.util.concurrent.CompletableFuture

/**
Expand Down Expand Up @@ -97,6 +98,21 @@ class StandardAccount @JvmOverloads constructor(
val contract = provider.getClassAt(address).send()
return if (contract is ContractClass) CairoVersion.ONE else CairoVersion.ZERO
}

/**
* Generate a random private key.
*
* @return private key
*/
@JvmStatic
fun generatePrivateKey(): Felt {
val random = SecureRandom()
val randomBytes = ByteArray(32)
random.nextBytes(randomBytes)
val randomInt = BigInteger(1, randomBytes)
val privateKey = randomInt % Felt.PRIME
return privateKey.toFelt
}
}

override fun signV1(calls: List<Call>, params: ExecutionParams, forFeeEstimate: Boolean): InvokeTransactionV1Payload {
Expand Down
7 changes: 7 additions & 0 deletions lib/src/test/kotlin/starknet/account/StandardAccountTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,13 @@ class StandardAccountTest {
StandardAccount(Felt.ZERO, privateKey, provider, chainId)
}

@Test
fun `generate random private key`() {
val randomPrivateKey = StandardAccount.generatePrivateKey()
assertTrue(randomPrivateKey.value < Felt.PRIME)
assertTrue(randomPrivateKey.hexStringPadded().length == 66)
}

@Test
fun `cairo 0 account with automatic version detection`() {
val call = Call(
Expand Down
4 changes: 4 additions & 0 deletions lib/starknet-jvm.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,10 @@ public class Main {

// Create an account interface
Felt privateKey = Felt.fromHex("0x123");

// You can also generate a random private key
Felt randomPrivateKey = StarknetCurve.generatePrivateKey();

Felt publicKey = StarknetCurve.getPublicKey(privateKey);

// Use the class hash of the desired account contract (i.e. the class hash of OpenZeppelin account contract)
Expand Down

0 comments on commit 56d1665

Please sign in to comment.