Skip to content

Commit

Permalink
perf: mainnet deployad branch contains Blob [Nat8] issues
Browse files Browse the repository at this point in the history
  • Loading branch information
ahdrahees committed Apr 22, 2024
1 parent d56a6bf commit 48cb8c5
Show file tree
Hide file tree
Showing 9 changed files with 244 additions and 187 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ vite.config.js.timestamp-*
vite.config.ts.timestamp-*
.dfx
deps
.mops
.mops
canister_ids.json
7 changes: 4 additions & 3 deletions dfx.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
"type": "motoko",
"dependencies": [
"icp_ledger",
"cycles_ledger",
"cycle_reserve",
"cycle_minting_canister",
"usdx_ledger",
Expand All @@ -55,8 +54,9 @@
},
"icp_ledger": {
"type": "custom",
"candid": "https://raw.githubusercontent.com/dfinity/ic/206a50f01306b398eb7e25988c7925fcd0e2caa4/rs/rosetta-api/icp_ledger/ledger.did",
"wasm": "https://download.dfinity.systems/ic/206a50f01306b398eb7e25988c7925fcd0e2caa4/canisters/ledger-canister.wasm.gz",
"candid": "https://raw.githubusercontent.com/dfinity/ic/33dd2ef2184a64c00e64ff0412e7378d46507005/rs/rosetta-api/icp_ledger/ledger.did",
"wasm": "https://download.dfinity.systems/ic/33dd2ef2184a64c00e64ff0412e7378d46507005/canisters/ledger-canister.wasm.gz",
"specified_id": "ryjl3-tyaaa-aaaaa-aaaba-cai",
"remote": {
"id": {
"ic": "ryjl3-tyaaa-aaaaa-aaaba-cai"
Expand All @@ -67,6 +67,7 @@
"type": "custom",
"candid": "https://raw.githubusercontent.com/dfinity/ic/2e921c9adfc71f3edc96a9eb5d85fc742e7d8a9f/rs/nns/cmc/cmc.did",
"wasm": "https://download.dfinity.systems/ic/2e921c9adfc71f3edc96a9eb5d85fc742e7d8a9f/canisters/cycles-minting-canister.wasm.gz",
"specified_id": "rkp4c-7iaaa-aaaaa-aaaca-cai",
"remote": {
"id": {
"ic": "rkp4c-7iaaa-aaaaa-aaaca-cai"
Expand Down
2 changes: 1 addition & 1 deletion mops.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[dependencies]
base = "0.10.4"
base = "0.11.1"
"encoding.mo" = "https://github.com/aviate-labs/encoding.mo#master@2711d18727e954b11afc0d37945608512b5fbce2"
account-identifier = "1.0.2"
map = "9.0.1"
Expand Down
34 changes: 34 additions & 0 deletions scripts/calculate-wasm-hash.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/bin/bash

dfx build cycle_reserve --ic
dfx build cycle_pool --ic
dfx build stablecoin_minter --ic

echo "######################## IC Mainnet WASM Hash ###########################"
# Define paths to each wasm file
cycle_reserve_path=".dfx/ic/canisters/cycle_reserve/cycle_reserve.wasm"
cycle_pool_path=".dfx/ic/canisters/cycle_pool/cycle_pool.wasm"
stablecoin_minter_path=".dfx/ic/canisters/stablecoin_minter/stablecoin_minter.wasm"


# Loop through each wasm file path
for wasm_file_path in "$cycle_reserve_path" "$cycle_pool_path" "$stablecoin_minter_path"; do
# Extract filename from path (optional)
filename=$(basename "$wasm_file_path")

# Check if the file exists
if [ ! -f "$wasm_file_path" ]; then
echo "Error: File '$wasm_file_path' does not exist."
continue # Skip to the next iteration if file is missing
fi

# Calculate the SHA256 hash using shasum
sha256_hash=$(shasum -a 256 "$wasm_file_path" | awk '{print $1}')

# Print the hash with filename (if extracted)
if [ -n "$filename" ]; then
echo "SHA256 hash of '$filename' : $sha256_hash"
else
echo "SHA256 hash of '$wasm_file_path': $sha256_hash"
fi
done
16 changes: 8 additions & 8 deletions scripts/deploy-local.sh
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ fi
export MINTER_ACCOUNT_ID=$(dfx ledger account-id --identity minter)
export DEFAULT_ACCOUNT_ID=$(dfx ledger account-id --identity default)

dfx deploy --specified-id ryjl3-tyaaa-aaaaa-aaaba-cai icp_ledger --argument "
dfx deploy icp_ledger --specified-id ryjl3-tyaaa-aaaaa-aaaba-cai --argument "
(variant {
Init = record {
minting_account = \"$MINTER_ACCOUNT_ID\";
Expand Down Expand Up @@ -58,22 +58,22 @@ dfx deploy cycles_ledger --specified-id um5iw-rqaaa-aaaaq-qaaba-cai --argument '
variant { Init= record { max_blocks_per_request = 1; index_id = null }}
)'

#Deploy Backend Canister
dfx deploy cycle_reserve --specified-id br5f7-7uaaa-aaaaa-qaaca-cai --with-cycles 1_000_000
#Deploy Reserve Canister
dfx deploy cycle_reserve --with-cycles 1_000_000

# Creating Local USDx Ledger before deploying stablecoin_minter (stablecoin_minter is a dependency of usdx_ledger)
dfx canister create usdx_ledger --specified-id bd3sg-teaaa-aaaaa-qaaba-cai
dfx canister create usdx_ledger --specified-id irorr-5aaaa-aaaak-qddsq-cai

# Creating Local stablecoin_minter , root_canister before deploying usdx_ledger (These are minteraccount and archivecontroller for usdx_ledger)
dfx canister create stablecoin_minter --specified-id be2us-64aaa-aaaaa-qaabq-cai
dfx canister create root_canister --specified-id b77ix-eeaaa-aaaaa-qaada-cai
dfx canister create stablecoin_minter --specified-id iyn2n-liaaa-aaaak-qddta-cai
dfx canister create root_canister --specified-id iwpxf-qyaaa-aaaak-qddsa-cai

# Deploy USDx Ledger Locally
./scripts/deploy-local-usdx.sh


dfx canister create cycle_pool --specified-id bw4dl-smaaa-aaaaa-qaacq-cai
dfx deploy cycle_pool --argument '(principal "bw4dl-smaaa-aaaaa-qaacq-cai")'
dfx canister create cycle_pool --specified-id i7m4z-gqaaa-aaaak-qddtq-cai
dfx deploy cycle_pool --argument '(principal "i7m4z-gqaaa-aaaak-qddtq-cai")'

dfx deploy stablecoin_minter

Expand Down
6 changes: 5 additions & 1 deletion src/backend/Utils.mo
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ module {
};
};

let subValue : SubValue = format(value);
let _subValue : SubValue = format(value);

return hmap;
};
Expand All @@ -136,4 +136,8 @@ module {
public func accountIdentifierDefault(id : Principal) : [Nat8] {
Blob.toArray(Account.accountIdentifier(id, Account.defaultSubaccount()));
};

public func accountIdentifierDefaultBlob(id : Principal) : Blob {
Account.accountIdentifier(id, Account.defaultSubaccount());
};
};
53 changes: 29 additions & 24 deletions src/backend/cycle-pool/main.mo
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import Principal "mo:base/Principal";
import Blob "mo:base/Blob";
import Utils "../Utils";

actor class CyclePool(cyclePoolCanisterId : Principal) {
actor CyclePool {
type Operation = { #Add; #Subtract : { amount : Nat } };
type ReserveResult = Result.Result<(), Text>;
type Time = Time.Time;
Expand All @@ -41,6 +41,7 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {
};
};

let cyclePoolCanisterId = Principal.fromText("i7m4z-gqaaa-aaaak-qddtq-cai");
private stable var xdrUsd : XdrUsd = { rate = 0; timestamp = 0 };

let failedToUpdateXdrUsdRate = Buffer.Buffer<UpdateXdrUsdRateError>(0);
Expand All @@ -49,7 +50,7 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {
stable let cyclesPoolTopUpFailed = StableBuffer.init<CyclePoolTopUpError>();

public func cycle_pool_receive() : async Nat {
Cycles.accept(Cycles.available());
Cycles.accept<system>(Cycles.available());
// Emit event cycles received
};

Expand All @@ -67,9 +68,9 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {
};

system func postupgrade() : () {
restartTotalSupplyTimer();
restartXrcFetchTimer();
restartReserveAdjustTimer();
restartTotalSupplyTimer<system>();
restartXrcFetchTimer<system>();
restartReserveAdjustTimer<system>();
};

//////////// Fetch XDR/USD rate from XRC and update xdrUsd //////////////
Expand All @@ -88,7 +89,7 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {
if (expectedCyclesInReserveWithNewRate > expectedCyclesInReserveWithPreviousRate) {
let cycleInNeedToMaintainPeg : Nat = expectedCyclesInReserveWithNewRate - expectedCyclesInReserveWithPreviousRate;
let cyclePoolBalance = Cycles.balance();
let balanceMinusAdditionalforComputaion : Int = cyclePoolBalance - 10_000_000_000_000; // Ten trillion cycles as a buffer
let balanceMinusAdditionalforComputaion : Int = cyclePoolBalance - 2_000_000_000_000; // Ten trillion cycles as a buffer

if (balanceMinusAdditionalforComputaion < cycleInNeedToMaintainPeg) {
let cyclesToMint = cycleInNeedToMaintainPeg - balanceMinusAdditionalforComputaion;
Expand Down Expand Up @@ -117,7 +118,7 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {
amount = { e8s = icpAmountE8s };
fee = { e8s = 10_000 };
from_subaccount = null;
to = Blob.toArray(accountIdentifierCMC);
to = accountIdentifierCMC;
created_at_time = ?{ timestamp_nanos = Nat64.fromIntWrap(Time.now()) };
};

Expand All @@ -136,7 +137,7 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {
canister_id = cyclePoolCanisterId;
};
let notifyTopUpResult = await CMC.notify_top_up(notifyTopUpArg);
let mintedCycles : Nat = switch (notifyTopUpResult) {
let _mintedCycles : Nat = switch (notifyTopUpResult) {
case (#Ok(value)) { value };
case (#Err(error)) {
StableBuffer.add(cyclesPoolTopUpFailed, { error_time = Time.now(); error = #CMC error });
Expand All @@ -150,8 +151,8 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {
let quote_asset = { symbol = "USD"; class_ = #FiatCurrency };
let timestamp = null;

Cycles.add(10_000_000_000);
let getExchangeRateResult = await XRC.get_exchange_rate({
Cycles.add<system>(10_000_000_000);
let _getExchangeRateResult = await XRC.get_exchange_rate({
base_asset;
quote_asset;
timestamp;
Expand Down Expand Up @@ -195,25 +196,25 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {
let oneHourInNanoSec = 3600_000_000_000;
let nextFetchTime = oneHourInNanoSec - (Time.now() % oneHourInNanoSec);

Timer.setTimer(
Timer.setTimer<system>(
#nanoseconds(Int.abs nextFetchTime),
func() : async () {
xrcFetchTimerId := Timer.recurringTimer(#seconds 3600, timerUpdateXdrUsdRate);
xrcFetchTimerId := Timer.recurringTimer<system>(#seconds 3600, timerUpdateXdrUsdRate);
await timerUpdateXdrUsdRate();
}
);

};

private func restartXrcFetchTimer() : () {
private func restartXrcFetchTimer<system>() : () {
// let currentTime = Time.now();
let oneHourInNanoSec = 3600_000_000_000;
let nextFetchTime = oneHourInNanoSec - (Time.now() % oneHourInNanoSec);

xrcFetchTimerId := Timer.setTimer(
xrcFetchTimerId := Timer.setTimer<system>(
#nanoseconds(Int.abs nextFetchTime),
func() : async () {
xrcFetchTimerId := Timer.recurringTimer(#seconds 3600, timerUpdateXdrUsdRate);
xrcFetchTimerId := Timer.recurringTimer<system>(#seconds 3600, timerUpdateXdrUsdRate);
await timerUpdateXdrUsdRate();
}
);
Expand All @@ -231,11 +232,11 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {

stable var totalSupplyTimerId : TimerId = 0;
totalSupplyTimerId := do {
Timer.recurringTimer(#seconds 1, fetchTotalSupply);
Timer.recurringTimer<system>(#seconds 1, fetchTotalSupply);
};

private func restartTotalSupplyTimer() : () {
totalSupplyTimerId := Timer.recurringTimer(#seconds 1, fetchTotalSupply);
private func restartTotalSupplyTimer<system>() : () {
totalSupplyTimerId := Timer.recurringTimer<system>(#seconds 1, fetchTotalSupply);
};

private func stopTotalSupplyTimer() : () {
Expand All @@ -248,22 +249,26 @@ actor class CyclePool(cyclePoolCanisterId : Principal) {
let expectedCyclesInReserve__ : Float = usdxTotalSupply * (1 / xdrUsd.rate) * 1_000_000_000_000;
let expectedCyclesInReserve = Int.abs(Float.toInt(expectedCyclesInReserve__));

// 8,511,097,318,335 = 11.33606873*(1/1.331916239)*1,000,000,000,000
// 8,511,097,318,335 > 8_499_224_797_270

if (expectedCyclesInReserve > reserveCurrentCycles) {
Cycles.add(expectedCyclesInReserve - reserveCurrentCycles);
let result = await CycleReserve.cycle_reserve_adjust(#Add);
// 11,872,521,065
Cycles.add<system>(expectedCyclesInReserve - reserveCurrentCycles);
let _result = await CycleReserve.cycle_reserve_adjust(#Add);
} else if (expectedCyclesInReserve < reserveCurrentCycles) {
let amount : Nat = reserveCurrentCycles - expectedCyclesInReserve;
let result = await CycleReserve.cycle_reserve_adjust(#Subtract { amount });
let _result = await CycleReserve.cycle_reserve_adjust(#Subtract { amount });
};
};

stable var reserveAdjustTimerId : TimerId = 0;
reserveAdjustTimerId := do {
Timer.recurringTimer(#seconds 1, adjustCycleReserve);
Timer.recurringTimer<system>(#seconds 1, adjustCycleReserve);
};

private func restartReserveAdjustTimer() : () {
reserveAdjustTimerId := Timer.recurringTimer(#seconds 1, adjustCycleReserve);
private func restartReserveAdjustTimer<system>() : () {
reserveAdjustTimerId := Timer.recurringTimer<system>(#seconds 1, adjustCycleReserve);
};
private func stopReserveAdjustTimer() : () {
Timer.cancelTimer(reserveAdjustTimerId);
Expand Down
23 changes: 12 additions & 11 deletions src/backend/cycle-reserve/main.mo
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Principal "mo:base/Principal";
import Cycles "mo:base/ExperimentalCycles";
import Debug "mo:base/Debug";

import Result "mo:base/Result";
import Text "mo:base/Text";

Expand All @@ -15,44 +15,45 @@ actor {

let cyclePool : actor {
cycle_pool_receive : shared () -> async Nat;
} = actor ("bw4dl-smaaa-aaaaa-qaacq-cai");
} = actor ("i7m4z-gqaaa-aaaak-qddtq-cai");

let stablecoinMinter : actor {} = actor ("bd3sg-teaaa-aaaaa-qaaba-cai");
let stablecoinMinter : Principal = Principal.fromText("iyn2n-liaaa-aaaak-qddta-cai");

// Ledger canister or Cycle minting canister will call this method to add cycles to the reserve
public shared ({ caller }) func cycle_reserve_receive() : async Result {
if (caller != Principal.fromActor(stablecoinMinter)) {
if (caller != stablecoinMinter) {
#err("Unauthorized caller");
} else {
let acceptCycles = Cycles.accept(Cycles.available());
// accept Cycles
let _acceptCycles = Cycles.accept<system>(Cycles.available());
#ok();
};

};

// Pool canister will call this method to adjust the reserve
public shared ({ caller }) func cycle_reserve_adjust(operaion : Operation) : async Result {
if (caller != Principal.fromActor(cyclePool)) {
if (caller != Principal.fromText("i7m4z-gqaaa-aaaak-qddtq-cai")) {
return #err("Unauthorized caller");
};

switch (operaion) {
case (#Add) {
let acceptCycles = Cycles.accept(Cycles.available());
let _acceptCycles = Cycles.accept<system>(Cycles.available());
#ok();
};
case (#Subtract { amount : Nat }) {
Cycles.add(amount);
let subtractedCycles = await cyclePool.cycle_pool_receive();
Cycles.add<system>(amount);
let _subtractedCycles = await cyclePool.cycle_pool_receive();
#ok();
};
};

};

// Get current cycle reserve balance
public shared func cycle_reserve_balance() : async Nat {
let balance = Cycles.balance();
public shared query func cycle_reserve_balance() : async Nat {
Cycles.balance();
};

};
Loading

0 comments on commit 48cb8c5

Please sign in to comment.