Skip to content

Commit

Permalink
fix errors in rebalancing task
Browse files Browse the repository at this point in the history
  • Loading branch information
khirvy019 committed Feb 19, 2025
1 parent 00990b4 commit e9b4596
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 17 deletions.
13 changes: 10 additions & 3 deletions stablehedge/functions/auth_key.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,30 @@

from stablehedge.apps import LOGGER
from stablehedge.exceptions import StablehedgeException
from stablehedge.js.runner import ScriptFunctions
from stablehedge.utils.wallet import wif_to_cash_address, subscribe_address
from stablehedge.utils.transaction import tx_model_to_cashscript

from main import models as main_models


def get_auth_key_wallet_wif():
return settings.STABLEHEDGE["AUTH_KEY_WALLET_WIF"]

def subscribe_auth_key():
address = get_auth_key_address()
LOGGER.info(f"Subscribing address holding auth keys: {address}")
return subscribe_address(address)

def get_auth_key_address():
wif = settings.STABLEHEDGE["AUTH_KEY_WALLET_WIF"]
wif = get_auth_key_wallet_wif()
return wif_to_cash_address(wif)

def get_auth_key_utxo(token_category:str):
address = get_auth_key_address()

utxo = main_models.Transaction.objects.filter(
address__address=obj.address,
address__address=address,
cashtoken_nft__category=token_category,
cashtoken_nft__capability=main_models.CashNonFungibleToken.Capability.NONE,
spent=False,
Expand All @@ -38,11 +43,13 @@ def get_signed_auth_key_utxo(token_category:str, locktime:int=0):
)

ct_utxo = tx_model_to_cashscript(utxo)
ct_utxo["wif"] = get_auth_key_wallet_wif()

sign_result = ScriptFunctions.signAuthKeyUtxo(dict(locktime=locktime, authKeyUtxo=ct_utxo ))
sign_result = ScriptFunctions.signAuthKeyUtxo(dict(locktime=locktime, authKeyUtxo=ct_utxo))
if not sign_result["success"]:
raise StablehedgeException(sign_result.get("error", "Failed to sign auth key utxo"))

ct_utxo.pop("wif", None)
ct_utxo["lockingBytecode"] = sign_result["lockingBytecode"]
ct_utxo["unlockingBytecode"] = sign_result["unlockingBytecode"]

Expand Down
3 changes: 2 additions & 1 deletion stablehedge/functions/market.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

from .auth_key import get_signed_auth_key_utxo
from .redemption_contract import find_fiat_token_utxos
from .treasury_contract import get_bch_utxos

def transfer_treasury_funds_to_redemption_contract(
treasury_contract_address,
Expand All @@ -25,7 +26,7 @@ def transfer_treasury_funds_to_redemption_contract(
if redemption_contract.auth_token_id != treasury_contract.auth_token_id:
raise StablehedgeException("Mismatch in auth token", code="mismatch-auth-token")

reserve_utxo = find_fiat_token_utxos(redemption_contract.address).first()
reserve_utxo = find_fiat_token_utxos(redemption_contract).first()

treasury_contract_utxos = get_bch_utxos(treasury_contract_address, satoshis=satoshis)

Expand Down
2 changes: 1 addition & 1 deletion stablehedge/functions/redemption_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

def find_fiat_token_utxos(redemptionContractOrAddress, min_token_amount=None, min_satoshis=None):
if isinstance(redemptionContractOrAddress, str):
obj = models.RedemptionContract(redemptionContractOrAddress)
obj = models.RedemptionContract.objects.get(address=redemptionContractOrAddress)
else:
obj = redemptionContractOrAddress

Expand Down
13 changes: 7 additions & 6 deletions stablehedge/js/src/funcs/rebalancing.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { TransactionBuilder } from 'cashscript'
import { P2PKH_INPUT_SIZE } from 'cashscript/dist/constants.js'
import { getOutputSize } from 'cashscript/dist/utils.js'
import { RedemptionContract } from '../contracts/redemption-contract/index.js'
import { TreasuryContract } from '../contracts/treasury-contract/index.js'
import { parseUtxo, serializeOutput, serializeUtxo } from '../utils/crypto.js'
import { addPrecision, calculateInputSize, removePrecision } from '../utils/transaction.js'
import { getOutputSize } from 'cashscript/dist/utils.js'

/**
* @param {Object} opts
Expand Down Expand Up @@ -43,11 +44,11 @@ export async function transferTreasuryFundsToRedemptionContract(opts) {

transaction.addInput(reserveUtxo, rcUnlocker)
__totalInput += addPrecision(reserveUtxo.satoshis)
__txFee += addPrecision(tcInputSize)
__txFee += addPrecision(rcInputSize)

transaction.addInput(authKeyUtxo, rcUnlocker)
transaction.addInput(authKeyUtxo, authKeyUtxo.template.unlockP2PKH())
__totalInput += addPrecision(authKeyUtxo.satoshis)
__txFee += addPrecision(rcInputSize)
__txFee += addPrecision(P2PKH_INPUT_SIZE)

transaction.addInputs(treasuryContractUtxos, tcUnlocker)
__totalInput += treasuryContractUtxos
Expand All @@ -65,13 +66,13 @@ export async function transferTreasuryFundsToRedemptionContract(opts) {
changeOutput = false
}

const reserveOutput = { to: rc.address, amount: outputSats, token: reserveUtxo.token }
const reserveOutput = { to: rc.tokenAddress, amount: outputSats, token: reserveUtxo.token }
transaction.addOutput(reserveOutput)
__totalOutput += addPrecision(outputSats)
__txFee += addPrecision(getOutputSize(reserveOutput))

const authKeyOutput = {
to: authKeyUtxo.template.unlockP2PKH().getLockingBytecode(),
to: authKeyUtxo.template.unlockP2PKH().generateLockingBytecode(),
amount: authKeyUtxo.satoshis,
token: authKeyUtxo.token,
}
Expand Down
10 changes: 5 additions & 5 deletions stablehedge/js/src/funcs/transaction.js
Original file line number Diff line number Diff line change
Expand Up @@ -152,18 +152,18 @@ export function signAuthKeyUtxo(opts) {
locktime: locktime,
inputs: [{
outpointIndex: authKeyUtxo?.vout,
outpointTransactionHash: hexToBin(opts?.utxo?.txid),
outpointTransactionHash: hexToBin(authKeyUtxo?.txid),
sequenceNumber: 0xfffffffe,
unlockingBytecode: new Uint8Array(),
}],
outputs: [{
lockingBytecode: utxoLockingBytecode,
valueSatoshis: authKeyUtxo.satoshis,
token: {
category: authKeyUtxo.token.category,
category: hexToBin(authKeyUtxo.token.category),
amount: authKeyUtxo.token.amount,
nft: {
commitment: authKeyUtxo.token.nft.commitment,
commitment: hexToBin(authKeyUtxo.token.nft.commitment),
capability: authKeyUtxo.token.nft.capability,
}
}
Expand All @@ -175,10 +175,10 @@ export function signAuthKeyUtxo(opts) {
lockingBytecode: utxoLockingBytecode,
valueSatoshis: authKeyUtxo.satoshis,
token: {
category: authKeyUtxo.token.category,
category: hexToBin(authKeyUtxo.token.category),
amount: authKeyUtxo.token.amount,
nft: {
commitment: authKeyUtxo.token.nft.commitment,
commitment: hexToBin(authKeyUtxo.token.nft.commitment),
capability: authKeyUtxo.token.nft.capability,
}
}
Expand Down
3 changes: 2 additions & 1 deletion stablehedge/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
get_spendable_sats,
get_wif_for_short_proposal
)
from stablehedge.functions.market import transfer_treasury_funds_to_redemption_contract
from stablehedge.utils.blockchain import broadcast_transaction
from stablehedge.utils.wallet import wif_to_pubkey

Expand Down Expand Up @@ -205,7 +206,7 @@ def rebalance_funds(treasury_contract_address:str):

satoshis_to_transfer = None
if transferrable > required_sats:
satoshis_to_transfer = required_sats
satoshis_to_transfer = int(required_sats)

result = transfer_treasury_funds_to_redemption_contract(
treasury_contract_address, satoshis=satoshis_to_transfer
Expand Down

0 comments on commit e9b4596

Please sign in to comment.