API Reference
Models
- class term_structure.models.async_exchange_client.AsyncExchangeClient(host: str | None = None)
The underlying agent to asynchronously interact with TermStructure. It is strongly coupled with TermStructure’s web interface.
- Parameters:
host – If specified, all traffics will be routed to the given URL. A common scenario is to target to testnet.
- async get_v1_account_info(api_key: str) dict
Get account information by specific L1 address or account ID.
- Parameters:
api_key – The registered api key on Term Structure.
- async get_v1_asset_info(api_key: str) dict
Get asset information of specific account.
- Parameters:
api_key – The registered api key on Term Structure.
- async get_v1_base_token_prices(token_ids: list[str]) dict
Get base token prices information.
- Parameters:
token_ids – A list of token ids to query.
- async get_v1_deposit_history(api_key: str, start_time: str | None = None, end_time: str | None = None, limit: str | None = None) dict
Get deposit history of specific account.
- Parameters:
api_key – The registered api key on Term Structure.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_v1_loan_history(api_key: str, start_time: str | None = None, end_time: str | None = None, limit: str | None = None) dict
Get loan history of specific account.
- Parameters:
api_key – The registered api key on Term Structure.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_v1_loan_info(api_key: str) dict
Get loan information of specific account.
- Parameters:
api_key – The registered api key on Term Structure.
- async get_v1_opened_orders(api_key: str, market: Literal['PRIMARY', 'SECONDARY', 'REPO'] = 'PRIMARY', start_time: str | None = None, end_time: str | None = None, limit: str | None = None) dict
Get open orders of specific account.
- Parameters:
api_key – The registered api key on Term Structure.
account_id – The identifier on Term Structure.
market – The market to query.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_v1_orders_history(api_key: str, market: Literal['PRIMARY', 'SECONDARY', 'REPO'] = 'PRIMARY', start_time: str | None = None, end_time: str | None = None, limit: str | None = None) dict
Get order history of specific account.
- Parameters:
api_key – The registered api key on Term Structure.
market – The market to query.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_v1_primary_candlesticks(main_token_id: str, start_time: int | None = None, end_time: int | None = None, limit: int | None = None) dict
Get candlesticks of specific main token in primary market.
- Parameters:
main_token_id – The bond token id.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_v1_primary_ticker(main_token_id: str) dict
Get market ticker information of specific bond token in primary market.
- Parameters:
main_token_id – The bond token id.
- async get_v1_redeem_history(api_key: str, layer: Literal['L1', 'L2'] = 'L1', start_time: str | None = None, end_time: str | None = None, limit: str | None = None) dict
Get redeem history of specific account.
- Parameters:
api_key – The registered api key on Term Structure.
layer – At which layer of redeems to query.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_v1_repay_history(api_key: str, start_time: str | None = None, end_time: str | None = None, limit: str | None = None) dict
Get repay history of specific account.
- Parameters:
api_key – The registered api key on Term Structure.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_v1_secondary_candlesticks(main_token_id: str, start_time: int | None = None, end_time: int | None = None, limit: int | None = None) dict
Get candlesticks of specific main token in secondary market.
- Parameters:
main_token_id – The bond token id.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_v1_secondary_orderbook(main_token_id: str) dict
Get orderbook data information in secondary market.
- Parameters:
main_token_id – The bond token id.
- async get_v1_secondary_ticker(main_token_id: str) dict
Get market ticker of specific main token in secondary market.
- Parameters:
main_token_id – The bond token id.
- async get_v1_secondary_trades(main_token_id: str, limit: str | None = None) dict
Get trades information in secondary market.
- Parameters:
main_token_id – The bond token id.
limit – Max query amount.
- async get_v1_withdraw_history(api_key: str, start_time: str | None = None, end_time: str | None = None, limit: str | None = None) dict
Get withdraw history of specific account.
- Parameters:
api_key – The registered api key on Term Structure.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async post_v1_primary_cancel_order(api_key: str, eddsa_sig: dict, ecdsa_sig: str, message: list[str], account_id: str, order_hash: str, fee_token_name: str, fee_amount: str) dict
Cancel order in primary market.
- Parameters:
api_key – The registered api key on Term Structure.
eddsa_sig – The EdDSA signature.
ecdsa_sig – The ECDSA signature.
message – The prepared payload to sign.
account_id – The identifier on Term Structure.
order_hash – The order identifier.
fee_token_name – The name of desired token to charge fee.
fee_amount – The charged fee amount.
- async post_v1_primary_place_borrow_order(api_key: str, eddsa_sig: dict, ecdsa_sig: str, message: list[str], account_id: str, base_token_name: str, base_token_amount: str, collateral_token_name: str, collateral_amount: str, idempotent_key: str, borrow_fee_rate: str, fee_token_name: str, fee_amount: str, maturity_time: str, expired_time: str, interest_rate: str, epoch: str, borrow_min_fee_amt: str, client_order_id: str | None = None) dict
Place borrow order in primary market.
- Parameters:
api_key – The registered api key on Term Structure.
eddsa_sig – The EdDSA signature.
ecdsa_sig – The ECDSA signature.
message – The prepared payload to sign.
account_id – The identifier on Term Structure.
base_token_name – The name of token desired to borrow.
base_token_amount – The desired amount to borrow.
collateral_token_name – The collateral token name.
collateral_amount – An over collateralized amount.
idempotent_key – An unique digit-string to prevent duplication.
borrow_fee_rate – A fee rate referenced from exchange config.
fee_token_name – The name of desired token to charge fee.
fee_amount – The charged fee amount.
maturity_time – The corresponding maturity time for the involved bond token.
expired_time – The desired expiration time.
interest_rate – The desired interest rate.
epoch – An increasing digit-string referenced from exchange config.
borrow_min_fee_amt – The amount of base token to be charged as the min fee.
client_order_id – A field to keep customized identifier for the order.
- async post_v1_primary_place_lend_order(api_key: str, eddsa_sig: dict, ecdsa_sig: str, message: list[str], account_id: str, base_token_name: str, base_token_amount: str, idempotent_key: str, lend_fee_rate: str, fee_token_name: str, fee_amount: str, maturity_time: str, expired_time: str, interest_rate: str, epoch: str, default_matched_interest_rate: str, lend_min_fee_amt: str, client_order_id: str | None = None) dict
Place lend order in primary market.
- Parameters:
api_key – The registered api key on Term Structure.
eddsa_sig – The EdDSA signature.
ecdsa_sig – The ECDSA signature.
message – The prepared payload to sign.
account_id – The identifier on Term Structure.
base_token_name – The name of token desired to lend.
base_token_amount – The desired amount to lend.
idempotent_key – An unique digit-string to prevent duplication.
lend_fee_rate – A fee rate referenced from exchange config.
fee_token_name – The name of desired token to charge fee.
fee_amount – The charged fee amount.
maturity_time – The corresponding maturity time for the involved bond token.
expired_time – The desired expiration time.
interest_rate – The desired interest rate.
epoch – An increasing digit-string referenced from exchange config.
default_matched_interest_rate – A fee rate referenced from exchange config.
lend_min_fee_amt – The amount of base token to be charged as the min fee.
client_order_id – A field to keep customized identifier for the order.
- async post_v1_primary_redeem(api_key: str, eddsa_sig: dict, ecdsa_sig: str, message: list[str], account_id: str, main_token_name: str, main_token_amount: str, nonce: str, fee_token_name: str, fee_amount: str) dict
Redeem base token with main token.
- Parameters:
api_key – The registered api key on Term Structure.
eddsa_sig – The EdDSA signature.
ecdsa_sig – The ECDSA signature.
message – The prepared payload to sign.
account_id – The identifier on Term Structure.
main_token_name – The bond token name.
main_token_amount – The desired amount to redeem.
nonce – A monotonically increasing number.
fee_token_name – The name of desired token to charge fee.
fee_amount – The charged fee amount.
- async post_v1_secondary_cancel_order(api_key: str, eddsa_sig: dict, ecdsa_sig: str, message: list[str], account_id: str, order_hash: str, fee_token_name: str, fee_amount: str) dict
Cancel order in secondary market.
- Parameters:
api_key – The registered api key on Term Structure.
eddsa_sig – The EdDSA signature.
ecdsa_sig – The ECDSA signature.
message – The prepared payload to sign.
account_id – The identifier on Term Structure.
order_hash – The order identifier.
fee_token_name – The name of desired token to charge fee.
fee_amount – The charged fee amount.
- async post_v1_secondary_place_order(api_key: str, eddsa_sig: dict, ecdsa_sig: str, message: list[str], type: Literal['LIMIT', 'MARKET'], side: Literal['SELL', 'BUY'], account_id: str, main_token_amount: str, idempotent_key: str, expired_time: str, epoch: str, taker_fee: str, maker_fee: str, taker_min_fee_amt: str, maker_min_fee_amt: str, client_order_id: str | None = None) dict
Place order in secondary market.
- Parameters:
api_key – The registered api key on Term Structure.
eddsa_sig – The EdDSA signature.
ecdsa_sig – The ECDSA signature.
message – The prepared payload to sign.
type – The desired type.
side – The desired side.
account_id – The identifier on Term Structure.
main_token_amount – The desired amount to order.
idempotent_key – An unique digit-string to prevent duplication.
expired_time – The desired expiration time.
epoch – An increasing digit-string referenced from exchange config.
taker_fee – A fee rate referenced from exchange config.
maker_fee – A fee rate referenced from exchange config.
taker_min_fee_amt – The amount of base token to be charged as taker side min fee.
maker_min_fee_amt – The amount of base token to be charged as maker side min fee.
client_order_id – A field to keep customized identifier for the order.
- async post_v1_trader_api_key(message: str, l1_address: str, signature: str) dict
Get API key information of specific account.
- Parameters:
message – A template string referenced from echange config.
l1_address – A layer one wallet address.
signature – The signature of message signed by the private key of l1_address.
- class term_structure.models.async_exchange_broker.AsyncExchangeBroker(host: str | None = None)
The higher-level agent to interact with TermStructure L2, focusing on business-level concerns.
- Parameters:
host – If specified, all traffics will be routed to the given URL. A common scenario is to target to testnet.
- async aclose()
- async cancel_primary_order_by_identity(identity: Identity, order_hash: str, fee_token_name: str) dict
Cancel an open order from primary market.
- Parameters:
identity – A connected identity.
order_hash – The order identifier.
fee_token_name – The name of desired token to charge fee.
- async cancel_secondary_order_by_identity(identity: Identity, order_hash: str, fee_token_name: str) dict
Cancel an open order from secondary market.
- Parameters:
identity – A connected identity.
order_hash – The order identifier.
fee_token_name – The name of desired token to charge fee.
- async connect(layer_1_wallet_address: str, layer_1_wallet_private_key: str, layer_2_api_key: str | None = None) Identity
Establish an identity to provide private accessibilities to a specific L1/L2 identity.
- Parameters:
layer_1_wallet_address – The L1 wallet address of the identity.
layer_1_wallet_private_key – The corresponding private key for layer_1_wallet_address
layer_2_api_key – The registered api key on Term Structure. If not specified, it will be evaluated automatically.
- Returns:
The established Identity.
- property exchange_config: ExchangeConfig
Retrieve static configurations of Term Structure exchange.
- property exchange_info: ExchangeInfo
Retrieve runtime configurations of Term Structure exchange.
- async get_account_by_identity(identity: Identity) dict
Retrieve account information of specific identity.
- Parameters:
identity – A connected identity.
- async get_assets_by_identity(identity: Identity) list
Retrieve asset information of specific identity.
- Parameters:
identity – A connected identity.
- async get_base_token_prices(base_token_names: list[str]) list[Decimal]
Get base token prices information.
- Parameters:
base_token_names – A list of base token names to query.
- async get_deposit_history_by_identity(identity: Identity, start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve deposit history of specific identity.
- Parameters:
identity – A connected identity.
- async get_loan_history_by_identity(identity: Identity) list
Retrieve loan history of specific identity.
- Parameters:
identity – A connected identity.
- async get_loans_by_identity(identity: Identity) list
Retrieve loans of specific identity.
- Parameters:
identity – A connected identity.
- async get_opened_orders_by_identity(identity: Identity, market: Literal['PRIMARY', 'SECONDARY', 'REPO'] = 'PRIMARY', start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve open orders of specific identity.
- Parameters:
identity – A connected identity.
market – The market where orders belong to
- async get_orders_history_by_identity(identity: Identity, market: Literal['PRIMARY', 'SECONDARY', 'REPO'] = 'PRIMARY', start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve order history of specific identity.
- Parameters:
identity – A connected identity.
market – The market where orders belong to
- async get_primary_candlesticks(main_token_name: str, start_time: int | None = None, end_time: int | None = None, limit: int | None = None) dict
Get candlesticks of specific main token in primary market.
- Parameters:
main_token_name – The bond token name.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_primary_ticker(main_token_name: str) dict
Get market ticker information of specific bond token in primary market.
- Parameters:
main_token_name – The bond token name.
- async get_redeem_history_by_identity(identity: Identity, layer: Literal['L1', 'L2']) list
Retrieve redeem history of specific identity.
- Parameters:
identity – A connected identity.
layer – The history of which layer in query.
- async get_repay_history_by_identity(identity: Identity) list
Retrieve repay history of specific identity.
- Parameters:
identity – A connected Identity.
- async get_secondary_candlesticks(main_token_name: str, start_time: int | None = None, end_time: int | None = None, limit: int | None = None) dict
Get candlesticks of specific main token in secondary market.
- Parameters:
main_token_name – The bond token name.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_secondary_orderbook(main_token_name: str) dict
Get orderbook data information in secondary market.
- Parameters:
main_token_name – The bond token name.
- async get_secondary_ticker(main_token_name: str) dict
Get market ticker of specific main token in secondary market.
- Parameters:
main_token_name – The bond token name.
- async get_secondary_trades(main_token_name: str, limit: str | None = None) dict
Get trades information in secondary market.
- Parameters:
main_token_name – The bond token name.
limit – Max query amount.
- async get_withdraw_history_by_identity(identity: Identity, start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve withdraw history of specific identity.
- Parameters:
identity – A connected identity.
- async place_primary_borrow_order_by_identity(identity: Identity, main_token_name: str, collateral_token_name: str, borrow_amount: Decimal, interest_rate: Decimal, collateral_amount: Decimal | None = None, min_fee_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place borrow order on specific primary market.
- Parameters:
identity – A connected identity.
main_token_name – The bond token name.
collateral_token_name – The collateral token name.
borrow_amount – The desired amount to borrow.
interest_rate – The desired interest rate to borrow.
collateral_amount – If specified, an over collateralized amount could be provided.
min_fee_base_token_amount – The minimum fee amount to be charged in base token.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 6 days. The time would be floored according to time to maturity.
client_order_id – A field to keep customized identifier for the order.
- async place_primary_lend_order_by_identity(identity: Identity, main_token_name: str, lend_amount: Decimal, interest_rate: Decimal, min_fee_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place lend order on specific primary market.
- Parameters:
identity – A connected identity.
main_token_name – The bond token name.
lend_amount – The desired amount to lend.
interest_rate – The desired interest rate to lend.
min_fee_base_token_amount – The minimum fee amount to be charged in base token.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 6 days. The time would be upper-bounded to one-day before maturity time.
client_order_id – A field to keep customized identifier for the order.
- async place_secondary_limit_order_by_identity(identity: Identity, order_side: Literal['SELL', 'BUY'], main_token_name: str, main_token_amount: Decimal, base_token_name: str, interest_rate: Decimal | None = None, base_token_amount: Decimal | None = None, min_taker_fee_base_token_amount: Decimal | None = None, min_maker_fee_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place limit order on specific secondary market.
- Parameters:
identity – A connected identity.
order_side – The desired side.
main_token_name – The bond token name.
main_token_amount – The desired amount to sell or buy.
base_token_name – The name of token desired to quote.
interest_rate – The desired interest rate to quote. This argument is mutully exclusive with base_token_amount.
base_token_amount – The desired quote amount. This argument is mutully exclusive with interest_rate.
min_taker_fee_base_token_amount – The minimum taker side fee amount to be charged in base token.
min_maker_fee_base_token_amount – The minimum maker side fee amount to be charged in base token.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 7 days. The time would be upper-bounded to maturity time.
client_order_id – A field to keep customized identifier for the order.
- async place_secondary_market_order_by_identity(identity: Identity, order_side: Literal['SELL', 'BUY'], main_token_name: str, main_token_amount: Decimal, base_token_name: str, min_taker_fee_base_token_amount: Decimal | None = None, stop_loss_interest_rate: Decimal | None = None, stop_loss_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place limit order on specific secondary market.
- Parameters:
identity – A connected identity.
order_side – The desired side.
main_token_name – The bond token name.
main_token_amount – The desired amount to sell or buy.
base_token_name – The name of token desired to quote.
min_taker_fee_base_token_amount – The minimum taker side fee amount to be charged in base token.
stop_loss_interest_rate – The desired interest rate to stop loss. This argument is mutully exclusive with stop_loss_base_token_amount.
stop_loss_base_token_amount – The desired quote amount to stop loss. This argument is mutully exclusive with stop_loss_interest_rate.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 7 days. The time would be upper-bounded to maturity time.
client_order_id – A field to keep customized identifier for the order.
- async redeem_by_identity(identity: Identity, main_token_name: str, main_token_amount: Decimal) dict
Redeem a matured loan for specific identity.
- Parameters:
identity – A connected identity.
main_token_name – The bond token name.
main_token_amount – The desired amount to redeem.
- async sync_exchange_config()
Update exchange_config to latest.
- async sync_exchange_info()
Update exchange_info to latest.
- class term_structure.models.async_single_wallet_exchange_broker.AsyncSingleWalletExchangeBroker(layer_1_wallet_address: str, layer_1_wallet_private_key: str, layer_2_api_key: str | None = None, host: str | None = None)
- async cancel_primary_order(order_hash: str, fee_token_name: str) dict
Cancel an open order from primary market.
- Parameters:
order_hash – The order identifier.
fee_token_name – The name of desired token to charge fee.
- async cancel_secondary_order(order_hash: str, fee_token_name: str) dict
Cancel an open order from secondary market.
- Parameters:
order_hash – The order identifier.
fee_token_name – The name of desired token to charge fee.
- property exchange_config: ExchangeConfig
Retrieve static configurations of Term Structure exchange.
- property exchange_info: ExchangeInfo
Retrieve runtime configurations of Term Structure exchange.
- async get_base_token_prices(base_token_names: list[str]) list[Decimal]
Get base token prices information.
- Parameters:
base_token_names – A list of base token names to query.
- async get_deposit_history(start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve deposit history of specific identity.
- async get_opened_orders(market: Literal['PRIMARY', 'SECONDARY', 'REPO'] = 'PRIMARY', start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve open orders of specific identity.
- Parameters:
market – The market where orders belong to
- async get_orders_history(market: Literal['PRIMARY', 'SECONDARY', 'REPO'] = 'PRIMARY', start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve order history of specific identity.
- Parameters:
market – The market where orders belong to
- async get_primary_candlesticks(main_token_name: str, start_time: int | None = None, end_time: int | None = None, limit: int | None = None) dict
Get candlesticks of specific main token in primary market.
- Parameters:
main_token_name – The bond token name.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_primary_ticker(main_token_name: str) dict
Get market ticker information of specific bond token in primary market.
- Parameters:
main_token_name – The bond token name.
- async get_redeem_history(layer: Literal['L1', 'L2']) list
Retrieve redeem history of specific identity.
- Parameters:
layer – The history of which layer in query.
- async get_secondary_candlesticks(main_token_name: str, start_time: int | None = None, end_time: int | None = None, limit: int | None = None) dict
Get candlesticks of specific main token in secondary market.
- Parameters:
main_token_name – The bond token name.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_secondary_orderbook(main_token_name: str) dict
Get orderbook data information in secondary market.
- Parameters:
main_token_name – The bond token name.
- async get_secondary_ticker(main_token_name: str) dict
Get market ticker of specific main token in secondary market.
- Parameters:
main_token_name – The bond token name.
- async get_secondary_trades(main_token_name: str, limit: str | None = None) dict
Get trades information in secondary market.
- Parameters:
main_token_name – The bond token name.
limit – Max query amount.
- async get_withdraw_history(start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve withdraw history of specific identity.
- async place_primary_borrow_order(main_token_name: str, collateral_token_name: str, borrow_amount: Decimal, interest_rate: Decimal, collateral_amount: Decimal | None = None, min_fee_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place borrow order on specific primary market.
- Parameters:
main_token_name – The bond token name.
collateral_token_name – The collateral token name.
borrow_amount – The desired amount to borrow.
interest_rate – The desired interest rate to borrow.
collateral_amount – If specified, an over collateralized amount could be provided.
min_fee_base_token_amount – The minimum fee amount to be charged in base token.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 6 days. The time would be floored according to time to maturity.
client_order_id – A field to keep customized identifier for the order.
- async place_primary_lend_order(main_token_name: str, lend_amount: Decimal, interest_rate: Decimal, min_fee_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place lend order on specific primary market.
- Parameters:
main_token_name – The bond token name.
lend_amount – The desired amount to lend.
interest_rate – The desired interest rate to lend.
min_fee_base_token_amount – The minimum fee amount to be charged in base token.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 6 days. The time would be upper-bounded to one-day before maturity time.
client_order_id – A field to keep customized identifier for the order.
- async place_secondary_limit_order(order_side: Literal['SELL', 'BUY'], main_token_name: str, main_token_amount: Decimal, base_token_name: str, interest_rate: Decimal | None = None, base_token_amount: Decimal | None = None, min_taker_fee_base_token_amount: Decimal | None = None, min_maker_fee_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place limit order on specific secondary market.
- Parameters:
order_side – The desired side.
main_token_name – The bond token name.
main_token_amount – The desired amount to sell or buy.
base_token_name – The name of token desired to quote.
interest_rate – The desired interest rate to quote. This argument is mutully exclusive with base_token_amount.
base_token_amount – The desired quote amount. This argument is mutully exclusive with interest_rate.
min_taker_fee_base_token_amount – The minimum taker side fee amount to be charged in base token.
min_maker_fee_base_token_amount – The minimum maker side fee amount to be charged in base token.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 7 days. The time would be upper-bounded to maturity time.
client_order_id – A field to keep customized identifier for the order.
- async place_secondary_market_order(order_side: Literal['SELL', 'BUY'], main_token_name: str, main_token_amount: Decimal, base_token_name: str, min_taker_fee_base_token_amount: Decimal | None = None, stop_loss_interest_rate: Decimal | None = None, stop_loss_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place limit order on specific secondary market.
- Parameters:
order_side – The desired side.
main_token_name – The bond token name.
main_token_amount – The desired amount to sell or buy.
base_token_name – The name of token desired to quote.
min_taker_fee_base_token_amount – The minimum taker side fee amount to be charged in base token.
stop_loss_interest_rate – The desired interest rate to stop loss. This argument is mutully exclusive with stop_loss_base_token_amount.
stop_loss_base_token_amount – The desired quote amount to stop loss. This argument is mutully exclusive with stop_loss_interest_rate.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 7 days. The time would be upper-bounded to maturity time.
client_order_id – A field to keep customized identifier for the order.
- async redeem(main_token_name: str, main_token_amount: Decimal) dict
Redeem a matured loan for specific identity.
- Parameters:
main_token_name – The bond token name.
main_token_amount – The desired amount to redeem.
- async sync_exchange_config()
Update exchange_config to latest.
- async sync_exchange_info()
Update exchange_info to latest.
- class term_structure.models.async_multiple_wallet_exchange_broker.AsyncMultipleWalletExchangeBroker(wallet_name_to_wallet_map: Mapping[str, dict], host: str | None = None)
- async cancel_primary_order(wallet_name: str, order_hash: str, fee_token_name: str) dict
Cancel an open order from primary market.
- Parameters:
wallet_name – The user defined wallet name.
order_hash – The order identifier.
fee_token_name – The name of desired token to charge fee.
- async cancel_secondary_order(wallet_name: str, order_hash: str, fee_token_name: str) dict
Cancel an open order from secondary market.
- Parameters:
wallet_name – The user defined wallet name.
order_hash – The order identifier.
fee_token_name – The name of desired token to charge fee.
- property exchange_config: ExchangeConfig
Retrieve static configurations of Term Structure exchange.
- property exchange_info: ExchangeInfo
Retrieve runtime configurations of Term Structure exchange.
- async get_account(wallet_name: str) dict
Retrieve account information of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
- async get_assets(wallet_name: str) list
Retrieve asset information of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
- async get_base_token_prices(base_token_names: list[str]) list[Decimal]
Get base token prices information.
- Parameters:
base_token_names – A list of base token names to query.
- async get_deposit_history(wallet_name: str, start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve deposit history of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
- async get_loan_history(wallet_name: str) list
Retrieve loan history of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
- async get_loans(wallet_name: str) list
Retrieve loans of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
- async get_opened_orders(wallet_name: str, market: Literal['PRIMARY', 'SECONDARY', 'REPO'] = 'PRIMARY', start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve open orders of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
market – The market where orders belong to
- async get_orders_history(wallet_name: str, market: Literal['PRIMARY', 'SECONDARY', 'REPO'] = 'PRIMARY', start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve order history of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
market – The market where orders belong to
- async get_primary_candlesticks(main_token_name: str, start_time: int | None = None, end_time: int | None = None, limit: int | None = None) dict
Get candlesticks of specific main token in primary market.
- Parameters:
main_token_name – The bond token name.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_primary_ticker(main_token_name: str) dict
Get market ticker information of specific bond token in primary market.
- Parameters:
main_token_name – The bond token name.
- async get_redeem_history(wallet_name: str, layer: Literal['L1', 'L2']) list
Retrieve withdraw history of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
layer – The history of which layer in query.
- async get_repay_history(wallet_name: str) list
Retrieve repay history of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
- async get_secondary_candlesticks(main_token_name: str, start_time: int | None = None, end_time: int | None = None, limit: int | None = None) dict
Get candlesticks of specific main token in secondary market.
- Parameters:
main_token_name – The bond token name.
start_time – The inclusive start time in millisecond.
end_time – The exclusive end time in millisecond.
limit – Max query amount.
- async get_secondary_orderbook(main_token_name: str) dict
Get orderbook data information in secondary market.
- Parameters:
main_token_name – The bond token name.
- async get_secondary_ticker(main_token_name: str) dict
Get market ticker of specific main token in secondary market.
- Parameters:
main_token_name – The bond token name.
- async get_secondary_trades(main_token_name: str, limit: str | None = None) dict
Get trades information in secondary market.
- Parameters:
main_token_name – The bond token name.
limit – Max query amount.
- async get_withdraw_history(wallet_name: str, start_time: datetime | None = None, end_time: datetime | None = None, limit: int | None = None) list
Retrieve withdraw history of specific identity.
- Parameters:
wallet_name – The user defined wallet name.
- async place_primary_borrow_order(wallet_name: str, main_token_name: str, collateral_token_name: str, borrow_amount: Decimal, interest_rate: Decimal, collateral_amount: Decimal | None = None, min_fee_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place borrow order on specific primary market.
- Parameters:
wallet_name – The user defined wallet name.
main_token_name – The bond token name.
collateral_token_name – The collateral token name.
borrow_amount – The desired amount to borrow.
interest_rate – The desired interest rate to borrow.
collateral_amount – If specified, an over collateralized amount could be provided.
min_fee_base_token_amount – The minimum fee amount to be charged in base token.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 6 days. The time would be floored according to time to maturity.
client_order_id – A field to keep customized identifier for the order.
- async place_primary_lend_order(wallet_name: str, main_token_name: str, lend_amount: Decimal, interest_rate: Decimal, min_fee_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place lend order on specific primary market.
- Parameters:
wallet_name – The user defined wallet name.
main_token_name – The bond token name.
lend_amount – The desired amount to lend.
interest_rate – The desired interest rate to lend.
min_fee_base_token_amount – The minimum fee amount to be charged in base token.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 6 days. The time would be upper-bounded to one-day before maturity time.
client_order_id – A field to keep customized identifier for the order.
- async place_secondary_limit_order(wallet_name: str, order_side: Literal['SELL', 'BUY'], main_token_name: str, main_token_amount: Decimal, base_token_name: str, interest_rate: Decimal | None = None, base_token_amount: Decimal | None = None, min_taker_fee_base_token_amount: Decimal | None = None, min_maker_fee_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place limit order on specific secondary market.
- Parameters:
wallet_name – The user defined wallet name.
order_side – The desired side.
main_token_name – The bond token name.
main_token_amount – The desired amount to sell or buy.
base_token_name – The name of token desired to quote.
interest_rate – The desired interest rate to quote. This argument is mutully exclusive with base_token_amount.
base_token_amount – The desired quote amount. This argument is mutully exclusive with interest_rate.
min_taker_fee_base_token_amount – The minimum taker side fee amount to be charged in base token.
min_maker_fee_base_token_amount – The minimum maker side fee amount to be charged in base token.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 7 days. The time would be upper-bounded to maturity time.
client_order_id – A field to keep customized identifier for the order.
- async place_secondary_market_order(wallet_name: str, order_side: Literal['SELL', 'BUY'], main_token_name: str, main_token_amount: Decimal, base_token_name: str, min_taker_fee_base_token_amount: Decimal | None = None, stop_loss_interest_rate: Decimal | None = None, stop_loss_base_token_amount: Decimal | None = None, max_time_to_live: timedelta | None = None, client_order_id: str | None = None) dict
Place limit order on specific secondary market.
- Parameters:
wallet_name – The user defined wallet name.
order_side – The desired side.
main_token_name – The bond token name.
main_token_amount – The desired amount to sell or buy.
base_token_name – The name of token desired to quote.
min_taker_fee_base_token_amount – The minimum taker side fee amount to be charged in base token.
stop_loss_interest_rate – The desired interest rate to stop loss. This argument is mutully exclusive with stop_loss_base_token_amount.
stop_loss_base_token_amount – The desired quote amount to stop loss. This argument is mutully exclusive with stop_loss_interest_rate.
max_time_to_live – Set a customized max time to live before the order is executed. If not specified, it defaults to 7 days. The time would be upper-bounded to maturity time.
client_order_id – A field to keep customized identifier for the order.
- async redeem(wallet_name: str, main_token_name: str, main_token_amount: Decimal) dict
Redeem a matured loan for specific identity.
- Parameters:
wallet_name – The user defined wallet name.
main_token_name – The bond token name.
main_token_amount – The desired amount to redeem.
- async sync_exchange_config()
Update exchange_config to latest.
- async sync_exchange_info()
Update exchange_info to latest.
- class term_structure.models.contract_client.ContractClient(rpc_url: str, layer_1_wallet_private_key: str, layer_1_chain_id: str, layer_1_zk_true_up_contract_address: str)
Class of smart contract client that interacts with TermStructure contracts on Ethereum (L1).
- Parameters:
rpc_url – RPC URL of Ethereum network provider.
layer_1_wallet_private_key – Private key of the L1 crypto wallet.
layer_1_chain_id – Blockchain ID of the L1.
layer_1_zk_true_up_contract_address – TermStructure ZkTrueUp contract address.
- add_collateral(loan_id: str, collateral_amount: int, asset_approval: bool | None = False) dict
Add collateral crypto asset to the existing loan.
- Parameters:
loan_id – ID of the loan.
collateral_amount – Crypto asset amount to be added.
asset_approval (optional) – Initially send a transaction to call ERC20:approve() if setting with True. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
- approve_tokens(token_symbol: str, approve_amount: int, spender_address: str) dict
Call ERC20 token approval to set token allowance.
- Parameters:
token_symbol – ERC20 token symbol.
approve_amount – ERC20 token amount to be approved.
spender_address – Spender account address.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- approve_tokens_by_contract_address(token_address: str, approve_amount: int, spender_address: str) dict
Call ERC20 token approval to set token allowance. Access with the given token contract address.
- Parameters:
token_address – ERC20 token contract address.
approve_amount – ERC20 token amount to be approved.
spender_address – Spender account address.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
- static create_web3(rpc_url: str) Web3
Create a Web3 library instance for interacting with Ethereum.
- Parameters:
rpc_url – RPC URL of Ethereum network provider.
- Returns:
Web3 library instance.
- deposit(to_account_address: str, deposit_asset_symbol: str, deposit_amount: int, asset_approval: bool | None = False) dict
Deposit crypto asset to TermStructure.
- Parameters:
to_account_address – Receiver’s L1 wallet account address of the deposit.
deposit_asset_symbol – Crypto asset symbol (ETH or ERC20 token).
deposit_amount – Crypto asset amount to be deposited.
asset_approval (optional) – Initially send a transaction to call ERC20:approve() if setting with True. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
- force_withdraw(withdraw_asset_symbol: str) dict
Force withdrawal for the crypto asset from TermStructure.
- Parameters:
withdraw_asset_symbol – Crypto asset symbol (ETH or ERC20 token).
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
Note
Call this function and wait until the next rollup from L2.
Make sure the pending_balance on L1 is larger than zero.
Call withdraw() to return the asset from TermStructure contract to L1 wallet.
- get_account_address(account_id: int) str
Return account address from TermStructure contract by given account ID.
- Parameters:
account_id – Account ID on TermStructure.
- Returns:
L1 wallet account address.
- get_account_id(account_address: str) int
Return account ID from TermStructure contract by given account address.
- Parameters:
account_address – L1 wallet account address.
- Returns:
Account ID on TermStructure.
- get_asset_balance(asset_symbol: str, account_address: str) int
Return crypto asset (ETH or ERC20 token) balance of the given account address.
- Parameters:
asset_symbol – Crypto asset symbol (ETH or ERC20 token).
account_address – L1 wallet account address.
- Returns:
Crypto asset balance of the account address.
- get_asset_config(asset_symbol: str) tuple
Return crypto asset configuration from TermStructure contract by asset symbol.
- Parameters:
asset_symbol – Crypto asset symbol (ETH or ERC20 token).
- Returns:
Tuple of the asset configuration (is_stable_coin, is_tsb_token, decimals, min_deposit_amount contract_address, price_feed).
- get_asset_config_by_id(asset_id: int) tuple
Return crypto asset configuration from TermStructure contract by asset ID.
- Parameters:
asset_id – Crypto asset ID on TermStructure (ETH or ERC20 token).
- Returns:
Tuple of the asset configuration (is_stable_coin, is_tsb_token, decimals, min_deposit_amount contract_address, price_feed).
- get_asset_id(asset_symbol: str) int
Return crypto asset ID from TermStructure contract by asset symbol.
- Parameters:
asset_symbol – Crypto asset symbol (ETH or ERC20 token).
- Returns:
Asset ID on TermStructure contract.
- get_ether_balance(account_address: str) int
Return ETH balance of the given account address.
- Parameters:
account_address – L1 wallet account address.
- Returns:
ETH balance of the account address.
- get_health_factor(loan_id: str) int
Return health factor of the loan from TermStructure contract.
- Parameters:
loan_id – ID of the loan.
- Returns:
Health factor of the loan.
- get_latest_asset_price_data(asset_symbol: str) dict
Return latest crypto asset price data from price feed contract.
- Parameters:
asset_symbol – Crypto asset symbol (ETH or ERC20 token).
- Returns:
Dictionary of latest price data of the crypto asset (price, decimals).
- get_latest_asset_price_data_by_id(asset_id: int) dict
Return latest crypto asset price data by ID from price feed contract.
- Parameters:
asset_id – Crypto asset ID (ETH or ERC20 token).
- Returns:
Dictionary of latest price data of the crypto asset (price, decimals).
- get_liquidation_factor(is_stable_coin_pair: bool = False) tuple
Return liquidation factor of the debt/collateral crypto asset pair from TermStructure contract.
- Parameters:
is_stable_coin_pair – Set with True if both debt/collateral are stable coins. Set with False otherwise.
- Returns:
Tuple of liquidation factor information (liquidation_ltv_threshold, borrow_order_ltv_threshold, liquidator_incentive, protocol_penalty).
Note
- For example, in the case of returning (925, 30, 15):
liquidation_ltv_threshold = 925 indicates that the Liquidation LTV threshold is 0.925.
borrow_order_ltv_threshold = 900 indicates that the Borrow Order LTV threshold is 0.9.
liquidator_incentive = 30 indicates that the incentive percentage is 30%.
protocol_penalty = 15 indicates that the penalty percentage is 15%.
- get_loan_amount(loan_id: str) tuple
Return loan amount information from TermStructure contract.
- Parameters:
loan_id – ID of the loan.
- Returns:
Tuple of loan amount information (collateral_amount, locked_collateral_amount debt_amount).
- get_loan_id(debt_asset_symbol: str, collateral_asset_symbol: str, maturity_date: str, account_id: int | None = None) str
Return loan ID from TermStructure contract by loan information and account ID.
- Parameters:
debt_asset_symbol – Crypto asset symbol (ETH or ERC20 token).
collateral_asset_symbol – Crypto asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
account_id (optional) – Account ID on TermStructure.
- Returns:
ID of the loan.
Note
If account_id = None, the account ID of self.account.address is taken by default.
- get_pending_balance(pending_asset_symbol: str, account_address: str) int
Return pending balance of crypto asset triggered by withdrawal on TermStructure (L2).
- Parameters:
pending_asset_symbol – Crypto asset symbol (ETH or ERC20 token).
account_address – L1 wallet account address.
- Returns:
Account’s pending balance of crypto asset on TermStructure (L1).
- get_token_allowance(token_symbol: str, owner_address: str, spender_address: str) int
Return ERC20 token allowance of the given spender account address.
- Parameters:
token_symbol – ERC20 token symbol.
owner_address – L1 wallet account address of owner.
spender_address – L1 wallet account address of spender.
- Returns:
Amount of token allowance for the spender address.
- get_token_allowance_by_contract_address(token_address: str, owner_address: str, spender_address: str) int
Return ERC20 token allowance of the given spender account address. Access with the given token contract address.
- Parameters:
token_address – ERC20 token contract address.
owner_address – L1 wallet account address of owner.
spender_address – L1 wallet account address of spender.
- Returns:
Amount of token allowance for the spender address.
- get_token_balance(token_symbol: str, account_address: str) int
Return ERC20 token balance of the given account address.
- Parameters:
token_symbol – ERC20 token symbol.
account_address – L1 wallet account address.
- Returns:
ERC20 token balance of the account address.
- get_token_balance_by_contract_address(token_address: str, account_address: str) int
Return ERC20 token balance of the given account address. Access with the given token contract address.
- Parameters:
token_address – ERC20 token contract address.
account_address – L1 wallet account address.
- Returns:
ERC20 token balance of the account address.
- get_token_decimals_by_contract_address(token_address: str) int
Return ERC20 token decimals. Access with the given token contract address.
- Parameters:
token_address – ERC20 token contract address.
- Returns:
Decimals of the ERC20 token.
- get_token_name_by_contract_address(token_address: str) str
Return ERC20 token name. Access with the given token contract address.
- Parameters:
token_address – ERC20 token contract address.
- Returns:
Name of the ERC20 token.
- get_token_symbol_by_contract_address(token_address: str) str
Return ERC20 token symbol. Access with the given token contract address.
- Parameters:
token_address – ERC20 token contract address.
- Returns:
Symbol of the ERC20 token.
- get_token_total_supply_by_contract_address(token_address: str) int
Return ERC20 token total supply. Access with the given token contract address.
- Parameters:
token_address – ERC20 token contract address.
- Returns:
Total supply of the ERC20 token.
- get_tsb_token_address(underlying_asset_id: int, maturity_date: str) str
Return TSB token address from TermStructure contract by underlying asset ID and maturity date string.
- Parameters:
underlying_asset_id – Underlying asset ID on TermStructure.
maturity_date – Maturity date string of the TSB token (YYYY-MM-DD).
- Returns:
TSB token contract address.
- static get_uint_max() int
Get the maximum value of data type uint256 from Web3 library.
- Returns:
Maximum value of uint256.
- static get_utc_date_str(timestamp: int) str
Convert timestamp to UTC date string.
- Parameters:
timestamp – timestamp in seconds.
- Returns:
Date string in UTC format.
- Raises:
ValueError – invalid literal for int() with base 10
- static get_utc_timestamp(date_str: str) int
Convert date string to UTC timestamp.
- Parameters:
date_str – Date string in YYYY-MM-DD format.
- Returns:
Timestamp in UTC format.
- Raises:
ValueError – Time data does not match format
- handle_contract_error(error: ContractError)
Handle and raise TermStructure contract error.
- static is_valid_l1_address(address: str) bool
Check whether the given address is valid (in correct format).
- Parameters:
address – account address or contract address on L1 blockchain.
- Returns:
True if the given address is valid. False otherwise.
- static load_json_by_path(path: str) Json
Load JSON file by a given path.
- Parameters:
path – JSON file path.
- Returns:
JSON-format content.
- redeem(tsb_token_address: str, redeem_amount: int, redeem_and_deposit: bool | None = False) dict
Redeem underlying crypto asset with TSB tokens.
- Parameters:
tsb_token_address – TSB token contract address.
redeem_amount – TSB token amount for redemption.
redeem_and_deposit (optional) – Redeem the returned underlying crypto asset to L2 if setting with True. Otherwise, the underlying crypto asset is returned to L1 wallet. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
- register(deposit_asset_symbol: str, deposit_amount: int, asset_approval: bool | None = False) dict
Register a new user account with crypto asset deposit on TermStructure.
- Parameters:
deposit_asset_symbol – Crypto asset symbol (ETH or ERC20 token).
deposit_amount – Crypto asset amount to be deposited.
asset_approval (optional) – Initially send a transaction to call ERC20:approve() if setting with True. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
Note
In order to register on TermStructure, some crypto asset deposit is required.
- remove_collateral(loan_id: str, collateral_amount: int) dict
Remove collateral crypto asset from the existing loan.
- Parameters:
loan_id – ID of the loan.
collateral_amount – Collateral asset amount to be removed.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
- repay(loan_id: str, collateral_amount: int, debt_amount: int, repay_and_deposit: bool | None = False, asset_approval: bool | None = False) dict
Repay debt crypto asset to the existing loan. Loan owner only.
- Parameters:
loan_id – ID of the loan.
collateral_amount – Crypto asset amount to be returned.
debt_amount – Crypto asset amount to be repaid.
repay_and_deposit (optional) – Deposit the returned collateral asset to L2 if setting with True. Otherwise, the collateral asset is returned to L1 wallet. Defaults to False.
asset_approval (optional) – Initially send a transaction to call ERC20:approve() if setting with True. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
- resolve_loan_id(loan_id: str) list
Resolve loan ID on TermStructure contract.
- Parameters:
loan_id – ID of the loan.
- Returns:
List of the result from resolving the loan ID [account_id, maturity_time, debt_asset_id, collateral_asset_id].
- withdraw(withdraw_asset_symbol: str, withdraw_amount: int) dict
Normal withdrawal for the crypto asset from TermStructure.
- Parameters:
withdraw_asset_symbol – Crypto asset symbol (ETH or ERC20 token).
withdraw_amount – Crypto asset amount to be withdrawn.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
Note
Withdrawal request on L2 should be sent in advance.
Make sure the pending_balance on L1 is larger than zero.
Wait until the next rollup and call this function.
- class term_structure.models.contract_broker.ContractBroker(rpc_url: str, layer_1_wallet_private_key: str, layer_1_chain_id: str | None = None, layer_1_zk_true_up_contract_address: str | None = None, contract_client: ContractClient | None = None)
Class of smart contract broker that interacts with TermStructure contracts on Ethereum (L1).
- Parameters:
rpc_url – RPC URL of Ethereum network provider.
layer_1_wallet_private_key – Private key of the L1 crypto wallet.
layer_1_chain_id (optional) – Blockchain ID of the L1.
layer_1_zk_true_up_contract_address (optional) – TermStructure ZkTrueUp contract address.
contract_client (optional) – Existing TermStructure ContractClient instance. Defaults to None.
- add_collateral_by_loan_id_with_allowance_check(loan_id: str, collateral_amount: Decimal) dict
Add collateral crypto asset to the existing loan by loan ID with checking ERC20 token allowance in advance.
- Parameters:
loan_id – ID of the loan.
collateral_amount – Collateral asset amount to be added.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
Note
This function will check whether the amount of token allowance is enough to add collateral. If it’s not, an extra transaction will be sent to call ERC20:approve().
- add_collateral_by_loan_info(debt_asset_symbol: str, collateral_asset_symbol: str, maturity_date: str, collateral_amount: Decimal) dict
Add collateral crypto asset to the existing loan by loan info with checking ERC20 token allowance in advance.
- Parameters:
debt_asset_symbol – Debt asset symbol (ETH or ERC20 token).
collateral_asset_symbol – Collateral asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
collateral_amount – Collateral asset amount to be added.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
ContractBrokerError – { collateral_asset_symbol } is not found
ContractBrokerError – { debt_asset_symbol } is not found
TermStructureContractError – { error returned from contract }
Note
This function will check whether the amount of token allowance is enough to add collateral. If it’s not, an extra transaction will be sent to call ERC20:approve().
- deposit_with_allowance_check(layer_1_wallet_address: str, deposit_asset_symbol: str, deposit_amount: Decimal) dict
Deposit crypto asset to TermStructure with checking ERC20 token allowance in advance.
- Parameters:
layer_1_wallet_address – Receiver’s L1 wallet account address of the deposit.
deposit_asset_symbol – Deposit asset symbol (ETH or ERC20 token).
deposit_amount – Asset amount to be deposited.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
ContractBrokerError – { layer_1_wallet_address } address is invalid or empty
ContractBrokerError – { deposit_asset_symbol } is not found
ContractBrokerError – Specified deposit amount < minimum deposit amount ({value})
TermStructureContractError – { error returned from contract }
Note
This function will check whether the amount of token allowance is enough to deposit. If it’s not, an extra transaction will be sent to call ERC20:approve().
- force_withdraw(withdraw_asset_symbol: str) dict
Force withdrawal for the crypto asset from TermStructure.
- Parameters:
withdraw_asset_symbol – Withdrawal crypto asset symbol (ETH or ERC20 token).
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
ContractBrokerError – { withdraw_asset_symbol } is not found
TermStructureContractError – { error returned from contract }
Note
Call this function and wait until the next rollup from L2.
Make sure the pending_balance on L1 is larger than zero.
Call withdraw() to return the asset from TermStructure contract to L1 wallet.
- get_account_address_by_account_id(account_id: int) str
Return account address from TermStructure contract by given account ID.
- Parameters:
account_id – Account ID on TermStructure.
- Returns:
L1 wallet account address.
- get_account_id() int
Return account ID from TermStructure contract.
- Returns:
Account ID on TermStructure.
- get_account_id_by_account_address(account_address: str) int
Return account ID from TermStructure contract by given account address.
- Parameters:
account_address – L1 wallet account address.
- Returns:
Account ID on TermStructure.
- Raises:
ContractBrokerError – { account_address } address is invalid or empty
- get_asset_balance(asset_symbol: str) Decimal
Return crypto asset (ETH or ERC20 token) balance of the given account address.
- Parameters:
asset_symbol – Crypto asset symbol (ETH or ERC20 token).
- Returns:
Crypto asset balance of the account address.
- Raises:
ContractBrokerError – { asset_symbol } is not found
- get_asset_config(asset_symbol: str) dict
Return crypto asset configuration from TermStructure contract by asset symbol.
- Parameters:
asset_symbol – Crypto asset symbol (ETH or ERC20 token).
- Returns:
Dictionary of the asset configuration (is_stable_coin, is_tsb_token, decimals, min_deposit_amount contract_address, price_feed).
- Raises:
ContractBrokerError – { asset_symbol } is not found
- get_asset_config_by_id(asset_id: int) dict
Return crypto asset configuration from TermStructure contract by asset ID.
- Parameters:
asset_id – Crypto asset ID on TermStructure (ETH or ERC20 token).
- Returns:
Dictionary of the asset configuration (is_stable_coin, is_tsb_token, decimals, min_deposit_amount contract_address, price_feed).
- get_asset_id(asset_symbol: str) int
Return crypto asset ID from TermStructure contract by asset symbol.
- Parameters:
asset_symbol – Crypto asset symbol (ETH or ERC20 token).
- Returns:
Asset ID on TermStructure contract.
- Raises:
ContractBrokerError – { asset_symbol } is not found
- get_health_factor_by_loan_id(loan_id: str) Decimal
Return health factor of the loan from TermStructure contract by loan ID.
- Parameters:
loan_id – ID of the loan.
- Returns:
Health factor of the loan.
- get_health_factor_by_loan_info(debt_asset_symbol: str, collateral_asset_symbol: str, maturity_date: str) Decimal
Return health factor of the loan from TermStructure contract by loan info.
- Parameters:
debt_asset_symbol – Debt asset symbol (ETH or ERC20 token).
collateral_asset_symbol – Collateral asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
- Returns:
Health factor of the loan.
- Raises:
ContractBrokerError – { debt_asset_symbol } is not found
ContractBrokerError – { collateral_asset_symbol } is not found
- get_latest_asset_price_data(asset_symbol: str) Decimal
Return latest crypto asset price data from price feed contract.
- Parameters:
asset_symbol – Crypto asset symbol (ETH or ERC20 token).
- Returns:
Latest price data of the crypto asset.
- Raises:
ContractBrokerError – { asset_symbol } is not found
- get_liquidation_factor(is_stable_coin_pair: bool = False) dict
Return liquidation factor of the debt/collateral crypto asset pair from TermStructure contract.
- Parameters:
is_stable_coin_pair – Set with True if both debt/collateral are stable coins. Set with False otherwise.
- Returns:
Dictionary of liquidation factor information (liquidation_ltv_threshold, borrow_order_ltv_threshold, liquidator_incentive, protocol_penalty).
- get_loan_amount_by_loan_id(loan_id: str) dict
Return loan amount information from TermStructure contract by loan ID.
- Parameters:
loan_id – ID of the loan.
- Returns:
Dictionary of loan amount information (collateral_amount, locked_collateral_amount, debt_amount).
- get_loan_amount_by_loan_info(debt_asset_symbol: str, collateral_asset_symbol: str, maturity_date: str) Decimal
Return loan amount information from TermStructure contract by loan info.
- Parameters:
debt_asset_symbol – Debt asset symbol (ETH or ERC20 token).
collateral_asset_symbol – Collateral asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
- Returns:
Dictionary of loan amount information (debt_amount, collateral_amount).
- Raises:
ContractBrokerError – { debt_asset_symbol } is not found
ContractBrokerError – { collateral_asset_symbol } is not found
- get_loan_dict(debt_asset_symbol: str, collateral_asset_symbol: str, maturity_date: str) dict
Return aggregated loan data from TermStructure contract by given loan information.
- Parameters:
debt_asset_symbol – Debt asset symbol (ETH or ERC20 token).
collateral_asset_symbol – Collateral asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
- Returns:
Dictionary of the loan data (loan_id, debt_amount, collateral_amount, account_id, debt_asset_id, collateral_asset_id, maturity_time, maturity_date, health_factor).
- Raises:
ContractBrokerError – { debt_asset_symbol } is not found
ContractBrokerError – { collateral_asset_symbol } is not found
- get_loan_dict_by_id(loan_id: str) dict
Return aggregated loan data from TermStructure contract by given loan ID.
- Parameters:
loan_id – ID of the loan.
- Returns:
Dictionary of the loan data (loan_id, collateral_amount, locked_collateral_amount, debt_amount, account_id, debt_asset_id, collateral_asset_id, maturity_time, maturity_date, health_factor).
- get_loan_id(debt_asset_symbol: str, collateral_asset_symbol: str, maturity_date: str) str
Return loan ID from TermStructure contract by loan information.
- Parameters:
debt_asset_symbol – Debt crypto asset symbol (ETH or ERC20 token).
collateral_asset_symbol – Collateral crypto asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
- Returns:
ID of the loan.
- Raises:
ContractBrokerError – { debt_asset_symbol } is not found
ContractBrokerError – { collateral_asset_symbol } is not found
- get_max_removable_collateral_amount_by_loan_id(loan_id: str) Decimal
Calculate and return maximum removable collateral amount of the loan and decimals of the collateral by loan ID.
- Parameters:
loan_id – ID of the loan.
- Returns:
Maximum of removable collateral amount.
- get_max_removable_collateral_amount_by_loan_info(debt_asset_symbol: str, collateral_asset_symbol: str, maturity_date: str) Decimal
Calculate and return maximum removable collateral amount of the loan and decimals of the collateral by loan info.
- Parameters:
debt_asset_symbol – Debt asset symbol (ETH or ERC20 token).
collateral_asset_symbol – Collateral asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
- Returns:
Maximum of removable collateral amount.
- get_minimum_deposit_amount(deposit_asset_symbol: str) Decimal
Return required minimum deposit amount of the crypto asset.
- Parameters:
deposit_asset_symbol – Deposit asset symbol (ETH or ERC20 token).
- Returns:
Minimum deposit amount of the crypto asset.
- Raises:
ContractBrokerError – { deposit_asset_symbol } is not found
- get_normalized_asset_price(asset_symbol: str) int
Return normalized crypto asset price from price feed contract.
- Parameters:
asset_symbol – Crypto asset symbol (ETH or ERC20 token).
- Returns:
Normalized price of the crypto asset (decimals = 18).
- Raises:
ContractBrokerError – { asset_symbol } is not found
- get_normalized_asset_price_by_id(asset_id: int) int
Return normalized crypto asset price by ID from price feed contract.
- Parameters:
asset_id – Crypto asset ID (ETH or ERC20 token).
- Returns:
Normalized price of the crypto asset (decimals = 18).
- get_pending_balance(pending_asset_symbol: str) Decimal
Return pending balance of crypto asset triggered by withdrawal on TermStructure (L2).
- Parameters:
pending_asset_symbol – Pending crypto asset symbol (ETH or ERC20 token).
- Returns:
Account’s pending balance of crypto asset on TermStructure (L1).
- Raises:
ContractBrokerError – { pending_asset_symbol } is not found
- get_token_info(token_symbol: str) dict
Return ERC20 token information.
- Parameters:
token_symbol – ERC20 token symbol.
- Returns:
Dictionary of ERC20 token information (contract_address, name, symbol, decimals, balance_of, total_supply).
- Raises:
ContractBrokerError – { token_symbol } is not found
ContractBrokerError – Asset { token_symbol } is not ERC20 tokens or not found
ContractBrokerError – Asset { token_symbol } address is invalid or empty
- get_token_info_by_contract_address(token_address: str) dict
Return ERC20 token information. Access with the given token contract address.
- Parameters:
token_address – ERC20 token contract address.
- Returns:
Dictionary of ERC20 token information (contract_address, name, symbol, decimals, balance_of, total_supply).
- Raises:
ContractBrokerError – { token_address } address is invalid or empty
- get_tsb_token_address(underlying_asset_symbol: str, maturity_date: str) str
Return TSB token address from TermStructure contract by underlying asset symbol and maturity date string.
- Parameters:
underlying_asset_symbol – Underlying asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the TSB token (YYYY-MM-DD).
- Returns:
TSB token contract address.
- Raises:
ContractBrokerError – { underlying_asset_symbol } is not found
- get_tsb_token_info(underlying_asset_symbol: str, maturity_date: str) dict
Return TSB token balance of the given account address.
- Parameters:
underlying_asset_symbol – Underlying crypto asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
- Returns:
Dictionary of TSB token information (contract_address, name, symbol, decimals, balance_of, total_supply).
- Raises:
ContractBrokerError – { underlying_asset_symbol } is not found
- redeem_asset_by_asset_info(underlying_asset_symbol: str, maturity_date: str, redeem_amount: Decimal, deposit_to_l2: bool | None = False)
Redeem underlying crypto asset with TSB tokens by asset info.
- Parameters:
underlying_asset_symbol – Underlying crypto asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
redeem_amount – TSB token amount for redemption.
deposit_to_l2 (optional) – Redeem the returned underlying crypto asset to L2 if setting with True. Otherwise, the underlying crypto asset is returned to L1 wallet. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
ContractBrokerError – { underlying_asset_symbol } is not found
ContractBrokerError – Specified deposit amount < minimum deposit amount ({value})
TermStructureContractError – { error returned from contract }
- redeem_asset_by_tsb_token_address(tsb_token_address: str, redeem_amount: Decimal, deposit_to_l2: bool | None = False) dict
Redeem underlying crypto asset with TSB tokens by TSB token address.
- Parameters:
tsb_token_address – TSB token contract address.
redeem_amount – TSB token amount for redemption.
deposit_to_l2 (optional) – Redeem the returned underlying crypto asset to L2 if setting with True. Otherwise, the underlying crypto asset is returned to L1 wallet. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
ContractBrokerError – { tsb_token_address } address is invalid or empty
TermStructureContractError – { error returned from contract }
- register_with_allowance_check(deposit_asset_symbol: str, deposit_amount: Decimal) dict
Register a new user account with crypto asset deposit on TermStructure with checking ERC20 token allowance in advance.
- Parameters:
deposit_asset_symbol – Deposit asset symbol (ETH or ERC20 token).
deposit_amount – Asset amount to be deposited.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
ContractBrokerError – { deposit_asset_symbol } is not found
ContractBrokerError – Specified deposit amount < minimum deposit amount ({value})
TermStructureContractError – { error returned from contract }
Note
In order to register on TermStructure, some crypto asset deposit is required.
This function will check whether the amount of token allowance is enough to deposit. If it’s not, an extra transaction will be sent to call ERC20:approve().
- remove_collateral_by_loan_id(loan_id: str, collateral_amount: Decimal) dict
Remove collateral crypto asset from the existing loan by loan ID.
- Parameters:
loan_id – ID of the loan.
collateral_amount – Collateral asset amount to be removed.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
- remove_collateral_by_loan_info(debt_asset_symbol: str, collateral_asset_symbol: str, maturity_date: str, collateral_amount: Decimal | None = None, max_amount_removal: bool | None = False) dict
Remove collateral crypto asset to the existing loan by loan info.
- Parameters:
debt_asset_symbol – Debt asset symbol (ETH or ERC20 token).
collateral_asset_symbol – Collateral asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
collateral_amount (optional) – Collateral asset amount to be removed. Defaults to None. It will be 0 if max_amount_removal is False.
max_amount_removal (optional) – Remove collateral asset with maximum removable amount if setting with True. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
ContractBrokerError – { collateral_asset_symbol } is not found
ContractBrokerError – { debt_asset_symbol } is not found
TermStructureContractError – { error returned from contract }
- repay_by_loan_id_with_allowance_check(loan_id: str, collateral_amount: Decimal, debt_amount: Decimal, deposit_to_l2: bool | None = False) dict
Repay debt crypto asset to the existing loan by loan ID with checking ERC20 token allowance in advance. Loan owner only.
- Parameters:
loan_id – ID of the loan.
collateral_amount – Collateral asset amount to be returned.
debt_amount – Debt asset amount to be repaid.
deposit_to_l2 (optional) – Deposit the returned collateral asset to L2 if setting with True. Otherwise, the collateral asset is returned to L1 wallet. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
TermStructureContractError – { error returned from contract }
Note
This function will check whether the amount of token allowance is enough to repay debt. If it’s not, an extra transaction will be sent to call ERC20:approve().
- repay_by_loan_info(debt_asset_symbol: str, collateral_asset_symbol: str, maturity_date: str, collateral_amount: Decimal, debt_amount: Decimal, deposit_to_l2: bool | None = False) dict
Repay debt crypto asset to the existing loan by loan info with checking ERC20 token allowance in advance. Loan owner only.
- Parameters:
debt_asset_symbol – Debt asset symbol (ETH or ERC20 token).
collateral_asset_symbol – Collateral asset symbol (ETH or ERC20 token).
maturity_date – Maturity date string of the loan (YYYY-MM-DD).
collateral_amount – Collateral asset amount to be returned.
debt_amount – Debt asset amount to be repaid.
deposit_to_l2 (optional) – Deposit the returned collateral asset to L2 if setting with True. Otherwise, the collateral asset is returned to L1 wallet. Defaults to False.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
ContractBrokerError – { collateral_asset_symbol } is not found
ContractBrokerError – { debt_asset_symbol } is not found
ContractBrokerError – Specified deposit amount < minimum deposit amount ({value})
TermStructureContractError – { error returned from contract }
Note
This function will check whether the amount of token allowance is enough to add collateral. If it’s not, an extra transaction will be sent to call ERC20:approve().
- resolve_loan_id(loan_id: str) dict
Resolve loan ID on TermStructure contract.
- Parameters:
loan_id – ID of the loan.
- Returns:
Dictionary of the result from resolving the loan ID [account_id, maturity_time, debt_asset_id, collateral_asset_id].
- validate_deposit_amount(deposit_asset_symbol: str, deposit_amount: Decimal)
Check the minimum deposit amount of the crypto asset before the deposit.
- Parameters:
deposit_asset_symbol – Deposit asset symbol (ETH or ERC20 token).
deposit_amount – Asset amount to be deposited.
- Raises:
ContractBrokerError – Specified deposit amount < minimum deposit amount ({value})
ContractBrokerError – { deposit_asset_symbol } is not found
- withdraw(withdraw_asset_symbol: str, withdraw_amount: Decimal) dict
Normal withdrawal for the crypto asset from TermStructure.
- Parameters:
withdraw_asset_symbol – Withdrawal crypto asset symbol (ETH or ERC20 token).
withdraw_amount – Crypto asset amount to be withdrawn.
- Returns:
Dictionary of transaction information (tx_hash, gas_fee).
- Raises:
ContractBrokerError – { withdraw_asset_symbol } is not found
TermStructureContractError – { error returned from contract }
Note
Withdrawal request on L2 should be sent in advance.
Make sure the pending_balance on L1 is larger than zero.
Wait until the next rollup and call this function.
Schemas
- class term_structure.schemas.ExchangeInfo(*, raw: dict, last_updated_time: datetime)
Runtime configurations of Term Structure exchange.