Created
April 27, 2024 22:14
-
-
Save 0xcen/bf53fa7e59631ac183dcb2dc78b95cb9 to your computer and use it in GitHub Desktop.
This file contains 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 { BN } from '@coral-xyz/anchor'; | |
import { PublicKey } from '@solana/web3.js'; | |
import { stringify, parse } from 'json-bigint'; | |
import fs from 'fs'; | |
const file = 'tests/accounts/token_account.json'; // Replace with the path to your JSON file | |
const account = fs.readFileSync(file, 'utf8'); | |
const newU64 = new BN(90000000000); // Replace with the desired u64 value | |
const parsedAccount = parse(account); | |
console.log('Reading account data from:', file); | |
const prevBuffer = Buffer.from(parsedAccount.account.data[0], 'base64'); | |
console.log( | |
'Account mint:', | |
new PublicKey(prevBuffer.subarray(0, 32)).toBase58() | |
); | |
console.log( | |
'Account owner:', | |
new PublicKey(prevBuffer.subarray(32, 64)).toBase58() | |
); | |
console.log( | |
'Initial account value:', | |
new BN(prevBuffer.subarray(64, 72), 'le').toString() | |
); | |
// Extract the 8 bytes as a big-endian u64 | |
const uint8Array = new Uint8Array(prevBuffer); | |
console.log('New account value:', newU64.toString()); | |
// Convert the new u64 to bytes and replace the original bytes | |
const nextAmount = newU64.toBuffer('le', 8); | |
uint8Array.set(nextAmount, 64); | |
const nextBuffer = Buffer.from(uint8Array); | |
console.log( | |
'Updated account mint:', | |
new PublicKey(nextBuffer.subarray(0, 32)).toBase58() | |
); | |
console.log( | |
'Updated account owner:', | |
new PublicKey(nextBuffer.subarray(32, 64)).toBase58() | |
); | |
console.log( | |
'Updated account value:', | |
new BN(nextBuffer.subarray(64, 72), 'le').toString() | |
); | |
const updatedAccount = { | |
...parsedAccount.account, | |
data: [nextBuffer.toString('base64'), 'base64'], | |
}; | |
const updatedJsonData = { | |
...parsedAccount, | |
account: { | |
...updatedAccount, | |
rentEpoch: parsedAccount.account.rentEpoch, | |
}, | |
pubkey: parsedAccount.pubkey, | |
}; | |
fs.writeFileSync(file, stringify(updatedJsonData, null, 2)); | |
console.log('Account data updated and written back to:', file); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment