Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add wasm bindings for orders #1836

Merged
merged 2 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions wasm-wrappers/WASM-API.md
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,22 @@ It is recommended to use a strict `Transaction` size and set the second paramete
Calculate the "effective balance" of a pool, given the total pool balance and pledge by the pool owner/staker.
The effective balance is how the influence of a pool is calculated due to its balance.

### Function: `encode_create_order_output`

Given ask and give amounts and a conclude key create output that creates an order.

'ask_token_id' parameter represents a Token is it's Some and a Coin otherwise.
'give_token_id' parameter represents a Token is it's Some and a Coin otherwise.

### Function: `encode_input_for_fill_order`

Given amount to fill order (which is described in terms of ask currency) and a destination
for for result outputs create an input that fills and order.

### Function: `encode_input_for_conclude_order`

Given and order id create an input that concludes an order.

### Enum: `Network`

The network, for which an operation to be done. Mainnet, testnet, etc.
Expand Down
40 changes: 40 additions & 0 deletions wasm-wrappers/js-bindings/wasm_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ import {
encode_multisig_challenge,
encode_witness_htlc_multisig,
extract_htlc_secret,
encode_create_order_output,
encode_input_for_fill_order,
encode_input_for_conclude_order,
SignatureHashType,
encode_input_for_withdraw_from_delegation,
estimate_transaction_size,
Expand Down Expand Up @@ -776,6 +779,43 @@ export async function run_test() {
);
console.log("htlc with tokens encoding ok");

encode_create_order_output(
azarovh marked this conversation as resolved.
Show resolved Hide resolved
Amount.from_atoms("40000"),
undefined,
Amount.from_atoms("10000"),
token_id,
address,
Network.Testnet
);
console.log("create order coins for tokens encoding ok");

encode_create_order_output(
Amount.from_atoms("10000"),
token_id,
Amount.from_atoms("40000"),
undefined,
address,
Network.Testnet
);
console.log("create order tokens for coins encoding ok");

const order_id = "tordr1xxt0avjtt4flkq0tnlyphmdm4aaj9vmkx5r2m4g863nw3lgf7nzs7mlkqc";
encode_input_for_fill_order(
order_id,
Amount.from_atoms("40000"),
address,
BigInt(1),
Network.Testnet
);
console.log("fill order encoding ok");

encode_input_for_conclude_order(
order_id,
BigInt(1),
Network.Testnet
);
console.log("conclude order encoding ok");

try {
const invalid_inputs = "invalid inputs";
encode_transaction(invalid_inputs, outputs, BigInt(0));
Expand Down
89 changes: 79 additions & 10 deletions wasm-wrappers/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,9 @@ use common::{
make_token_id, IsTokenFreezable, Metadata, NftIssuance, NftIssuanceV0, TokenCreator,
TokenId, TokenIssuance, TokenIssuanceV1, TokenTotalSupply,
},
AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, Destination, OutPointSourceId,
SignedTransaction, Transaction, TxInput, TxOutput, UtxoOutPoint,
AccountCommand, AccountNonce, AccountOutPoint, AccountSpending, ChainConfig, Destination,
OrderData, OutPointSourceId, SignedTransaction, Transaction, TxInput, TxOutput,
UtxoOutPoint,
},
primitives::{
self, amount::UnsignedIntType, per_thousand::PerThousand, BlockHeight, Idable, H256,
Expand Down Expand Up @@ -793,6 +794,21 @@ pub fn data_deposit_fee(current_block_height: u64, network: Network) -> Amount {
)
}

fn parse_output_value(
chain_config: &ChainConfig,
amount: &Amount,
token_id: Option<String>,
) -> Result<OutputValue, Error> {
let amount = amount.as_internal_amount()?;
match token_id {
Some(token_id) => {
let token_id = parse_addressable(chain_config, &token_id)?;
Ok(OutputValue::TokenV1(token_id, amount))
}
None => Ok(OutputValue::Coin(amount)),
}
}

/// Given the parameters needed to create hash timelock contract, and a network type (mainnet, testnet, etc),
/// this function creates an output.
#[wasm_bindgen]
Expand All @@ -806,14 +822,7 @@ pub fn encode_output_htlc(
network: Network,
) -> Result<Vec<u8>, Error> {
let chain_config = Builder::new(network.into()).build();
let amount = amount.as_internal_amount()?;
let output_value = match token_id {
Some(token_id) => {
let token_id = parse_addressable(&chain_config, &token_id)?;
OutputValue::TokenV1(token_id, amount)
}
None => OutputValue::Coin(amount),
};
let output_value = parse_output_value(&chain_config, &amount, token_id)?;
let refund_timelock = OutputTimeLock::decode_all(&mut &refund_timelock[..])
.map_err(|_| Error::InvalidTimeLock)?;
let secret_hash =
Expand Down Expand Up @@ -1248,6 +1257,66 @@ pub fn effective_pool_balance(
Ok(Amount::from_internal_amount(effective_balance))
}

/// Given ask and give amounts and a conclude key create output that creates an order.
///
/// 'ask_token_id' parameter represents a Token is it's Some and a Coin otherwise.
azarovh marked this conversation as resolved.
Show resolved Hide resolved
/// 'give_token_id' parameter represents a Token is it's Some and a Coin otherwise.
#[wasm_bindgen]
pub fn encode_create_order_output(
ask_amount: Amount,
ask_token_id: Option<String>,
give_amount: Amount,
give_token_id: Option<String>,
Comment on lines +1267 to +1269
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we pass Option<&str> here, for consistency with conclude_address?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is done because Option<&str> is not supported by wasm

conclude_address: &str,
network: Network,
) -> Result<Vec<u8>, Error> {
let chain_config = Builder::new(network.into()).build();
let ask = parse_output_value(&chain_config, &ask_amount, ask_token_id)?;
let give = parse_output_value(&chain_config, &give_amount, give_token_id)?;
let conclude_key = parse_addressable::<Destination>(&chain_config, conclude_address)?;

let order = OrderData::new(conclude_key, ask, give);
let output = TxOutput::CreateOrder(Box::new(order));
Ok(output.encode())
}

/// Given amount to fill order (which is described in terms of ask currency) and a destination
/// for for result outputs create an input that fills and order.
azarovh marked this conversation as resolved.
Show resolved Hide resolved
#[wasm_bindgen]
pub fn encode_input_for_fill_order(
order_id: &str,
fill_amount: Amount,
destination: &str,
nonce: u64,
network: Network,
) -> Result<Vec<u8>, Error> {
let chain_config = Builder::new(network.into()).build();
let order_id = parse_addressable(&chain_config, order_id)?;
let fill_amount = fill_amount.as_internal_amount()?;
let destination = parse_addressable::<Destination>(&chain_config, destination)?;
let input = TxInput::AccountCommand(
AccountNonce::new(nonce),
AccountCommand::FillOrder(order_id, fill_amount, destination),
);
Ok(input.encode())
}

/// Given and order id create an input that concludes an order.
azarovh marked this conversation as resolved.
Show resolved Hide resolved
#[wasm_bindgen]
pub fn encode_input_for_conclude_order(
order_id: &str,
nonce: u64,
network: Network,
) -> Result<Vec<u8>, Error> {
let chain_config = Builder::new(network.into()).build();
let order_id = parse_addressable(&chain_config, order_id)?;
let input = TxInput::AccountCommand(
AccountNonce::new(nonce),
AccountCommand::ConcludeOrder(order_id),
);
Ok(input.encode())
}

#[cfg(test)]
mod tests {
use randomness::Rng;
Expand Down
Loading