LoginSignup
0
0

Replace public key in solana project

Last updated at Posted at 2024-03-27

View the public key of an existing project

anchor keys list

Generate a new private key

solana-keygen new -s -f --no-bip39-passphrase -o new-keypair.json
cp -f ./new-keypair.json ./target/deploy/abc-keypair.json

Replace the public key

replace the public key in the declare_id and Anchor. toml files,run the following command:

anchor keys sync

python version

import os
import re
import toml
import subprocess

keyfile = "./new-keypair.json"

# mkdir -p ./target/deploy
dirshell = ['mkdir', '-p', './target/deploy']
ok = subprocess.run(dirshell, capture_output=True, text=True)

# solana-keygen new -s --force --no-bip39-passphrase -o new-keypair.json
shell = ['solana-keygen', 'new', '-s','--force', '--no-bip39-passphrase', '-o', keyfile]
result1 = subprocess.run(shell, capture_output=True, text=True)
print(result1.stdout)

# cp -f ./new-keypair.json ./target/deploy/abc-keypair.json
cpshell = ['cp', '-f', keyfile, './target/deploy/abc-keypair.json']
subprocess.run(cpshell, capture_output=True, text=True)
print("create new keypair file: ", "./target/deploy/abc-keypair.json")

# solana address -k ./new-keypair.json
solanashell = ['solana', 'address', '-k', keyfile]
result2 = subprocess.run(solanashell, capture_output=True, text=True)

addr = result2.stdout.replace("\n", "")
print("ProjectId: ", addr)

declare_id_regex = r"^(([\w]+::)*)declare_id!\(\"(\w*)\"\)"

rsfile = "./programs/abc/src/lib.rs"
with open(rsfile, 'r') as file:
    libdata = file.read()

    change_str = f'declare_id!("{addr}")'
    libresult = re.sub(declare_id_regex, change_str, libdata, 0, re.MULTILINE)

with open(rsfile, 'w') as file:
    file.write(libresult)

tomlfile = "./Anchor.toml"
with open(tomlfile, 'r') as file:
   tomldata = toml.load(file)

tomldata['programs']['localnet']['abc'] = addr

with open(tomlfile, 'w') as file:
    toml.dump(tomldata, file)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0