Created
April 23, 2024 13:53
-
-
Save chongkan/edffe0613cad007322ea486e323e0f72 to your computer and use it in GitHub Desktop.
Solana Create Nonce Account
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
Keypair, | |
NONCE_ACCOUNT_LENGTH, | |
SystemProgram, | |
TransactionMessage, | |
VersionedTransaction | |
} from "@solana/web3.js"; | |
class AccHelper { | |
/** | |
* | |
* @description Create a new NONCE Account | |
* @param {Connection} connection - The connection object to custom RPC | |
* @param {Keypair} authority - The authority keypair | |
* @param {Keypair} feePayer - The fee payer keypair (usually the wallet signer & 1st signer in the transaction**) | |
* @returns {Promise<object>} - The account object | |
* @example | |
* const account = await Account.createAccount(connection, authority, feePayer); | |
* console.log(account); | |
*/ | |
static async createNonceAccount({ connection, authority, dapp }) { | |
const nAcc = Keypair.generate(); | |
// Instructions | |
const instructions = [ | |
SystemProgram.createAccount({ | |
fromPubkey: authority.publicKey, | |
newAccountPubkey: nAcc.publicKey, | |
lamports: await connection.getMinimumBalanceForRentExemption( | |
NONCE_ACCOUNT_LENGTH | |
), | |
space: NONCE_ACCOUNT_LENGTH, | |
programId: SystemProgram.programId, | |
}), | |
SystemProgram.nonceInitialize({ | |
noncePubkey: nAcc.publicKey, | |
authorizedPubkey: dapp, // nonce account authority (for advance and close) | |
}) | |
]; | |
// Message | |
const messageV0 = new TransactionMessage({ | |
payerKey: authority.publicKey, | |
recentBlockhash: (await connection.getRecentBlockhash()).blockhash, | |
instructions, | |
}).compileToV0Message(); | |
// Signing | |
const transactionV0 = new VersionedTransaction(messageV0); | |
transactionV0.sign([nAcc]); | |
console.log("TransactionV0 signed by NEW NonceAccount: ", transactionV0); | |
const stx = await authority.signTransaction(transactionV0); | |
console.log("Signature by Wallet: ", stx); | |
// TODO. Is this correct? | |
transactionV0.signatures[0] = stx.signatures[0]; | |
console.log("TransactionV0 signed by Wallet: ", transactionV0); | |
// TODO move elsewhere | |
const serialized = transactionV0.serialize(); | |
localStorage.setItem("serializedTxnSigned", serialized); | |
const txId = await connection.sendRawTransaction(serialized); | |
console.log("Transaction ID: ", txId); | |
return { txId, nAcc }; | |
} | |
} | |
export default AccHelper; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment