// CHICP Future: a time lock for the creator's future-programs bag. // // Rules, fixed at install and unchangeable once the canister has no controllers: // * Nothing leaves before the schedule starts. // * The schedule starts `delay` after CHICP lists on ICPSwap. The canister checks the Soon market // once a day and records the first time it reports the token as Graduated. If that never shows // up (listing never happens, or Soon's interface changes), the schedule starts at `fallbackStart` // instead, so the tokens can never be stuck. // * Then `tranches` equal releases, one every `interval`. Each sends the remaining balance divided // by the releases left, so the last one empties the lock (and late deposits are spread too). // * The only destination is `beneficiary` (the public Coop Fund). There is no other way out. // Anyone may call `release()`; a daily timer calls it too. Anyone can top up cycles. import Principal "mo:base/Principal"; import Time "mo:base/Time"; import Timer "mo:base/Timer"; import Int "mo:base/Int"; import Nat "mo:base/Nat"; import Nat64 "mo:base/Nat64"; import Cycles "mo:base/ExperimentalCycles"; import Error "mo:base/Error"; import Array "mo:base/Array"; persistent actor class FutureLock(init : { ledger : Principal; // CHICP ICRC-1 ledger market : Principal; // Soon market canister (reports the Graduated phase) beneficiary : Principal; // the only place tokens can go: the Coop Fund delaySecs : Nat; // listing → first release intervalSecs : Nat; // between releases tranches : Nat; // number of releases fallbackStartNs : Int; // schedule start if listing is never seen pollSecs : Nat; // how often to check the market / try a release }) = self { type Account = { owner : Principal; subaccount : ?Blob }; type TransferErr = { #BadFee : { expected_fee : Nat }; #BadBurn : { min_burn_amount : Nat }; #InsufficientFunds : { balance : Nat }; #TooOld; #CreatedInFuture : { ledger_time : Nat64 }; #Duplicate : { duplicate_of : Nat }; #TemporarilyUnavailable; #GenericError : { error_code : Nat; message : Text }; }; type Ledger = actor { icrc1_balance_of : shared query Account -> async Nat; icrc1_fee : shared query () -> async Nat; icrc1_transfer : shared { to : Account; fee : ?Nat; memo : ?Blob; from_subaccount : ?Blob; created_at_time : ?Nat64; amount : Nat } -> async { #Ok : Nat; #Err : TransferErr }; }; // Only the fields this lock needs from Soon's market info. type Phase = { #Trading; #Graduating : {}; #Graduated : { pool : Principal } }; type Market = actor { info : shared query () -> async { phase : Phase } }; let cfg = init; var listedAtNs : ?Int = null; // first time the market was seen Graduated var done : Nat = 0; // releases sent var released : Nat = 0; // e8s sent to the beneficiary var log : [(Int, Nat, Nat)] = []; // (time, e8s, ledger block) var lastCheckNs : Int = 0; var lastError : Text = ""; transient var busy = false; let SEC : Int = 1_000_000_000; func ledger() : Ledger { actor (Principal.toText(cfg.ledger)) }; func startNs() : Int { switch (listedAtNs) { case (?t) t + cfg.delaySecs * SEC; case null cfg.fallbackStartNs; }; }; // releases that are due by `now` func due(now : Int) : Nat { let s = startNs(); if (now < s) return 0; Nat.min(cfg.tranches, Int.abs((now - s) / (cfg.intervalSecs * SEC)) + 1); }; func checkListing() : async () { if (listedAtNs != null) return; // a fallback start already under way is final: a listing seen later doesn't restart the clock if (Time.now() >= cfg.fallbackStartNs) return; try { let m : Market = actor (Principal.toText(cfg.market)); switch ((await m.info()).phase) { case (#Graduated _) listedAtNs := ?Time.now(); case _ {} }; } catch (e) { lastError := "market: " # Error.message(e) }; }; // Send every release that is due. Safe to call any time, by anyone. public func release() : async { #ok : Nat; #err : Text } { if (busy) return #err("busy"); busy := true; await checkListing(); lastCheckNs := Time.now(); var sent = 0; try { while (done < due(Time.now())) { let L = ledger(); let fee = await L.icrc1_fee(); let bal = await L.icrc1_balance_of({ owner = Principal.fromActor(self); subaccount = null }); let left = cfg.tranches - done; let share = if (left <= 1) bal else bal / left; if (share <= fee) { done += 1 } else { switch (await L.icrc1_transfer({ to = { owner = cfg.beneficiary; subaccount = null }; fee = ?fee; memo = null; from_subaccount = null; created_at_time = null; amount = share - fee })) { case (#Ok b) { done += 1; released += share - fee; sent += 1; log := Array.append([(Time.now(), share - fee, b)], log) }; case (#Err e) { lastError := "transfer: " # debug_show e; busy := false; return #err(lastError) }; }; }; }; } catch (e) { lastError := "ledger: " # Error.message(e); busy := false; return #err(lastError) }; busy := false; #ok(sent); }; public query func status() : async { beneficiary : Principal; ledger : Principal; market : Principal; listedAtNs : ?Int; fallbackStartNs : Int; startNs : Int; nextNs : ?Int; delaySecs : Nat; intervalSecs : Nat; tranches : Nat; done : Nat; released : Nat; lastCheckNs : Int; lastError : Text; cycles : Nat; } { let s = startNs(); { beneficiary = cfg.beneficiary; ledger = cfg.ledger; market = cfg.market; listedAtNs; fallbackStartNs = cfg.fallbackStartNs; startNs = s; nextNs = if (done >= cfg.tranches) null else ?(s + done * cfg.intervalSecs * SEC); delaySecs = cfg.delaySecs; intervalSecs = cfg.intervalSecs; tranches = cfg.tranches; done; released; lastCheckNs; lastError; cycles = Cycles.balance(); }; }; public query func releases() : async [(Int, Nat, Nat)] { log }; transient let _tick = Timer.recurringTimer(#seconds (cfg.pollSecs), func() : async () { ignore await release() }); };