4. Transaction Building
How to build, sign and submit transactions with @amadeus-protocol/sdk 1.8.0.
Overview
Every Amadeus transaction is a single contract call with three parts: a contract ('Coin', 'LockupVault', ...), a function ('transfer', ...) and a list of arguments. The SDK turns a call into a transaction in four steps:
- Call:
{ contract, method, args }. The SDK calls this aContractCall. - Unsigned transaction:
{ signer, nonce, action }, wheresigneris your 48-byte public key andactionis{ op: 'call', contract, function, args }. The SDK serializes it with VecPak and hashes it with SHA-256. - Signature: a BLS12-381 signature over that hash.
- Packed transaction (
txPacked): the bytes you send to the node.
The quickest path is a TransactionBuilder created with your private key (the Base58-encoded 64-byte seed):
import { AmadeusSDK, TransactionBuilder } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const builder = new TransactionBuilder(privateKey) // Base58 seed
const { txHash, txPacked } = builder.transfer({
recipient: recipientAddress,
amount: 10.5, // AMA, converted to atomic units for you
symbol: 'AMA'
})
const { hash } = await sdk.transaction.submit(txPacked)
:::note Sign for the network you submit to
Each network signs transactions under its own BLS domain, so a signature made for one network is invalid on the other. A builder signs for mainnet unless you create it with a network: new TransactionBuilder(privateKey, { network: NetworkType.TESTNET }). See Signing for testnet and Networks and testnet.
:::
TransactionBuilder
Create the builder with a private key to sign every transaction with that key. The optional second argument picks the network to sign for (mainnet by default):
import { NetworkType, TransactionBuilder } from '@amadeus-protocol/sdk'
const builder = new TransactionBuilder(privateKey)
const testnetBuilder = new TransactionBuilder(privateKey, { network: NetworkType.TESTNET })
Every instance method that signs, including contract(abi) and the Lockup and NFT shortcuts, uses the builder's network. You can also create it with no key (new TransactionBuilder()). Then you pass the signer's public key to build() and the secret key to sign() on each call. Methods that sign by themselves, such as transfer(), contract() and nft*(), throw if the builder has no key.
Transfer AMA and other coins
transfer() builds and signs in one step. amount is in whole tokens (for AMA, 10.5 means 10.5 AMA). The builder converts it with toAtomicAma and decodes the Base58 recipient into the raw 48-byte key that the Coin contract expects.
To look at the transaction before you sign it, use buildTransfer() and then sign():
import { TransactionBuilder } from '@amadeus-protocol/sdk'
const builder = new TransactionBuilder(privateKey)
const unsignedTx = builder.buildTransfer({
recipient: recipientAddress,
amount: 10.5,
symbol: 'AMA'
})
console.log('Nonce:', unsignedTx.tx.nonce)
console.log('Action:', unsignedTx.tx.action)
const { txHash, txPacked } = builder.sign(unsignedTx)
The static version does the same without a builder instance. Like every static method that signs, it takes the network as an optional last argument:
import { NetworkType, TransactionBuilder } from '@amadeus-protocol/sdk'
const { txHash, txPacked } = TransactionBuilder.buildSignedTransfer({
senderPrivkey: privateKey,
recipient: recipientAddress,
amount: 10.5,
symbol: 'AMA'
})
const testnetTransfer = TransactionBuilder.buildSignedTransfer(
{ senderPrivkey: privateKey, recipient: recipientAddress, amount: 10.5, symbol: 'AMA' },
NetworkType.TESTNET
)
Calls with ABIs
For built-in contracts that ship an ABI (LOCKUP_ABI, LOCKUP_PRIME_ABI, NFT_ABI), the SDK can generate typed methods. Each function in the ABI becomes a method, and its inputs become a typed params object:
import {
LOCKUP_ABI,
LOCKUP_PRIME_ABI,
NetworkType,
TransactionBuilder,
createContract,
toAtomicAma
} from '@amadeus-protocol/sdk'
// Unsigned: each ABI function returns a ContractCall
const lockupPrime = createContract(LOCKUP_PRIME_ABI)
const call = lockupPrime.lock({ amount: toAtomicAma(100).toString(), tier: '30d' })
// { contract: 'LockupPrime', method: 'lock', args: ['100000000000', '30d'] }
// Signer-bound: each ABI function returns { txHash, txPacked }
const signedLockupPrime = createContract(LOCKUP_PRIME_ABI).connect(privateKey, NetworkType.TESTNET)
const builder = new TransactionBuilder(privateKey, { network: NetworkType.TESTNET })
const viaBuilder = builder.contract(LOCKUP_ABI).unlock({ vaultIndex: '5' })
createContract(abi)returns an object with one method per ABI function. Each method returns aContractCall.createContract(abi).connect(privateKey, network?)andbuilder.contract(abi)return methods that build and sign in one step.connectsigns fornetwork(mainnet by default), andbuilder.contractfor the builder's network.- Every param is a string, and it is passed to the contract as-is. Amounts must already be in atomic units (
toAtomicAma(100).toString()).
:::note Where these contracts run today
The node (1.6.5) accepts Lockup, LockupPrime and Nft calls on testnet only. On mainnet they are included in a block but fail with invalid_bic_action. Recent mainnet LockupPrime.lock, Nft.create_collection and Nft.mint transactions all show this receipt. So sign calls to the shipped ABIs for testnet, as shown in Contracts and NFTs. Staking uses the separate LockupVault contract; see Staking.
:::
Contracts and NFTs covers the ABIs, runtime validation, the Lockup and LockupPrime shortcuts and the NFT builders in detail.
Build a call, sign it elsewhere
A ContractCall is plain data ({ contract, method, args }), so you can build it in one place and sign it in another: a separate process, a server or a hardware-backed signer. You can also log it before signing.
import { TransactionBuilder, buildCoinTransfer } from '@amadeus-protocol/sdk'
const call = buildCoinTransfer({ recipient: recipientAddress, amount: 10.5, symbol: 'AMA' })
console.log(call.contract, call.method, call.args) // Coin transfer [ Uint8Array(48) [...], '10500000000', 'AMA' ]
const { txHash, txPacked } = TransactionBuilder.signCall(privateKey, call)
You can get a ContractCall from:
buildCoinTransfer({ recipient, amount, symbol });createContract(abi).someFunction(params)orbuildContractCall(abi, 'someFunction', params);buildNftTransfer,buildNftMintandbuildNftCreateCollection. Since 1.8.0 the mint and create-collection builders send the single map argument the node expects; see Contracts and NFTs.
To turn a ContractCall into a transaction:
| Method | Returns | Signs for |
|---|---|---|
TransactionBuilder.signCall(privateKey, call, network?) | { txHash, txPacked } | network (default mainnet) |
TransactionBuilder.buildFromCall(call, signerPk) / builder.buildFromCall(call) | unsigned transaction | nothing yet |
TransactionBuilder.buildAndSignCall(signerPk, signerSk, call, network?) | { txHash, txPacked } | network (default mainnet) |
builder.buildAndSignCall(call) | { txHash, txPacked } | the builder's network |
signContractCall(privateKey, call, network?) | { txHash, txPacked } | network (default mainnet) |
Calls with raw arguments
You can call any contract and function with build(), sign() and buildAndSign() by passing the arguments yourself. Arguments can be strings or Uint8Array. Pass addresses as raw bytes (fromBase58(address)), not as Base58 strings. Pass amounts as atomic-unit strings.
import { TransactionBuilder, fromBase58, toAtomicAma } from '@amadeus-protocol/sdk'
const builder = new TransactionBuilder(privateKey)
const { txHash, txPacked } = builder.buildAndSign('Coin', 'transfer', [
fromBase58(recipientAddress), // addresses go in as raw 48-byte keys
toAtomicAma(10.5).toString(),
'AMA'
])
The static versions take the keys explicitly. Use them to build where only the public key is known and sign later:
import {
TransactionBuilder,
deriveSkAndSeed64FromBase58Seed,
fromBase58,
getPublicKey,
toAtomicAma
} from '@amadeus-protocol/sdk'
const { seed64, sk } = deriveSkAndSeed64FromBase58Seed(privateKey)
const signerPk = getPublicKey(seed64)
const unsignedTx = TransactionBuilder.build(signerPk, 'Coin', 'transfer', [
fromBase58(recipientAddress),
toAtomicAma(10.5).toString(),
'AMA'
])
// Hand unsignedTx to whatever holds the key, then:
const { txHash, txPacked } = TransactionBuilder.sign(unsignedTx, sk)
TransactionBuilder.sign and TransactionBuilder.buildAndSign also take an optional network as their last argument.
Any method that takes a secret key accepts either the Base58 seed string or the sk from deriveSkAndSeed64FromBase58Seed. Raw Uint8Array values are used as the secret key unchanged, so never pass the 64-byte seed bytes there.
Signing for testnet
Create the builder with { network: NetworkType.TESTNET } and every transaction it signs uses the testnet domain:
import { AmadeusSDK, NetworkType, TransactionBuilder } from '@amadeus-protocol/sdk'
const testnet = new AmadeusSDK({ baseUrl: 'https://testnet-rpc.ama.one/api' })
const builder = new TransactionBuilder(privateKey, { network: NetworkType.TESTNET })
const { txHash, txPacked } = builder.transfer({ recipient: recipientAddress, amount: 1, symbol: 'AMA' })
const { hash } = await testnet.transaction.submit(txPacked)
The signing functions that TransactionBuilder uses are also exported, and they take the same optional network. signContractCall signs a ContractCall without a builder:
import { AmadeusSDK, NetworkType, buildCoinTransfer, signContractCall } from '@amadeus-protocol/sdk'
const testnet = new AmadeusSDK({ baseUrl: 'https://testnet-rpc.ama.one/api' })
const call = buildCoinTransfer({ recipient: recipientAddress, amount: 1, symbol: 'AMA' })
const { txHash, txPacked } = signContractCall(privateKey, call, NetworkType.TESTNET)
const { hash } = await testnet.transaction.submit(txPacked)
For raw arguments, use buildAndSignRaw, or buildUnsigned followed by signUnsigned:
import {
NetworkType,
buildAndSignRaw,
buildUnsigned,
deriveSkAndSeed64FromBase58Seed,
fromBase58,
getPublicKey,
signUnsigned,
toAtomicAma
} from '@amadeus-protocol/sdk'
const { seed64, sk } = deriveSkAndSeed64FromBase58Seed(privateKey)
const signerPk = getPublicKey(seed64)
const args = [fromBase58(recipientAddress), toAtomicAma(1).toString(), 'AMA']
// One step
const signed = buildAndSignRaw(signerPk, sk, 'Coin', 'transfer', args, NetworkType.TESTNET)
// Two steps
const unsignedTx = buildUnsigned(signerPk, 'Coin', 'transfer', args)
const signedLater = signUnsigned(unsignedTx, sk, NetworkType.TESTNET)
| Function | Purpose |
|---|---|
buildUnsigned(signerPk, contract, method, args) | Build an unsigned transaction |
buildUnsignedFromCall(signerPk, call) | Same, from a ContractCall |
signUnsigned(unsignedTx, signerSk, network?) | Sign an unsigned transaction |
buildAndSignRaw(signerPk, signerSk, contract, method, args, network?) | Build and sign |
signContractCall(privateKey, call, network?) | Derive keys from a Base58 seed, then build and sign |
txDstForNetwork(network?) | The BLS domain tag a network signs under |
normalizeSignerSk(signerSk) | Turn a Base58 seed into the secret key the signer uses (other values pass through) |
Leaving out network, or passing NetworkType.MAINNET or NetworkType.CUSTOM, signs with the mainnet domain. For testnet endpoints, the faucet and NetworkType, see Networks and testnet.
Transaction structure
interface UnsignedTransaction {
signer: Uint8Array // sender public key (48 bytes)
nonce: bigint
action: TransactionAction
}
interface TransactionAction {
op: 'call'
contract: string // e.g. 'Coin'
function: string // e.g. 'transfer'
args: SerializableValue[]
}
interface UnsignedTransactionWithHash {
tx: UnsignedTransaction
hash: Uint8Array // SHA-256 of the VecPak-encoded tx
}
interface BuildTransactionResult {
txHash: string // Base58 of hash
txPacked: Uint8Array // what you submit
}
To inspect a transaction before you sign it:
import { TransactionBuilder, toBase58 } from '@amadeus-protocol/sdk'
const builder = new TransactionBuilder(privateKey)
const unsignedTx = builder.buildTransfer({ recipient: recipientAddress, amount: 10.5, symbol: 'AMA' })
console.log('Signer:', toBase58(unsignedTx.tx.signer))
console.log('Nonce:', unsignedTx.tx.nonce.toString())
console.log('Contract:', unsignedTx.tx.action.contract)
console.log('Function:', unsignedTx.tx.action.function)
console.log('Args:', unsignedTx.tx.action.args)
console.log('Hash:', toBase58(unsignedTx.hash)) // same value as txHash after signing
Nonces
The SDK sets the nonce from the clock: BigInt(Date.now()) * 1_000_000n. The node accepts a transaction only if its nonce is higher than the last nonce it recorded for that signer. Otherwise it rejects it with invalid_tx_nonce. Two transactions built by the same signer in the same millisecond get the same nonce. When you send several transactions, build each one after the previous submit returns:
import { AmadeusSDK, TransactionBuilder } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const builder = new TransactionBuilder(privateKey)
for (const payment of payments) {
// Build each tx only after the previous submit returns, so nonces never collide
const { txPacked } = builder.transfer({ ...payment, symbol: 'AMA' })
const { hash } = await sdk.transaction.submit(txPacked)
console.log(payment.recipient, hash)
}
Amounts
AMA has 9 decimals: 1 AMA = 1,000,000,000 atomic units ("flat" in the node and SDK).
transfer(),buildTransfer(),buildSignedTransfer()andbuildCoinTransfer()take whole tokens and convert them for you.- ABI params (such as the
amountofLockupPrime.lock) and rawbuild()arguments must be atomic-unit strings. UsetoAtomicAma(10.5).toString(), which gives'10500000000'. ThelockupPrimeLock()shortcut is the exception: it takes AMA and converts it. - NFT amounts are whole token counts, not atomic units.
toAtomicAma rounds to the nearest atomic unit (it formats the amount with toFixed(9)), so toAtomicAma(0.1) is exactly 100000000 and float error such as 1.9999999999 becomes 2000000000. It returns a JavaScript number, though, which is exact only up to Number.MAX_SAFE_INTEGER atomic units (about 9,007,199 AMA). For larger amounts, build the atomic string yourself.
Submitting transactions
sdk.transaction.submit sends the packed transaction and returns as soon as the node accepts it into its pool:
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const { hash } = await sdk.transaction.submit(txPacked)
console.log('Accepted into the pool:', hash)
sdk.transaction.submitAndWait also waits until the transaction is in an entry and returns its receipt. A transaction can be included and still fail. Always check receipt.success:
import { AmadeusSDK } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
const { hash, metadata, receipt } = await sdk.transaction.submitAndWait(txPacked)
console.log('Entry:', metadata.entry_height, metadata.entry_hash)
if (receipt.success) {
console.log('Executed:', hash)
} else {
console.error('Included but failed:', receipt.result) // e.g. 'insufficient_funds'
}
The receipt has success, result (an error code when success is false), logs and exec_used.
To wait until the transaction is finalized instead of just included, pass { finalized: true }:
const { hash, metadata, receipt } = await sdk.transaction.submitAndWait(txPacked, { finalized: true })
The node checks for the transaction every 100 ms, up to 60 times (about 6 seconds). If it is still not included (or not finalized, with { finalized: true }), the request fails and the SDK throws. The transaction can still land later, so look it up with sdk.transaction.get(txHash) before you build a replacement.
Error handling
Neither submit nor submitAndWait returns an error field. On success, the SDK strips the node's error: 'ok' and returns only the data. Failures show up in two places:
- Rejected before execution: the SDK throws
AmadeusSDKError. Rejections from the transaction pool come back with the bare code aserror.message, such asinvalid_signature,invalid_tx_nonce,not_enough_tx_exec_balance,not_enough_txpool_balance,tx_exceeds_budgetortxpool_full. HTTP failures prefix the message withHTTP <status>:, and timeouts and network errors also throw. A testnet-signed transaction sent to mainnet, or the other way round, fails here withinvalid_signature. - Included but failed:
submitAndWaitresolves, butreceipt.successisfalseandreceipt.resultholds the contract's error code, such asinsufficient_funds,invalid_receiver_pkorinvalid_bic_action.submitalone never reports these, so usesubmitAndWaitor look the transaction up later.
import {
AmadeusSDK,
AmadeusSDKError,
getExecutionErrorMessage,
getValidationErrorMessage
} from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
try {
const { hash, receipt } = await sdk.transaction.submitAndWait(txPacked)
if (receipt.success) {
console.log('Confirmed:', hash)
} else {
// Layer 2: the node ran the call and it failed
const code = receipt.result ?? 'unknown'
console.error(code, getExecutionErrorMessage(code))
}
} catch (error) {
if (!(error instanceof AmadeusSDKError)) throw error
// Layer 1: rejected before execution (bad signature, nonce, balance, timeout...)
const code = error.message.replace(/^HTTP \d+: /, '')
console.error(code, getValidationErrorMessage(code))
}
getValidationErrorMessage, getExecutionErrorMessage and getTransactionErrorMessage map known codes to readable text. For any other code they return a generic message with the code in it.
Before you send
Check the recipient and the balance before you build a transfer. The node needs the amount plus a 0.01 AMA budget, of which a transfer uses only a fraction (see Transaction fees). Checking against AMA_TRANSFER_FEE (0.02 AMA), the reserve the extension and mobile wallet hold back, covers that budget:
import { AMA_TRANSFER_FEE, AmadeusSDK, isValidAddress } from '@amadeus-protocol/sdk'
const sdk = new AmadeusSDK({ baseUrl: 'https://mainnet-rpc.ama.one/api' })
if (!isValidAddress(recipientAddress)) {
throw new Error('Invalid recipient address')
}
const { balance } = await sdk.wallet.getBalance(senderAddress, 'AMA')
if (balance.float < amount + AMA_TRANSFER_FEE) {
throw new Error('Insufficient balance')
}
isValidAddress checks that the string is Base58 and decodes to 48 bytes.