Skip to content

Commit

Permalink
Tidy
Browse files Browse the repository at this point in the history
  • Loading branch information
rianhughes committed Aug 1, 2023
1 parent 19f835f commit 7b98e27
Showing 1 changed file with 31 additions and 92 deletions.
123 changes: 31 additions & 92 deletions examples/deployAccount/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

var (
name string = "testnet"
network string = "testnet"
predeployedClassHash = "0x2794ce20e5f2ff0d40e632cb53845b9f4e526ebd8471983f7dbd355b721d5a"
)

Expand All @@ -41,14 +41,11 @@ func getRandomKeys() (*felt.Felt, *felt.Felt) {
}

// precomputeAddress computes the address by hashing the relevant data.
// Note: order matters. Also, use ComputeHashOnElements on CallData if it has multiple values.
// ref: https://github.com/starkware-libs/cairo-lang/blob/master/src/starkware/starknet/core/os/contract_address/contract_address.py
// TODO: Move to contract / utils package
func precomputeAddress(deployerAddress *felt.Felt, salt *felt.Felt, classHash *felt.Felt, constructorCalldata []*felt.Felt) (*felt.Felt, error) {
CONTRACT_ADDRESS_PREFIX := new(felt.Felt).SetBytes([]byte("STARKNET_CONTRACT_ADDRESS"))

constructorCalldataBigIntArr, err := utils.FeltArrToBigIntArr(constructorCalldata)
constructorCallDataHashInt, _ := starknetgo.Curve.ComputeHashOnElements(*constructorCalldataBigIntArr)

bigIntArr, err := utils.FeltArrToBigIntArr([]*felt.Felt{
CONTRACT_ADDRESS_PREFIX,
deployerAddress,
Expand All @@ -58,6 +55,9 @@ func precomputeAddress(deployerAddress *felt.Felt, salt *felt.Felt, classHash *f
if err != nil {
return nil, err
}

constructorCalldataBigIntArr, err := utils.FeltArrToBigIntArr(constructorCalldata)
constructorCallDataHashInt, _ := starknetgo.Curve.ComputeHashOnElements(*constructorCalldataBigIntArr)
*bigIntArr = append(*bigIntArr, constructorCallDataHashInt)

preBigInt, err := starknetgo.Curve.ComputeHashOnElements(*bigIntArr)
Expand All @@ -80,9 +80,10 @@ func computeHashOnElementsFelt(feltArr []*felt.Felt) (*felt.Felt, error) {
return utils.BigIntToFelt(hash)
}

// calculateDeployAccountTransactionHash computes the transaction hash for deployAccount transactions
func calculateDeployAccountTransactionHash(tx rpcv02.BroadcastedDeployAccountTransaction, contractAddress *felt.Felt, chainID string) (*felt.Felt, error) {
Prefix_DEPLOY_ACCOUNT := new(felt.Felt).SetBytes([]byte("deploy_account")) // correct?
chainIdFelt := new(felt.Felt).SetBytes([]byte(chainID)) // correct?
Prefix_DEPLOY_ACCOUNT := new(felt.Felt).SetBytes([]byte("deploy_account"))
chainIdFelt := new(felt.Felt).SetBytes([]byte(chainID))

calldata := []*felt.Felt{tx.ClassHash, tx.ContractAddressSalt}
calldata = append(calldata, tx.ConstructorCalldata...)
Expand Down Expand Up @@ -132,58 +133,24 @@ func calculateTransactionHashCommon(
return computeHashOnElementsFelt(dataToHash)
}

// 1. Precompute addresss [Done!]
// 2. Fund account
// 3. Deploy (can use provider or account)

func main() {
// // init starknet gateway client
godotenv.Load(".env.testnet")
// Initialise the client.
godotenv.Load(fmt.Sprintf(".env.%s", network))
base := os.Getenv("INTEGRATION_BASE")
c, err := ethrpc.DialContext(context.Background(), base)
if err != nil {
panic(err)
}
clientv02 := rpcv02.NewProvider(c)

// Precompute address
// Get keys
pub, priv := getRandomKeys()
constructorCallData := []*felt.Felt{pub}
deployerAddress := &felt.Zero
classHash, err := utils.HexToFelt(predeployedClassHash)
if err != nil {
panic(err)
}
fmt.Println(deployerAddress, pub, classHash, constructorCallData)
precomputedAddress, err := precomputeAddress(deployerAddress, pub, classHash, constructorCallData)

fmt.Println("precomputedAddress:", precomputedAddress)

// Create starknet account
fmt.Println("Initialising NewMemKeystore..")
ks := starknetgo.NewMemKeystore()
fmt.Println("Initialising NewRPCAccount..")
account, err := starknetgo.NewRPCAccount(pub, precomputedAddress, ks, clientv02)
classHash, err := utils.HexToFelt(predeployedClassHash)
if err != nil {
panic(err)
}

// At this point you need to add funds to the deployed account in order to use it.
// Fund address
var input string
fmt.Println("The deployed account has to be feeded with ETH to perform transaction.")
fmt.Print("When your account has been funded with the faucet, press any key and enter to continue : ")
fmt.Scan(&input)

// Submit transaction to the network
fmt.Println("Initialised account with address:", account.AccountAddress)
fmt.Println("NOTE: Not using account to deployAccount as that method doesn't exist. Going to use provider for now.")

// NEXT: construct tx correctly
// To Sign
// ref : https://github.com/0xs34n/starknet.js/blob/develop/src/signer/default.ts#L63C1-L63C46
// signDeployAccountTransaction -> calculateDeployAccountTransactionHash -> calculateTransactionHashCommon -> computeHashOnElements

tx := rpcv02.BroadcastedDeployAccountTransaction{
BroadcastedTxnCommonProperties: rpcv02.BroadcastedTxnCommonProperties{
Nonce: &felt.Zero, // Contract accounts start with nonce zero.
Expand All @@ -196,68 +163,40 @@ func main() {
ContractAddressSalt: pub,
ConstructorCalldata: []*felt.Felt{pub},
}
fmt.Println("tx:", tx)
fmt.Println("constructorCallData:", constructorCallData)

// To sign the tranaction you need to:
// 1. Compute its transaction hash
// 2. and then sign it.
hash, err := calculateDeployAccountTransactionHash(tx, precomputedAddress, "SN_GOERLI") // TODO : fix inputs
precomputedAddress, err := precomputeAddress(&felt.Zero, pub, classHash, tx.ConstructorCalldata)
fmt.Println("precomputedAddress:", precomputedAddress)

// At this point you need to add funds to precomputed address to use it.
var input string
fmt.Println("The `precomputedAddress` account needs to have enough ETH to perform a transaction.")
fmt.Print("When your account has been funded by the faucet, press any key and enter to continue : ")
fmt.Scan(&input)

// Get the chainID to sign the transaction
chainId, err := clientv02.ChainID(context.Background())
if err != nil {
panic(err)
}

// Calculate and sign the transaction hash
hash, err := calculateDeployAccountTransactionHash(tx, precomputedAddress, chainId)
if err != nil {
panic(err)
}
fmt.Println(hash)
fmt.Println("Transaction hash:", hash)
x, y, err := starknetgo.Curve.SignFelt(hash, priv)
if err != nil {
panic(err)
}
fmt.Println(x, y)
tx.Signature = []*felt.Felt{x, y}

// NOTE: this is currently unstable due to context cancelling..
// Send transaction to the network
resp, err := clientv02.AddDeployAccountTransaction(context.Background(), tx)
if err != nil {
panic(err)
}

fmt.Println("AddDeployAccountTransaction response:", resp)

// increment := []types.FunctionCall{
// {
// ContractAddress: counterContAddress,
// EntryPointSelector: types.GetSelectorFromNameFelt("increment"),
// },
// }

// // estimate fee for executing transaction
// feeEstimate, err := account.EstimateFee(context.Background(), increment, types.ExecuteDetails{})
// if err != nil {
// panic(err.Error())
// }
// fee, _ := big.NewInt(0).SetString(string(feeEstimate.OverallFee), 0)
// expandedFee := big.NewInt(0).Mul(fee, big.NewInt(int64(feeMargin)))
// max := big.NewInt(0).Div(expandedFee, big.NewInt(100))
// fmt.Printf("Fee:\n\tEstimate\t\t%v wei\n\tEstimate+Margin\t\t%v wei\n\n", feeEstimate.OverallFee, max)

// // execute transaction
// execResp, err := account.Execute(context.Background(), increment, types.ExecuteDetails{MaxFee: big.NewInt(1000000000000)})
// if err != nil {
// panic(err.Error())
// }

// n, receipt, err := gw.WaitForTransaction(context.Background(), execResp.TransactionHash.String(), pollInterval, maxPoll)
// if err != nil {
// panic(err.Error())
// }
// fmt.Printf("Poll %dsec %dx \n\ttransaction(%s) receipt: %s\n\n", n*pollInterval, n, execResp.TransactionHash, receipt.Status)

// // get count after tx
// callResp, err = gw.Call(context.Background(), types.FunctionCall{
// ContractAddress: counterContAddress,
// EntryPointSelector: types.GetSelectorFromNameFelt("get_count"),
// }, "")
// if err != nil {
// panic(err.Error())
// }
// fmt.Println("Counter is currently at: ", callResp[0])
}

0 comments on commit 7b98e27

Please sign in to comment.