Attaching an address is just sending a 0 value tx to this address.
You can use the sendTransfer method of the JavaScript library. It handles the tip-selection (branch- and trunkTransaction) and conversion to trytes for you.
import { composeAPI } from '@iota/core'
const iota = composeAPI({
provider: 'http://localhost:14265' // replace with your IRI node.
})
// Must be truly random & 81-trytes long.
const seed = ' your seed here '
// Array of transfers which defines transfer recipients and value transferred in IOTAs.
const transfers = [{
address: ' recipient address here ',
value: 0, // 0Ki
tag: '', // optional tag of `0-27` trytes
message: '' // optional message in trytes
}]
// Depth or how far to go for tip selection entry point.
const depth = 3
// Difficulty of Proof-of-Work required to attach transaction to tangle.
// Minimum value on mainnet is `14`, `7` on spamnet and `9` on devnet and other testnets.
const minWeightMagnitude = 14
// Prepare a bundle and signs it.
iota.prepareTransfers(seed, transfers)
.then(trytes => {
// Persist trytes locally before sending to network.
// This allows for reattachments and prevents key reuse if trytes can't
// be recovered by querying the network after broadcasting.
// Does tip selection, attaches to tangle by doing PoW and broadcasts.
return iota.sendTrytes(trytes, depth, minWeightMagnitude)
})
.then(bundle => {
console.log(`Published transaction with tail hash: ${bundle[0].hash}`)
console.log(`Bundle: ${bundle}`)
})
.catch(err => {
// handle errors here
})
From the docs