>  기사  >  웹 프론트엔드  >  솔라나 거래 속도를 높이는 데 도움을 주세요

솔라나 거래 속도를 높이는 데 도움을 주세요

WBOY
WBOY원래의
2024-08-13 13:22:25959검색

Help make Solana Transaction faster

솔라나 거래를 더 빠르게 할 수 있도록 도와주세요
`async sendSplTransaction(wallet, {to, value, mintAddress, 소수, 수수료}) {
const receivePubKey = 새로운 PublicKey(to);
const mintPubKey = 새로운 공개키(mintAddress);
const bigValue = this.convertToBigInt(값, 소수);
const RecentBlockhash = this.provider.connection.getLatestBlockhash()를 기다립니다.
let currentBlockheight = wait this.provider.connection.getBlockHeight();
const { blockhash } = this.provider.connection.getLatestBlockhash()를 기다립니다.
const MAX_RETRIES = 3;
retryCount = 0;

    while (retryCount < MAX_RETRIES) {
        try {
            const senderATA = await getAssociatedTokenAddress(mintPubKey, this.keypair.publicKey);
            const recipientATA = await getAssociatedTokenAddress(mintPubKey, recipientPubKey);

            console.log('Sender pubkey:', this.keypair.publicKey.toString());
            console.log('Sender ATA:', senderATA.toString());
            console.log('Mint address:', mintAddress);

            let senderAccountInfo =  await this.provider.connection.getAccountInfo(senderATA);

            if (!senderAccountInfo) {
                console.log('Sender ATA not found. Attempting to create...');
                const transaction = new Transaction().add(
                    createAssociatedTokenAccountInstruction(
                        this.keypair.publicKey,
                        senderATA,
                        this.keypair.publicKey,
                        mintPubKey
                    )
                );
                await solanaWeb3.sendAndConfirmTransaction(this.provider.connection, transaction, [this.keypair]);
                console.log('Sender ATA created successfully');
            }

            const senderBalance = await this.provider.connection.getTokenAccountBalance(senderATA);
            console.log('Sender token balance:', senderBalance.value.uiAmount);

            if (senderBalance.value.uiAmount < value) {
                throw new Error(`Insufficient balance. Current balance: ${senderBalance.value.uiAmount}`);
            }

            const transaction = new Transaction({
                recentBlockhash: recentBlockhash.blockhash,
                feePayer: this.keypair.publicKey
            });
            transaction.recentBlockhash = blockhash;
            transaction.feePayer = this.keypair.publicKey;
            transaction.fee = fee;

            const recipientAccountInfo = await this.provider.connection.getAccountInfo(recipientATA);

            if (!recipientAccountInfo) {
                transaction.add(
                    createAssociatedTokenAccountInstruction(
                        this.keypair.publicKey,
                        recipientATA,
                        recipientPubKey,
                        mintPubKey
                    )
                );
            }

            transaction.add(
                createTransferInstruction(
                    senderATA,
                    recipientATA,
                    this.keypair.publicKey,
                    bigValue,
                    [],
                    TOKEN_PROGRAM_ID
                )
            );

            transaction.lastValidBlockHeight = currentBlockheight + 150;

            const txid = await solanaWeb3.sendAndConfirmTransaction(
                this.provider.connection,
                transaction,
                [this.keypair],
                {
                    commitment: "confirmed",
                    skipPreflight: true
                }
            );

            console.log('Transaction successful. Txid:', txid);
            return { success: true, data: { txid } };
        } catch (error) {
            if (error.message.includes('block height')) {
                retryCount++;
                const MAX_RETRY_DELAY = 30000;
                const delay = Math.min(2 ** retryCount * 1000, MAX_RETRY_DELAY);
                console.log(`Transaction failed, retrying in ${delay / 1000} seconds...`);
                await new Promise(resolve => setTimeout(resolve, delay));
            } else {
                return { success: false, data: null, error: error.message };
            }
        }
    }

    return { success: false, data: null, error: 'Transaction retries exhausted.' };
}`

위 내용은 솔라나 거래 속도를 높이는 데 도움을 주세요의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.