Я пытаюсь отозвать удержанные сборы за плату за перевод Solana, но получение неверной ошибки учетной записи, вот мой код: < /p>
import { Connection, Keypair, PublicKey, Transaction, sendAndConfirmTransaction } from '@solana/web3.js';
import {
TOKEN_2022_PROGRAM_ID,
getTransferFeeAmount,
unpackAccount,
withdrawWithheldTokensFromAccounts,
createAssociatedTokenAccountInstruction,
getAssociatedTokenAddress,
} from '@solana/spl-token';
import dotenv from 'dotenv';
dotenv.config();
if (!process.env.RECIPIENT_KEYPAIR) {
throw new Error('Necessary keypairs not found, have you run the create-token and mint-and-transfer scripts?');
}
const connection = new Connection(process.env.RPC_URL, 'confirmed');
const payer = Keypair.fromSecretKey(
new Uint8Array(JSON.parse(process.env.PAYER))
);
const mint = new PublicKey(process.env.MINT_PUBLIC_KEY);
const withdrawWithheldAuthority = Keypair.fromSecretKey(
new Uint8Array(JSON.parse(process.env.WITHDRAW_WITHHELD_AUTHORITY))
);
const recipientKeypair = Keypair.fromSecretKey(
new Uint8Array(JSON.parse(process.env.RECIPIENT_KEYPAIR))
);
console.log('Checking payer account balance...');
const balance = await connection.getBalance(payer.publicKey);
console.log(`Payer account balance: ${balance} lamports`);
if (balance < 10000000) { // 0.01 SOL
throw new Error(
'Not enough SOL in payer account, please fund: ',
payer.publicKey.toBase58()
);
}
console.log('Fetching all token accounts...');
const allAccounts = await connection.getProgramAccounts(TOKEN_2022_PROGRAM_ID, {
commitment: 'confirmed',
filters: [
{
memcmp: {
offset: 0,
bytes: mint.toString(),
},
},
],
});
console.log(`Found ${allAccounts.length} accounts associated with the mint.`);
const accountsToWithdrawFrom = [];
for (const accountInfo of allAccounts) {
const account = unpackAccount(
accountInfo.pubkey,
accountInfo.account,
TOKEN_2022_PROGRAM_ID
);
// We then extract the transfer fee extension data from the account
const transferFeeAmount = getTransferFeeAmount(account);
if (
transferFeeAmount !== null &&
transferFeeAmount.withheldAmount > BigInt(0)
) {
accountsToWithdrawFrom.push(accountInfo.pubkey);
}
}
if (accountsToWithdrawFrom.length === 0) {
throw new Error('No accounts to withdraw from: no transfers have been made');
} else {
console.log(`Found ${accountsToWithdrawFrom.length} accounts with withheld tokens.`);
}
// Check if the recipient has an associated token account
console.log('Checking if recipient has an associated token account...');
const recipientATA = await getAssociatedTokenAddress(mint, recipientKeypair.publicKey);
try {
await connection.getAccountInfo(recipientATA);
console.log('Recipient has an associated token account.');
} catch (error) {
console.log('Recipient does not have an associated token account. Creating one...');
// Create the associated token account instruction
const createATAInstruction = createAssociatedTokenAccountInstruction(
payer.publicKey,
recipientATA,
recipientKeypair.publicKey,
mint
);
// Create and send the transaction to create the ATA
const transaction = new Transaction().add(createATAInstruction);
await sendAndConfirmTransaction(connection, transaction, [payer]);
console.log('Associated token account created successfully.');
}
// Now call withdrawWithheldTokensFromAccounts
console.log('Initiating withdrawal of withheld tokens...');
const withdrawTokensSig = await withdrawWithheldTokensFromAccounts(
connection,
payer,
mint,
recipientKeypair.publicKey,
withdrawWithheldAuthority,
[payer],
accountsToWithdrawFrom,
TOKEN_2022_PROGRAM_ID
);
console.log(
`Bag secured, check it: https://solana.fm/tx/${withdrawTokensSi ... nnet-alpha`
);
< /code>
Я получаю следующую ошибку. < /p>
`бросить новый sendtransactionerror ('не удалось отправить транзакцию:' + res.error.message, logs);
^< /p>
sendTransActionError: не удалось отправить транзакцию: Сбой моделирования транзакций: Connection.sendencodedTransaction (C: \ Development \ Transfer-Fee-Demo \ node_modules.pnpm@solana+web3.js@1.87.6_bufferutil@4.0.8_utf-8-validate@5.0.10 \ node_modules@solana \ web3.js \ lib \ index.cjs.js: 9560: 13)
журналы: [
'Программа tokenzqdbnblqp5vehdkas6epflc1phnbqcxeppxueb invoke [1]',
'журнал программы: TransferFeeInstruction: shiprawWithHeldTokensfromaccount Tokenzqdbnblqp5vehdkas6epflc1phnbqcxeppxueb потребляет 1729 из 200000 вычислительных единиц ',
' Программа Tokenzqdbnblqp5Vehdkas6epflc1phnbqcxeppxueb не удалось: indalid data для обучения '
Подробнее здесь: https://stackoverflow.com/questions/794 ... kensfromac
Получение "vingalidaccountdata" при попытке выполнить Showdrawwithheldtokensfromaccounts с использованием @solana/web3.j ⇐ Javascript
Форум по Javascript
1740510992
Anonymous
Я пытаюсь отозвать удержанные сборы за плату за перевод Solana, но получение неверной ошибки учетной записи, вот мой код: < /p>
import { Connection, Keypair, PublicKey, Transaction, sendAndConfirmTransaction } from '@solana/web3.js';
import {
TOKEN_2022_PROGRAM_ID,
getTransferFeeAmount,
unpackAccount,
withdrawWithheldTokensFromAccounts,
createAssociatedTokenAccountInstruction,
getAssociatedTokenAddress,
} from '@solana/spl-token';
import dotenv from 'dotenv';
dotenv.config();
if (!process.env.RECIPIENT_KEYPAIR) {
throw new Error('Necessary keypairs not found, have you run the create-token and mint-and-transfer scripts?');
}
const connection = new Connection(process.env.RPC_URL, 'confirmed');
const payer = Keypair.fromSecretKey(
new Uint8Array(JSON.parse(process.env.PAYER))
);
const mint = new PublicKey(process.env.MINT_PUBLIC_KEY);
const withdrawWithheldAuthority = Keypair.fromSecretKey(
new Uint8Array(JSON.parse(process.env.WITHDRAW_WITHHELD_AUTHORITY))
);
const recipientKeypair = Keypair.fromSecretKey(
new Uint8Array(JSON.parse(process.env.RECIPIENT_KEYPAIR))
);
console.log('Checking payer account balance...');
const balance = await connection.getBalance(payer.publicKey);
console.log(`Payer account balance: ${balance} lamports`);
if (balance < 10000000) { // 0.01 SOL
throw new Error(
'Not enough SOL in payer account, please fund: ',
payer.publicKey.toBase58()
);
}
console.log('Fetching all token accounts...');
const allAccounts = await connection.getProgramAccounts(TOKEN_2022_PROGRAM_ID, {
commitment: 'confirmed',
filters: [
{
memcmp: {
offset: 0,
bytes: mint.toString(),
},
},
],
});
console.log(`Found ${allAccounts.length} accounts associated with the mint.`);
const accountsToWithdrawFrom = [];
for (const accountInfo of allAccounts) {
const account = unpackAccount(
accountInfo.pubkey,
accountInfo.account,
TOKEN_2022_PROGRAM_ID
);
// We then extract the transfer fee extension data from the account
const transferFeeAmount = getTransferFeeAmount(account);
if (
transferFeeAmount !== null &&
transferFeeAmount.withheldAmount > BigInt(0)
) {
accountsToWithdrawFrom.push(accountInfo.pubkey);
}
}
if (accountsToWithdrawFrom.length === 0) {
throw new Error('No accounts to withdraw from: no transfers have been made');
} else {
console.log(`Found ${accountsToWithdrawFrom.length} accounts with withheld tokens.`);
}
// Check if the recipient has an associated token account
console.log('Checking if recipient has an associated token account...');
const recipientATA = await getAssociatedTokenAddress(mint, recipientKeypair.publicKey);
try {
await connection.getAccountInfo(recipientATA);
console.log('Recipient has an associated token account.');
} catch (error) {
console.log('Recipient does not have an associated token account. Creating one...');
// Create the associated token account instruction
const createATAInstruction = createAssociatedTokenAccountInstruction(
payer.publicKey,
recipientATA,
recipientKeypair.publicKey,
mint
);
// Create and send the transaction to create the ATA
const transaction = new Transaction().add(createATAInstruction);
await sendAndConfirmTransaction(connection, transaction, [payer]);
console.log('Associated token account created successfully.');
}
// Now call withdrawWithheldTokensFromAccounts
console.log('Initiating withdrawal of withheld tokens...');
const withdrawTokensSig = await withdrawWithheldTokensFromAccounts(
connection,
payer,
mint,
recipientKeypair.publicKey,
withdrawWithheldAuthority,
[payer],
accountsToWithdrawFrom,
TOKEN_2022_PROGRAM_ID
);
console.log(
`Bag secured, check it: https://solana.fm/tx/${withdrawTokensSig}?cluster=mainnet-alpha`
);
< /code>
Я получаю следующую ошибку. < /p>
`бросить новый sendtransactionerror ('не удалось отправить транзакцию:' + res.error.message, logs);
^< /p>
sendTransActionError: не удалось отправить транзакцию: Сбой моделирования транзакций: Connection.sendencodedTransaction (C: \ Development \ Transfer-Fee-Demo \ node_modules.pnpm@solana+web3.js@1.87.6_bufferutil@4.0.8_utf-8-validate@5.0.10 \ node_modules@solana \ web3.js \ lib \ index.cjs.js: 9560: 13)
журналы: [
'Программа tokenzqdbnblqp5vehdkas6epflc1phnbqcxeppxueb invoke [1]',
'журнал программы: TransferFeeInstruction: shiprawWithHeldTokensfromaccount Tokenzqdbnblqp5vehdkas6epflc1phnbqcxeppxueb потребляет 1729 из 200000 вычислительных единиц ',
' Программа Tokenzqdbnblqp5Vehdkas6epflc1phnbqcxeppxueb не удалось: indalid data для обучения '
Подробнее здесь: [url]https://stackoverflow.com/questions/79467653/getting-invalidaccountdata-when-trying-to-execute-withdrawwithheldtokensfromac[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия