ton

How can I wait for transaction to confirm using tonweb?


I'm writing a simple DApp on TON blockchain and using tonweb to interact with it.

I need to send some transaction and after it confirms on chain, perform some other things in JS. Example:

await ton.send('ton_sendTransaction', [{
        to: 'some address',
        value: '1000'
    }]
)

// wait for tx to confirm on chain

console.log('Done!')

But I don't understand how can I do that using tonweb


Solution

  • Simple approach would be saving last user's transaction and run a loop until user's address will have new transacations.

    You can do it like that with tonweb:

    // Get user's wallet address from TON wallet browser extension
    const address = (await ton.send('ton_requestAccounts'))[0]
    
    // Get user's last transaction hash using tonweb
    const lastTx = (await tonweb.getTransactions(address, 1))[0]
    const lastTxHash = lastTx.transaction_id.hash
    
    // Send your transaction
    await ton.send('ton_sendTransaction', [{
            to: 'some address',
            value: '1000'
        }]
    )
    
    // Run a loop until user's last tx hash changes
    var txHash = lastTxHash
    while (txHash == lastTxHash) {
        await sleep(1500) // some delay between API calls
        let tx = (await tonweb.getTransactions(address, 1))[0]
        txHash = tx.transaction_id.hash
    }
    
    console.log('Done!')