Skip to content

Instantly share code, notes, and snippets.

@larry0x
Last active June 27, 2023 06:54
Show Gist options
  • Save larry0x/37e92420c64d6ecced91227c6c4da0aa to your computer and use it in GitHub Desktop.
Save larry0x/37e92420c64d6ecced91227c6c4da0aa to your computer and use it in GitHub Desktop.
#!/bin/bash
# Some helper functions for working with cosmos-sdk txs from the command line or
# in bash scripts.
#
# Example: say, if you want to send coins to multiple recipients. We need to:
#
# - compose a tx containing multiple "send" messages
# - set an appropriate gas limit and fee amount
# - sign it
# - broadcast it
# - wait until the tx is confirmed onchain.
#
# To do these, use the following commands:
#
# ```bash
# source txutils.sh
# resetTx
# appendMsg $(osmosisd tx bank send [account] cosmos1... 12345uosmo --from [account] --generate-only)
# appendMsg $(osmosisd tx bank send [account] cosmos1... 23456uosmo --from [account] --generate-only)
# setGas 1000000 0.0025uosmo
# signAndBroadcast osmosisd osmosis-1 [account] [password]
# ```
resetTx() {
if [ -f "./tx.json" ]; then
rm ./tx.json
fi
}
appendMsg() {
tx=$1
msgs=$(echo $tx | jq ".body.messages")
if [ -f "./tx.json" ]; then
jq ".body.messages += $msgs" tx.json | sponge tx.json
else
echo "$tx" > tx.json
fi
}
setGas() {
gas=$1
gasPrice=$2 # price without the denom
gasDenom=$3
jq ".auth_info.fee.gas_limit = \"$gas\"" tx.json | sponge tx.json
amountDec=$(echo "$gas * $gasPrice" | bc)
amount=${amountDec%.*}
if (( $amount > 0 )); then
jq ".auth_info.fee.amount = [{\"denom\":\"$gasDenom\",\"amount\":\"$amount\"}]" tx.json | sponge tx.json
else
jq '.auth_info.fee.amount = []' tx.json | sponge tx.json
fi
}
signAndBroadcast() {
bin=$1
chainId=$2
accName=$3
pass=$4
echo "🤖 Signing tx..."
echo $pass | $bin tx sign tx.json --chain-id $chainId --from $accName --output-document tx.json -y
echo "🤖 Broadcasting tx..."
txhash=$($bin tx broadcast tx.json --output json | jq -r '.txhash')
echo "txhash: $txhash"
echo "🤖 Tx broadcasted, waiting for confirmation..."
while true; do
txRes=$($bin q tx $txhash --output json 2> /dev/null) && returncode=0 || returncode=$?
if [[ $returncode -ne 0 ]]; then
echo "⏳ Tx not confirmed on chain yet, waiting..."
sleep 1
continue
fi
code=$(echo $txRes | jq -r '.code')
if [[ $code -ne 0 ]]; then
errMsg=$(echo $txRes | jq -r '.raw_log')
echo "❌ Tx failed: $errMsg"
exit 1
fi
echo "✅ Tx success!"
break
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment