Skip to content

Commit

Permalink
working almost, got the bucket requirement direction mismatched
Browse files Browse the repository at this point in the history
  • Loading branch information
devmannic committed Mar 10, 2022
1 parent df77759 commit 010a54b
Show file tree
Hide file tree
Showing 7 changed files with 27 additions and 5 deletions.
6 changes: 5 additions & 1 deletion 1-exchanges/hareswap/hare/src/harelib/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ impl MakeSignedOrder {
taker_contents: BucketContents::Fungible(resource_a_amount),
maker_callback: Callback::CallMethod {
component_address: maker_component_address,
method: "default_swap".to_owned(),
method: "handle_order_default_callback".to_owned(),
args: vec![],
},
};
Expand All @@ -153,6 +153,10 @@ impl MakeSignedOrder {

let voucher_encoded = scrypto_encode(&voucher);

// TEST DECODE
let decoded_voucher = private_decode_with_type::<Voucher>(&voucher_encoded).unwrap();
assert_eq!(voucher, decoded_voucher, "voucher decode error");

eprintln!("signing voucher bytes:\n{}", hex::encode(&voucher_encoded));

let signing_key = SigningKey::from_bytes(&private_key_bytes).expect("unable to create signing key (this should not happen)");
Expand Down
1 change: 1 addition & 0 deletions 1-exchanges/hareswap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ mod account;

pub mod api {
pub use super::maker::*;
pub use super::transporter::decoder::*;
pub use super::transporter::voucher::{Voucher, PassThruNFD, IsPassThruNFD};
pub use super::requirement::*;
pub use super::transporter::authentication::{sign, verify};
Expand Down
5 changes: 5 additions & 0 deletions 1-exchanges/hareswap/src/maker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,11 +72,14 @@ blueprint! {
// }

pub fn instantiate(verifying_key: EcdsaPublicKey, callback_auth: Option<Bucket>, account: Component, account_auth: Bucket) -> Component {
// change this redeem_auth to be a parameter
let redeem_auth = Vault::with_bucket(ResourceBuilder::new_fungible(DIVISIBILITY_NONE).initial_supply_fungible(1));

let transporter: Transporter = Transporter::instantiate(verifying_key, redeem_auth.resource_def()).into();
let order_def = transporter.resource_def(); // this wont change, save it here

info!("tokenized order resource address: {}", order_def.address());

// default to expecting the default callback and so just make the callback_auth ourselves
let callback_auth = if callback_auth.is_none() {
Vault::with_bucket(ResourceBuilder::new_fungible(DIVISIBILITY_NONE).initial_supply_fungible(1))
Expand Down Expand Up @@ -131,6 +134,7 @@ blueprint! {

// private, signature verification must happen first
fn settle_order(&mut self, matched_order: MatchedOrder, from_taker: Bucket) -> /*fromMaker*/ Bucket {
info!("settle_order: matched_order: {:?}", matched_order);
// just calling the callback with our auth. It will verify and execute

// tail call the callback with auth
Expand Down Expand Up @@ -216,6 +220,7 @@ blueprint! {
// call this as the entrypoint for the boring way to execute the SignedOrder
pub fn execute_order(&mut self, signed_order: SignedOrder, from_taker: Bucket, taker_auth: BucketRef) -> Bucket {
let orders = self.tokenize_order(signed_order, taker_auth);
info!("execute_order: SignedOrder successfully tokenized: {:?}", orders);
self.execute_order_token(orders, from_taker)
}

Expand Down
4 changes: 4 additions & 0 deletions 1-exchanges/hareswap/src/requirement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,20 @@ impl PartialEq<BucketContents> for BucketRef {

impl PartialOrd<BucketContents> for BucketRef {
fn partial_cmp(&self, other: &BucketContents) -> Option<Ordering> {
debug!("partial_cmd: {:?} =?= {:?}", self, other);
let bucket_type = self.resource_def().resource_type();

match (bucket_type, other) {
(ResourceType::Fungible { .. }, BucketContents::Fungible(amount)) => {
debug!("partial_cmd: Fungible {:?} =?= {:?}", self.amount(), amount);
Some(self.amount().cmp(amount))
},
(ResourceType::NonFungible, BucketContents::NonFungible(keys)) => {
// avoid copies by comparing sets of references. Iterates over the sets more than strictly needed to make the code simplier
let contents_keys: BTreeSet<&NonFungibleKey> = keys.iter().collect();
let self_keys = self.get_non_fungible_keys();
let self_keys: BTreeSet<&NonFungibleKey> = self_keys.iter().collect();
debug!("partial_cmd: NonFungible {:?} =?= {:?}", self_keys, contents_keys);
Some(self_keys.cmp(&contents_keys))
},
(_, _) => None,
Expand All @@ -67,6 +70,7 @@ impl BucketRequirement {
bucket.authorize(|bucket_ref| self.check_ref(&bucket_ref))
}
pub fn check_at_least_ref(&self, bucket_ref: &BucketRef) -> bool {
debug!("check_at_least_ref: {:?} =?= {:?}", self, bucket_ref.resource_def());
// same resource
if self.resource != bucket_ref.resource_def() {
return false;
Expand Down
1 change: 1 addition & 0 deletions 1-exchanges/hareswap/src/transporter/decoder.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use sbor::{Decoder, DecodeError, TypeId};

/// A data structure that can be decoded from a byte array using SBOR (but not automatically derived by blueprint! macro)
/// this is for when the macro creates conflicting code, such as the Decode traits for sbor and NonFungible
pub trait PrivateDecode: Sized + TypeId {
#[inline]
fn decode(decoder: &mut Decoder) -> Result<Self, DecodeError> {
Expand Down
10 changes: 8 additions & 2 deletions 1-exchanges/hareswap/src/transporter/voucher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use sbor::{Decode, Decoder, DecodeError, Describe, Encode, describe::Type, TypeI

use super::decoder::*;

#[derive(TypeId, Encode, Decode, Describe)]
#[derive(PartialEq, Eq, Debug, TypeId, Encode, Decode, Describe)]
pub struct PassThruNFD {
immutable_data: Vec<u8>,
mutable_data: Vec<u8>,
Expand Down Expand Up @@ -52,15 +52,21 @@ impl NonFungibleData for PassThruNFD {

// make the Voucher not Decode-able so it can't be (accidentally) created other than from SealedVoucher (with sig check)

#[derive(TypeId, Describe, Encode)]
#[derive(PartialEq, Eq, Debug, TypeId, Describe, Encode)]
pub struct Voucher {
pub resource_def: ResourceDef,
pub key: Option<NonFungibleKey>,
pub nfd: PassThruNFD
}

impl PrivateDecode for Voucher {
// based on the derive Decode implementation in sbor-derive:src/decode.rs
fn decode_value(decoder: &mut Decoder) -> Result<Self, DecodeError> {
let index = decoder.read_u8()?;
if index != ::sbor::type_id::FIELDS_TYPE_NAMED {
return Err(::sbor::DecodeError::InvalidIndex(index));
}
decoder.check_len(3)?;
let resource_def = ResourceDef::decode(decoder)?;
let key = Option::<NonFungibleKey>::decode(decoder)?;
let nfd = <PassThruNFD as sbor::Decode>::decode(decoder)?; // cannot derive Decode for Voucher because the decode method is implemented for both NonFungibleData and Decode traits. Disambiguate here
Expand Down
5 changes: 3 additions & 2 deletions 1-exchanges/hareswap/testing/setup.sh
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,10 @@ CALL_FUNCTION Address("$PACKAGE") "Maker" "instantiate" $pubkey_arg None Address
EOF
rtmc --output maker_setup.rtmc maker_setup.rtm
resim run --trace maker_setup.rtm > maker_setup.trace 2>&1
# annoying to get the return values when using resim instead of Rust APIs against the ledger...
MAKER_COMPONENT=$(tail -n1 maker_setup.trace | cut -d' ' -f3)
rm maker_setup.trace
VOUCHER_ADDRESS=$(grep "INFO.*tokenized order resource address:" maker_setup.trace | cut -d':' -f2)
#rm maker_setup.trace

# switch to taker
resim set-default-account $ACCOUNT1 $ACCOUNT1_PUBKEY
Expand All @@ -72,7 +74,6 @@ $HARE request-for-quote partial_order.txt $TAKER_AMOUNT $T $M $TAKER_AUTH
# simulate send to maker
# maker decide on price and sign order
MAKER_AMOUNT=200
# TODO get VOUCHER_ADDRESS or don't pass it along let the maker look it up
$HARE make-signed-order partial_order.txt $MAKER_AMOUNT $MAKER_COMPONENT $VOUCHER_ADDRESS $MAKER_OFFLINE_KEY_PRI > signed_order.txt
SIGNED_ORDER=$(cat signed_order.txt)

Expand Down

0 comments on commit 010a54b

Please sign in to comment.