My contributions to dhive library | How to wait for transaction status
hive-139531·@engrave·
0.000 HBDMy contributions to dhive library | How to wait for transaction status
 While working on Hive Ledger wallet I needed additional functionalities that were not available in `@hiveio/dhive` javascript library and decided that it's a good moment to improve it a bit. ## Transaction Status API A few months ago, when the Splinterlands game got traction and started onboarding masses, witnesses realized that the current implementation of the broadcast method is blocking and may cause network lags. The library was changed to use asynchronous call which helped a lot but projects that rely on a transaction status had to add additional code to handle it. I decided to add a handy method to support [Transaction Status API](https://developers.hive.io/apidefinitions/#apidefinitions-transaction-status-api). * [feat: add transaction status API](https://gitlab.syncad.com/hive/dhive/-/commit/bdb9b083dc7e9e4bd45b646226d1142fe5f8af88) ### How to wait for a transaction until it's included in a block ```javascript= const dhive = require("@hiveio/dhive"); const client = new dhive.Client("https://api.hive.blog"); const key = dhive.PrivateKey.fromString('PRIVATE KEY HERE'); const op = ["transfer", { amount: "0.001 HIVE", from: "engrave", to: "engrave.cold", memo: "" }]; (async () => { try { const {id} = await client.broadcast.sendOperations([op], key); console.log(`Transaction ID: ${id}`); let tx = null; do { tx = await client.transaction.findTransaction(id); console.log(`Transaction status: ${tx.status}`); await wait(500); } while (tx.status == 'within_mempool') if (tx.status == 'within_reversible_block') { console.log('Transaction confirmed'); } else { throw new Error(`Transaction failed with status: ${tx.status}`); } } catch (err) { console.error(err); } })(); const wait = async (ms) => { return new Promise(resolve => setTimeout(resolve, ms)); }; ``` The main point it so pool the API until we get anything but `within_mempool` and throw an error when received anything else than `within_reversible_block`. ## Account By Key API This is not a very popular API and I might be the only one using it, but it is very useful for a wallet supporting hardware wallets. The main reason is that you can only get the public key from the device, and you cannot store the information about the account, so every time you connect the hardware wallet, you need to search for associated accounts. * [feat: add "account_by_key_api"](https://gitlab.syncad.com/hive/dhive/-/commit/816bf781ab89265c22c3a2289db52a28ba0ace8e) ### How to search for an account by the **Bold**public key ```javascript= const dhive = require("@hiveio/dhive"); const client = new dhive.Client("https://api.hive.blog"); (async () => { try { const result = await client.keys.getKeyReferences(['TST65PUAPA4yC4RgPtGgsPupxT6yJtMhmT5JHFdsT3uoCbR8WJ25s']) console.log(result) // Will print [["hiveio"]] } catch (err) { console.error(err); } })(); ``` # Serializer fix I also encountered a small bug for `update_proposal` operation and fixed it. * [fix: update_proposal serializator](https://gitlab.syncad.com/hive/dhive/-/commit/10faa356ff741e9c078f2555391ec4500f4c64ef) *** **Support me with your witness vote! Click on the image below:** [](https://hivesigner.com/sign/account-witness-vote?witness=engrave&approve=1)
👍 harkar, willkomo, joeyarnoldvn, olexua, thefoundation, lukmarcus, engrave, sunshineee, heidimarie, karja, idakarlsen, the-table, silverquest, alphacore, maxer27, anech512, mborg, pkocjan, cheer-up, likwid, ewkaw, steelbak, promobot, birdwatcher, kgsupport, fjcalduch, kosimoos, rozku, themarkymark, buildawhale, upmyvote, apeminingclub, makerhacks, x30, gogreenbuddy, recoveryinc, samrisso, dlmmqb, tyrnis.curation, htotoo, bananass, penguinpablo, cryptonized, funnyman, merlion, hungrybear, onepercentbetter, jacuzzi, hallmann, reinmar, bezkresu, spacesheep, realitavshaluan, bricksolution, mintrawa, imtase, mcedric, french-tech, laruche, zonguin, aidefr, robotics101, pboulet, lpv, duke77, dragibusss, dbddv01, francosteemvotes, evildido, revueh, ykretz, dubignyp, iptrucs, appreciator, bluemist, itchyfeetdonica, samostically, outlinez, inciter, kgakakillerg, marblely, zeesh, actioncats, discoveringarni, iamyohann, whoaretheyph, noalys, makulit, aprasad2325, kimzwarch, jordand89, wargof, imcore, lartist-zen, broncnutz, minihw, manniman, traciyork, fourfourfun, yourtop3, plantstoplanks, hiq.redaktion, quekery, smooms, mary-me, ynwa.andree, kaeptn-iglo, hiq, prometheus1881, carmate, patriamcaritatis, rslsaku, damus-nostra, zeitgeisthelden, beebay.office, wochenblick, fehlerbeheber, ebike-adventure, hiq.magazine, abenteurer-dan, r0nny, uruiamme, foxyspirit, bengy, pocketrocket, enforcer48, freebornsociety, kryptik, abeerhunter, quochuy, soyalex, chinchilla, lemouth, anderssinho, sodom-lv, santigs, drsensor, softworld, bluerobo, blue-witness, arcange, investegg, achimmertens, shainemata, rohansuares, jasonbu, prolinuxua, borislavzlatanov, asgarth, mciszczon, tomiscurious, fatman, instytutfi, replicantua, v4vapid, primeradue, stoodkev, alther, mes, koxmicart, fw206, sarmaticus, sensorycznyswiat, hive-199021, sarmagames, combination, bowess, bazil7165, alpha, blocktrades.com, blocktrades, roelandp, macchiata, tomatom, bilpcoinrecords, atexoras, krrizjos18, auracraft, gabrielatravels, celinavisaez, vancouverdining, dickturpin, oluwoleolaide, grecki-bazar-ewy, pl-kuchnia, minnowvotes, alenox, steemitboard, hivebuzz, fixie, thevil, raphaelle, fengchao, helmibireuen, arabisouri, ianballantine, ahmedsy, jms211, hectorsanchez18, photographercr, lucyshalom18, smooth, urun, alfrednoyed, reenave, davidesimoncini, cnfund, btshuang, mygod, windtalker, shabuu, technocrypton, fieryfootprints, noble-noah, teamhumble, andrastia, dividendencheck, isabelpena, steemik, antor2024, drag33, ana-maria, bil.prag, katleya, lazy001, osmy91, cratic, aabcent, selfmadebastard, diecinueve, zuun.net, marucha01, russia-btc, long888, mintfinch, creacioneslelys, elevator09, breelikeatree, belialspk, lelon, irynochka, nj07, pastzam, mrsyria, marymi, nitin21, sofs-su, archangel21, kittima, doziekash, arminius3301, xdamianx, padreelferenco, ykdesign, sultanarsalan, gtg, justinw, techslut, williamtboy, wladzioo, kitzune, verbalshadow, happydolphin, tamaralovelace, gormiot, empoderat, seed-treasury, filmmaking4hive, odinnmm71, brayanmamani, kwsnomzys,