There are two parts to this question. The first is ensuring that you don't encounter the "out of gas" error.
You can try to estimate a transaction's gas fee by first calling the http-api's estimateFee endpoint. You can see how TON Center does it on their documentation site. Essentially, you want to provide details about the transaction that you will send to see how much gas the transaction could cost or if it will fail.
{
"address": "string",
"body": "string",
"init_code": "",
"init_data": "",
"ignore_chksig": true
}
The second part of this question is dedicated towards gas optimization. To optimize smart contracts on the TVM, you should understand how the compiler turns higher level languages into Fift. You can see how much each OP code costs on the documentation site. Generally speaking, the less you store, the less gas it costs.