├── cf-swap.png ├── cf-priceweighted.png ├── cf-shareweighted.png ├── .gitignore ├── dfx.json ├── lib ├── DRC205.mo ├── DRC207.mo ├── SwapRecord.mo ├── CRC32.mo ├── Binary.mo ├── Hex.mo ├── Types.mo ├── SHA224.mo ├── Bloom.mo ├── BASE32.mo ├── CF.mo └── Tools.mo ├── sys ├── Ledger2.mo └── CyclesWallet.mo ├── DRC205Bucket.mo ├── CyclesMarket.did ├── DRC205Proxy.mo ├── README中文.md ├── README.md └── LICENSE /cf-swap.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iclighthouse/Cycles.Finance/HEAD/cf-swap.png -------------------------------------------------------------------------------- /cf-priceweighted.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iclighthouse/Cycles.Finance/HEAD/cf-priceweighted.png -------------------------------------------------------------------------------- /cf-shareweighted.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iclighthouse/Cycles.Finance/HEAD/cf-shareweighted.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | dist-ssr 3 | *.local 4 | .dfx 5 | .vessel 6 | .config 7 | .tmp 8 | 9 | # Various IDEs and Editors 10 | .vscode/ 11 | .idea/ 12 | .history 13 | **/*~ 14 | 15 | # frontend code 16 | node_modules/ 17 | dist/ 18 | 19 | canister_ids.json 20 | icp-cycles.numbers 21 | CyclesMarket1204.mo 22 | CyclesMarket1206.mo 23 | Types1204.mo 24 | Types1206.mo 25 | .dfx/ -------------------------------------------------------------------------------- /dfx.json: -------------------------------------------------------------------------------- 1 | { 2 | "canisters": { 3 | "CyclesMarket": { 4 | "main": "./CyclesMarket.mo", 5 | "type": "motoko" 6 | }, 7 | "CyclesMarketTest": { 8 | "main": "./CyclesMarket.mo", 9 | "type": "motoko" 10 | }, 11 | "DRC205": { 12 | "main": "./DRC205Proxy.mo", 13 | "type": "motoko" 14 | } 15 | }, 16 | "defaults": { 17 | "build": { 18 | "args": "--compacting-gc", 19 | "packtool": "" 20 | } 21 | }, 22 | "networks": { 23 | "ic": { 24 | "providers": ["https://ic0.app"], 25 | "type": "persistent" 26 | }, 27 | "local": { 28 | "bind": "0.0.0.0:8000", 29 | "type": "ephemeral" 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /lib/DRC205.mo: -------------------------------------------------------------------------------- 1 | /** 2 | * Module : DRC205.mo 3 | * Canister : 6ylab-kiaaa-aaaak-aacga-cai 4 | */ 5 | import Principal "mo:base/Principal"; 6 | import Array "mo:base/Array"; 7 | import Nat32 "mo:base/Nat32"; 8 | import Blob "mo:base/Blob"; 9 | import Time "mo:base/Time"; 10 | import Binary "Binary"; 11 | import SHA224 "SHA224"; 12 | 13 | module { 14 | public type Address = Text; 15 | public type Txid = Blob; 16 | public type AccountId = Blob; 17 | public type CyclesWallet = Principal; 18 | public type Nonce = Nat; 19 | public type Data = Blob; 20 | public type Shares = Nat; 21 | public type TokenType = { 22 | #Cycles; 23 | #Icp; 24 | #Token: Principal; 25 | }; 26 | public type OperationType = { 27 | #AddLiquidity; 28 | #RemoveLiquidity; 29 | #Claim; 30 | #Swap; 31 | }; 32 | public type BalanceChange = { 33 | #DebitRecord: Nat; 34 | #CreditRecord: Nat; 35 | #NoChange; 36 | }; 37 | public type ShareChange = { 38 | #Mint: Shares; 39 | #Burn: Shares; 40 | #NoChange; 41 | }; 42 | public type TxnRecord = { 43 | txid: Txid; 44 | msgCaller: ?Principal; 45 | caller: AccountId; 46 | operation: OperationType; 47 | account: AccountId; 48 | cyclesWallet: ?CyclesWallet; 49 | token0: TokenType; 50 | token1: TokenType; 51 | token0Value: BalanceChange; 52 | token1Value: BalanceChange; 53 | fee: {token0Fee: Nat; token1Fee: Nat; }; 54 | shares: ShareChange; 55 | time: Time.Time; 56 | index: Nat; 57 | nonce: Nonce; 58 | orderType: { #AMM; #OrderBook; }; 59 | details: [{counterparty: Txid; token0Value: BalanceChange; token1Value: BalanceChange;}]; 60 | data: ?Data; 61 | }; 62 | 63 | public type Self = actor { 64 | version: shared query () -> async Nat8; 65 | fee : shared query () -> async (cycles: Nat); //cycles 66 | store : shared (_txn: TxnRecord) -> async (); 67 | storeBytes: shared (_txid: Txid, _data: [Nat8]) -> async (); 68 | bucket : shared query (_canister: Principal, _txid: Txid, _step: Nat, _version: ?Nat8) -> async (bucket: ?Principal); 69 | }; 70 | public type Bucket = actor { 71 | txnBytes: shared query (_app: Principal, _txid: Txid) -> async ?([Nat8], Time.Time); 72 | txn: shared query (_app: Principal, _txid: Txid) -> async ?(TxnRecord, Time.Time); 73 | }; 74 | public func generateTxid(_app: Principal, _caller: AccountId, _nonce: Nat): Txid{ 75 | let appType: [Nat8] = [83:Nat8, 87, 65, 80]; //SWAP 76 | let canister: [Nat8] = Blob.toArray(Principal.toBlob(_app)); 77 | let caller: [Nat8] = Blob.toArray(_caller); 78 | let nonce: [Nat8] = Binary.BigEndian.fromNat32(Nat32.fromNat(_nonce)); 79 | let txInfo = Array.append(Array.append(Array.append(appType, canister), caller), nonce); 80 | let h224: [Nat8] = SHA224.sha224(txInfo); 81 | return Blob.fromArray(Array.append(nonce, h224)); 82 | }; 83 | } 84 | -------------------------------------------------------------------------------- /lib/DRC207.mo: -------------------------------------------------------------------------------- 1 | /** 2 | * Module : DRC207.mo 3 | * Author : ICLighthouse Team 4 | * License : Apache License 2.0 5 | * Stability : Experimental 6 | * Github : https://github.com/iclighthouse/DRC_standards/ 7 | */ 8 | module { 9 | public type canister_id = Principal; 10 | 11 | public type definite_canister_settings = { 12 | freezing_threshold : Nat; 13 | controllers : [Principal]; 14 | memory_allocation : Nat; 15 | compute_allocation : Nat; 16 | }; 17 | 18 | public type canister_status = { 19 | status : { #stopped; #stopping; #running }; 20 | memory_size : Nat; 21 | cycles : Nat; 22 | settings : definite_canister_settings; 23 | module_hash : ?[Nat8]; 24 | }; 25 | 26 | /// monitorable_by_self: 27 | /// If `true` is entered, it's required to add the canister's own canister_id to its controllers. 28 | /// monitorable_by_blackhole: 29 | /// `monitorable_by_blackhole.canister_id`(principal) means that a blackhole is specified to read the canister status, For example `7hdtw-jqaaa-aaaak-aaccq-cai`. 30 | /// If monitorable_by_blackhole.canister_id is entered, it's is required to add the blackhole's canister_id to the canister's controllers. 31 | /// cycles_receivable: 32 | /// If `true` is entered, It means that the canister has implemented wallet_receive(). 33 | /// timer: 34 | /// the `timer.interval_seconds` should be greater than or equal to 5 minutes (300 seconds), 35 | /// timer.interval_seconds=`0` means that timer_tick() will be executed once per heartbeat by the Monitor, 36 | /// Notes: Timer_tick() will be executed once the eventType `TimerTick` has been subscribed to in the Monitor. There is no guarantee that timer_tick() will be triggered on time. 37 | public type DRC207Support = { 38 | monitorable_by_self: Bool; 39 | monitorable_by_blackhole: { allowed: Bool; canister_id: ?Principal; }; 40 | cycles_receivable: Bool; 41 | timer: { enable: Bool; interval_seconds: ?Nat; }; 42 | }; 43 | 44 | public type IC = actor { 45 | canister_status : { canister_id : canister_id } -> async canister_status; 46 | }; 47 | 48 | public type Self = actor { 49 | drc207 : shared query () -> async DRC207Support; 50 | canister_status : shared () -> async canister_status; 51 | timer_tick : shared () -> async (); 52 | wallet_receive : shared () -> async (); 53 | }; 54 | 55 | } 56 | /* Implementation example: 57 | 58 | /// DRC207 support 59 | public func drc207() : async DRC207.DRC207Support{ 60 | return { 61 | monitorable_by_self = true; 62 | monitorable_by_blackhole = { allowed = true; canister_id = ?Principal.fromText("7hdtw-jqaaa-aaaak-aaccq-cai"); }; 63 | cycles_receivable = true; 64 | timer = { enable = true; interval_seconds = ?300; }; // 5 minutes 65 | }; 66 | }; 67 | /// canister_status 68 | public func canister_status() : async DRC207.canister_status { 69 | let ic : DRC207.IC = actor("aaaaa-aa"); 70 | await ic.canister_status({ canister_id = Principal.fromActor(this) }); 71 | }; 72 | /// receive cycles 73 | public func wallet_receive(): async (){ 74 | let amout = Cycles.available(); 75 | let accepted = Cycles.accept(amout); 76 | }; 77 | /// timer tick 78 | public func timer_tick(): async (){ 79 | // do something 80 | }; 81 | */ 82 | -------------------------------------------------------------------------------- /lib/SwapRecord.mo: -------------------------------------------------------------------------------- 1 | /** 2 | * Module : SwapRecord.mo 3 | * Author : ICLight.house Team 4 | * Stability : Experimental 5 | */ 6 | import Array "mo:base/Array"; 7 | import Binary "Binary"; 8 | import Blob "mo:base/Blob"; 9 | import Nat "mo:base/Nat"; 10 | import Nat32 "mo:base/Nat32"; 11 | import Nat64 "mo:base/Nat64"; 12 | import Nat8 "mo:base/Nat8"; 13 | import Int64 "mo:base/Int64"; 14 | import Option "mo:base/Option"; 15 | import Prim "mo:⛔"; 16 | import Principal "mo:base/Principal"; 17 | import Text "mo:base/Text"; 18 | import Types "DRC205"; 19 | import SHA224 "SHA224"; 20 | 21 | module { 22 | public type Address = Types.Address; 23 | public type AccountId = Types.AccountId; 24 | public type Txid = Types.Txid; 25 | public type CyclesWallet = Types.CyclesWallet; 26 | public type Shares = Types.Shares; 27 | public type Nonce = Types.Nonce; 28 | public type Data = Types.Data; 29 | public type TokenType = Types.TokenType; 30 | public type OperationType = Types.OperationType; 31 | public type BalanceChange = Types.BalanceChange; 32 | public type ShareChange = Types.ShareChange; 33 | public type TxnRecord = Types.TxnRecord; 34 | public type Bucket = Principal; 35 | public type BucketInfo = { 36 | cycles: Nat; 37 | memory: Nat; 38 | heap: Nat; 39 | stableMemory: Nat32; 40 | count: Nat; 41 | }; 42 | public type AppId = Principal; 43 | public type AppInfo = { 44 | lastIndex: Nat; 45 | lastTxid: Txid; 46 | count: Nat; 47 | }; 48 | public type AppCertification = { 49 | level: Nat; // 1~3 50 | moduleHash: [Nat8]; 51 | certifiedBy: Principal; 52 | }; 53 | public type Sid = Blob; 54 | 55 | /* TxnRecord Encode Data Structure 56 | * ............. 57 | */ 58 | 59 | public let Nat64Max: Nat = 0xFFFFFFFFFFFFFFFF; //2**64 - 1; 60 | public func slice(a: [T], from: Nat, to: ?Nat): [T]{ 61 | let len = a.size(); 62 | if (len == 0) { return []; }; 63 | var to_: Nat = Option.get(to, Nat.sub(len, 1)); 64 | if (len <= to_){ to_ := len - 1; }; 65 | var na: [T] = []; 66 | var i: Nat = from; 67 | while ( i <= to_ ){ 68 | na := Array.append(na, Array.make(a[i])); 69 | i += 1; 70 | }; 71 | return na; 72 | }; 73 | //version: 1bytes 74 | private let _data: [Nat8] = [1]; 75 | //amount: 9bytes(8bytes+1decimals) 76 | private func _amountEncode(_value: Nat) : [Nat8]{ 77 | var value = _value; 78 | var decimals: Nat8 = 0; 79 | while (value > Nat64Max){ 80 | value /= 10; 81 | decimals += 1; 82 | }; 83 | return Array.append(Binary.BigEndian.fromNat64(Nat64.fromNat(value)), [decimals]); 84 | }; 85 | private func _amountDecode(_bytes: [Nat8]) : Nat{ 86 | if (_bytes.size() == 0) { return 0; }; 87 | let value = Nat64.toNat(Binary.BigEndian.toNat64(slice(_bytes, 0, ?7))); 88 | let decimals = Nat8.toNat(_bytes[8]); 89 | return value * (10 ** decimals); 90 | }; 91 | private func _principalFormat(_p: Text) : Text{ 92 | var i: Nat = 0; 93 | var t: Text = ""; 94 | for (c in _p.chars()){ 95 | if (i > 0 and i % 5 == 0) { t #= "-"; }; 96 | t #= Text.fromChar(c); 97 | i += 1; 98 | }; 99 | return t; 100 | }; 101 | 102 | public func generateSid(app: AppId, txid: Txid) : Blob{ 103 | let h224 = SHA224.sha224(Array.append(Blob.toArray(Principal.toBlob(app)), Blob.toArray(txid))); 104 | return Blob.fromArray(h224); 105 | }; 106 | 107 | // public func encode(txn: TxnRecord) : [Nat8]{ 108 | // [] 109 | // }; 110 | 111 | // public func decode(data: [Nat8]) : TxnRecord{ 112 | // // 113 | // }; 114 | 115 | 116 | }; -------------------------------------------------------------------------------- /sys/Ledger2.mo: -------------------------------------------------------------------------------- 1 | module{ 2 | // Amount of ICP tokens, measured in 10^-8 of a token. 3 | public type ICP = { 4 | e8s : Nat64; 5 | }; 6 | 7 | // Number of nanoseconds from the UNIX epoch (00:00:00 UTC, Jan 1, 1970). 8 | public type Timestamp = { 9 | timestamp_nanos: Nat64; 10 | }; 11 | 12 | // AccountIdentifier is a 32-byte array. 13 | // The first 4 bytes is big-endian encoding of a CRC32 checksum of the last 28 bytes. 14 | public type AccountIdentifier = Blob; 15 | 16 | // Subaccount is an arbitrary 32-byte byte array. 17 | // Ledger uses subaccounts to compute the source address, which enables one 18 | // principal to control multiple ledger accounts. 19 | public type SubAccount = Blob; 20 | 21 | // Sequence number of a block produced by the ledger. 22 | public type BlockIndex = Nat64; 23 | 24 | // An arbitrary number associated with a transaction. 25 | // The caller can set it in a `transfer` call as a correlation identifier. 26 | public type Memo = Nat64; 27 | 28 | // Arguments for the `transfer` call. 29 | public type TransferArgs = { 30 | // Transaction memo. 31 | // See comments for the `Memo` type. 32 | memo: Memo; 33 | // The amount that the caller wants to transfer to the destination address. 34 | amount: ICP; 35 | // The amount that the caller pays for the transaction. 36 | // Must be 10000 e8s. 37 | fee: ICP; 38 | // The subaccount from which the caller wants to transfer funds. 39 | // If null, the ledger uses the default (all zeros) subaccount to compute the source address. 40 | // See comments for the `SubAccount` type. 41 | from_subaccount: ?SubAccount; 42 | // The destination account. 43 | // If the transfer is successful, the balance of this account increases by `amount`. 44 | to: AccountIdentifier; 45 | // The point in time when the caller created this request. 46 | // If null, the ledger uses current IC time as the timestamp. 47 | created_at_time: ?Timestamp; 48 | }; 49 | 50 | public type TransferError = { 51 | // The fee that the caller specified in the transfer request was not the one that the ledger expects. 52 | // The caller can change the transfer fee to the `expected_fee` and retry the request. 53 | #BadFee : { expected_fee : ICP; }; 54 | // The account specified by the caller doesn't have enough funds. 55 | #InsufficientFunds : { balance: ICP; }; 56 | // The request is too old. 57 | // The ledger only accepts requests created within a 24 hours window. 58 | // This is a non-recoverable error. 59 | #TxTooOld : { allowed_window_nanos: Nat64 }; 60 | // The caller specified `created_at_time` that is too far in future. 61 | // The caller can retry the request later. 62 | #TxCreatedInFuture; 63 | // The ledger has already executed the request. 64 | // `duplicate_of` field is equal to the index of the block containing the original transaction. 65 | #TxDuplicate : { duplicate_of: BlockIndex; }; 66 | }; 67 | 68 | public type TransferResult = { 69 | #Ok : BlockIndex; 70 | #Err : TransferError; 71 | }; 72 | 73 | // Arguments for the `account_balance` call. 74 | public type AccountBalanceArgs = { 75 | account: AccountIdentifier; 76 | }; 77 | 78 | public type Self = actor { 79 | // Transfers tokens from a subaccount of the caller to the destination address. 80 | // The source address is computed from the principal of the caller and the specified subaccount. 81 | // When successful, returns the index of the block containing the transaction. 82 | transfer : shared (TransferArgs) -> async (TransferResult); 83 | 84 | // Returns the amount of ICP on the specified account. 85 | account_balance : shared query (AccountBalanceArgs) -> async (ICP); 86 | }; 87 | } -------------------------------------------------------------------------------- /lib/CRC32.mo: -------------------------------------------------------------------------------- 1 | import Nat "mo:base/Nat"; 2 | import Nat8 "mo:base/Nat8"; 3 | import Nat32 "mo:base/Nat32"; 4 | 5 | module { 6 | private let tablecrc32 : [Nat32] = [ 7 | 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 8 | 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 9 | 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 10 | 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 11 | 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 12 | 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 13 | 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 14 | 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 15 | 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 16 | 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 17 | 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 18 | 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 19 | 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 20 | 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 21 | 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 22 | 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 23 | 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 24 | 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 25 | 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 26 | 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 27 | 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 28 | 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 29 | 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 30 | 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 31 | 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 32 | 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 33 | 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 34 | 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 35 | 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 36 | 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 37 | 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 38 | 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 39 | 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 40 | 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 41 | 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 42 | 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 43 | 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 44 | 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 45 | 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 46 | 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 47 | 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 48 | 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 49 | 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d 50 | ]; 51 | 52 | /// Returns the 4 bytes result of crc32-ieee 53 | public func crc32(data : [Nat8]) : [Nat8] { 54 | var crc : Nat32 = 4294967295; 55 | for (byte in data.vals()) { 56 | crc := (crc >> 8) ^ tablecrc32[Nat32.toNat((crc ^ Nat32.fromNat(Nat8.toNat(byte))) & 0xFF)]; 57 | }; 58 | crc := (crc ^ 0xFFFFFFFF) & 0xffffffff; 59 | return [ 60 | Nat8.fromNat(Nat32.toNat((crc >> 24) & 0xFF)), 61 | Nat8.fromNat(Nat32.toNat((crc >> 16) & 0xFF)), 62 | Nat8.fromNat(Nat32.toNat((crc >> 8) & 0xFF)), 63 | Nat8.fromNat(Nat32.toNat((crc) & 0xFF)) 64 | ]; 65 | }; 66 | }; 67 | -------------------------------------------------------------------------------- /lib/Binary.mo: -------------------------------------------------------------------------------- 1 | import Array "mo:base/Array"; 2 | import Nat8 "mo:base/Nat8"; 3 | import Nat16 "mo:base/Nat16"; 4 | import Nat32 "mo:base/Nat32"; 5 | import Nat64 "mo:base/Nat64"; 6 | import Result "mo:base/Result"; 7 | 8 | module { 9 | public type ByteOrder = { 10 | fromNat16 : (Nat16) -> [Nat8]; 11 | fromNat32 : (Nat32) -> [Nat8]; 12 | fromNat64 : (Nat64) -> [Nat8]; 13 | toNat16 : ([Nat8]) -> Nat16; 14 | toNat32 : ([Nat8]) -> Nat32; 15 | toNat64 : ([Nat8]) -> Nat64; 16 | }; 17 | 18 | private func nat16to8 (n : Nat16) : Nat8 = Nat8.fromIntWrap(Nat16.toNat(n)); 19 | private func nat8to16 (n : Nat8) : Nat16 = Nat16.fromIntWrap(Nat8.toNat(n)); 20 | 21 | private func nat32to8 (n : Nat32) : Nat8 = Nat8.fromIntWrap(Nat32.toNat(n)); 22 | private func nat8to32 (n : Nat8) : Nat32 = Nat32.fromIntWrap(Nat8.toNat(n)); 23 | 24 | private func nat64to8 (n : Nat64) : Nat8 = Nat8.fromIntWrap(Nat64.toNat(n)); 25 | private func nat8to64 (n : Nat8) : Nat64 = Nat64.fromIntWrap(Nat8.toNat(n)); 26 | 27 | public let LittleEndian : ByteOrder = { 28 | toNat16 = func (src : [Nat8]) : Nat16 { 29 | nat8to16(src[0]) | nat8to16(src[1]) << 8; 30 | }; 31 | 32 | fromNat16 = func (n : Nat16) : [Nat8] { 33 | let b = Array.init(2, 0x00); 34 | b[0] := nat16to8(n); 35 | b[1] := nat16to8(n >> 8); 36 | Array.freeze(b); 37 | }; 38 | 39 | toNat32 = func (src : [Nat8]) : Nat32 { 40 | nat8to32(src[0]) | nat8to32(src[1]) << 8 | nat8to32(src[2]) << 16 | nat8to32(src[3]) << 24; 41 | }; 42 | 43 | fromNat32 = func (n : Nat32) : [Nat8] { 44 | let b = Array.init(4, 0x00); 45 | b[0] := nat32to8(n); 46 | b[1] := nat32to8(n >> 8); 47 | b[2] := nat32to8(n >> 16); 48 | b[3] := nat32to8(n >> 24); 49 | Array.freeze(b); 50 | }; 51 | 52 | toNat64 = func (src : [Nat8]) : Nat64 { 53 | nat8to64(src[0]) | nat8to64(src[1]) << 8 | nat8to64(src[2]) << 16 | nat8to64(src[3]) << 24 | 54 | nat8to64(src[4]) << 32 | nat8to64(src[5]) << 40 | nat8to64(src[6]) << 48 | nat8to64(src[7]) << 56; 55 | }; 56 | 57 | fromNat64 = func (n : Nat64) : [Nat8] { 58 | let b = Array.init(8, 0x00); 59 | b[0] := nat64to8(n); 60 | b[1] := nat64to8(n >> 8); 61 | b[2] := nat64to8(n >> 16); 62 | b[3] := nat64to8(n >> 24); 63 | b[4] := nat64to8(n >> 32); 64 | b[5] := nat64to8(n >> 40); 65 | b[6] := nat64to8(n >> 48); 66 | b[7] := nat64to8(n >> 56); 67 | Array.freeze(b); 68 | }; 69 | }; 70 | 71 | public let BigEndian : ByteOrder = { 72 | toNat16 = func (src : [Nat8]) : Nat16 { 73 | nat8to16(src[1]) | nat8to16(src[0]) << 8; 74 | }; 75 | 76 | fromNat16 = func (n : Nat16) : [Nat8] { 77 | let b = Array.init(2, 0x00); 78 | b[0] := nat16to8(n >> 8); 79 | b[1] := nat16to8(n); 80 | Array.freeze(b); 81 | }; 82 | 83 | toNat32 = func (src : [Nat8]) : Nat32 { 84 | nat8to32(src[3]) | nat8to32(src[2]) << 8 | nat8to32(src[1]) << 16 | nat8to32(src[0]) << 24; 85 | }; 86 | 87 | fromNat32 = func (n : Nat32) : [Nat8] { 88 | let b = Array.init(4, 0x00); 89 | b[0] := nat32to8(n >> 24); 90 | b[1] := nat32to8(n >> 16); 91 | b[2] := nat32to8(n >> 8); 92 | b[3] := nat32to8(n); 93 | Array.freeze(b); 94 | }; 95 | 96 | toNat64 = func (src : [Nat8]) : Nat64 { 97 | nat8to64(src[7]) | nat8to64(src[6]) << 8 | nat8to64(src[5]) << 16 | nat8to64(src[4]) << 24 | 98 | nat8to64(src[3]) << 32 | nat8to64(src[2]) << 40 | nat8to64(src[1]) << 48 | nat8to64(src[0]) << 56; 99 | }; 100 | 101 | fromNat64 = func (n : Nat64) : [Nat8] { 102 | let b = Array.init(8, 0x00); 103 | b[0] := nat64to8(n >> 56); 104 | b[1] := nat64to8(n >> 48); 105 | b[2] := nat64to8(n >> 40); 106 | b[3] := nat64to8(n >> 32); 107 | b[4] := nat64to8(n >> 24); 108 | b[5] := nat64to8(n >> 16); 109 | b[6] := nat64to8(n >> 8); 110 | b[7] := nat64to8(n); 111 | Array.freeze(b); 112 | }; 113 | }; 114 | }; 115 | -------------------------------------------------------------------------------- /lib/Hex.mo: -------------------------------------------------------------------------------- 1 | import Array "mo:base/Array"; 2 | import Blob "mo:base/Blob"; 3 | import Char "mo:base/Char"; 4 | import Hash "mo:base/Hash"; 5 | import Iter "mo:base/Iter"; 6 | import Nat8 "mo:base/Nat8"; 7 | import Result "mo:base/Result"; 8 | 9 | module { 10 | private let base : Nat8 = 16; 11 | private let hex : [Char] = [ 12 | '0', '1', '2', '3', 13 | '4', '5', '6', '7', 14 | '8', '9', 'a', 'b', 15 | 'c', 'd', 'e', 'f', 16 | ]; 17 | 18 | private func toLower(c : Char) : Char { 19 | switch (c) { 20 | case ('A') { 'a' }; 21 | case ('B') { 'b' }; 22 | case ('C') { 'c' }; 23 | case ('D') { 'd' }; 24 | case ('E') { 'e' }; 25 | case ('F') { 'f' }; 26 | case (_) { c; }; 27 | }; 28 | }; 29 | 30 | public type Hex = Text; 31 | 32 | // Checks whether two hex strings are equal. 33 | public func equal(a : Hex, b : Hex) : Bool { 34 | if (a.size() != b.size()) return false; 35 | let bcs = b.chars(); 36 | for (ac in a.chars()) { 37 | let a = toLower(ac); 38 | let bc = bcs.next(); 39 | switch (bc) { 40 | case (null) { return false; }; 41 | case (? bc) { 42 | let b = toLower(bc); 43 | if (a != b) return false; 44 | }; 45 | }; 46 | }; 47 | bcs.next() == null; 48 | }; 49 | 50 | // Hashes the given hex text. 51 | // NOTE: assumes the text is valid hex: [0-9a-fA-F]. 52 | public func hash(h : Hex) : Hash.Hash { 53 | switch (decode(h)) { 54 | case (#err(_)) { assert(false); 0 }; 55 | case (#ok(r)) { Blob.hash(Blob.fromArray(r)); }; 56 | }; 57 | }; 58 | 59 | // Checks whether the given hex text is valid hex. 60 | public func valid(h : Hex) : Bool { 61 | for (c in h.chars()) { 62 | for (i in hex.keys()) { 63 | let h = hex[i]; 64 | if (h != c and h != toLower(c)) { 65 | return false; 66 | }; 67 | }; 68 | }; 69 | true; 70 | }; 71 | 72 | // Converts a byte to its corresponding hexidecimal format. 73 | public func encodeByte(n : Nat8) : Hex { 74 | let c0 = hex[Nat8.toNat(n / base)]; 75 | let c1 = hex[Nat8.toNat(n % base)]; 76 | Char.toText(c0) # Char.toText(c1); 77 | }; 78 | 79 | // Converts an array of bytes to their corresponding hexidecimal format. 80 | public func encode(ns : [Nat8]) : Hex { 81 | Array.foldRight( 82 | ns, 83 | "", 84 | func(n : Nat8, acc : Hex) : Hex { 85 | encodeByte(n) # acc; 86 | }, 87 | ); 88 | }; 89 | 90 | // Converts the given hexadecimal character to its corresponding binary format. 91 | // NOTE: a hexadecimal char is just an 4-bit natural number. 92 | public func decodeChar(c : Char) : Result.Result { 93 | for (i in hex.keys()) { 94 | let h = hex[i]; 95 | if (h == c or h == toLower(c)) { 96 | return #ok(Nat8.fromNat(i)); 97 | } 98 | }; 99 | #err("unexpected character: " # Char.toText(c)); 100 | }; 101 | 102 | // Converts the given hexidecimal text to its corresponding binary format. 103 | public func decode(t : Hex) : Result.Result<[Nat8], Text> { 104 | var cs = Iter.toArray(t.chars()); 105 | if (cs.size() % 2 != 0) { 106 | cs := Array.append(['0'], cs); 107 | }; 108 | let ns = Array.init(cs.size() / 2, 0); 109 | for (i in Iter.range(0, ns.size() - 1)) { 110 | let j : Nat = i * 2; 111 | switch (decodeChar(cs[j])) { 112 | case (#err(e)) { return #err(e); }; 113 | case (#ok(x0)) { 114 | switch (decodeChar(cs[j+1])) { 115 | case (#err(e)) { return #err(e); }; 116 | case (#ok(x1)) { 117 | ns[i] := x0 * base + x1; 118 | }; 119 | }; 120 | }; 121 | }; 122 | }; 123 | #ok(Array.freeze(ns)); 124 | }; 125 | 126 | public func decode2(t : Hex) : ?[Nat8]{ 127 | switch(decode(t)){ 128 | case (#ok(v)) ?v; 129 | case (#err(e)) null; 130 | } 131 | }; 132 | }; 133 | -------------------------------------------------------------------------------- /sys/CyclesWallet.mo: -------------------------------------------------------------------------------- 1 | // Cycles Wallet 2 | // https://github.com/dfinity/cycles-wallet/ 3 | // https://github.com/dfinity/cycles-wallet/blob/main/wallet/src/lib.did 4 | 5 | module { 6 | type EventKind = { 7 | #CyclesSent: { 8 | to: Principal; 9 | amount: Nat64; 10 | refund: Nat64; 11 | }; 12 | #CyclesReceived: { 13 | from: Principal; 14 | amount: Nat64; 15 | }; 16 | #AddressAdded: { 17 | id: Principal; 18 | name: ?Text; 19 | role: Role; 20 | }; 21 | #AddressRemoved: { 22 | id: Principal; 23 | }; 24 | #CanisterCreated: { 25 | canister: Principal; 26 | cycles: Nat64; 27 | }; 28 | #CanisterCalled: { 29 | canister: Principal; 30 | method_name: Text; 31 | cycles: Nat64; 32 | }; 33 | #WalletDeployed: { 34 | canister: Principal; 35 | } 36 | }; 37 | 38 | type Event = { 39 | id: Nat32; 40 | timestamp: Nat64; 41 | kind: EventKind; 42 | }; 43 | 44 | type Role = { 45 | #Contact; 46 | #Custodian; 47 | #Controller; 48 | }; 49 | 50 | type Kind = { 51 | #Unknown; 52 | #User; 53 | #Canister; 54 | }; 55 | 56 | // An entry in the address book. It must have an ID and a role. 57 | type AddressEntry = { 58 | id: Principal; 59 | name: ?Text; 60 | kind: Kind; 61 | role: Role; 62 | }; 63 | 64 | type WalletResultCreate = { 65 | #Ok : { canister_id: Principal }; 66 | #Err: Text; 67 | }; 68 | 69 | type WalletResult = { 70 | #Ok; 71 | #Err : Text; 72 | }; 73 | 74 | type WalletResultCall = { 75 | #Ok : { return_: Blob }; 76 | #Err : Text; 77 | }; 78 | 79 | type CanisterSettings = { 80 | controller: ?Principal; 81 | controllers: ?[Principal]; 82 | compute_allocation: ?Nat; 83 | memory_allocation: ?Nat; 84 | freezing_threshold: ?Nat; 85 | }; 86 | 87 | type CreateCanisterArgs = { 88 | cycles: Nat64; 89 | settings: CanisterSettings; 90 | }; 91 | 92 | 93 | // Assets 94 | type HeaderField = (Text, Text); 95 | 96 | type HttpRequest = { 97 | method: Text; 98 | url: Text; 99 | headers: [HeaderField]; 100 | body: Blob; 101 | }; 102 | 103 | type HttpResponse = { 104 | status_code: Nat16; 105 | headers: [HeaderField]; 106 | body: Blob; 107 | streaming_strategy: ?StreamingStrategy; 108 | }; 109 | 110 | type StreamingCallbackHttpResponse = { 111 | body: Blob; 112 | token: ?Token; 113 | }; 114 | 115 | type Token = {}; 116 | 117 | type StreamingStrategy = { 118 | #Callback: { 119 | callback: shared query (Token) -> async (StreamingCallbackHttpResponse); 120 | token: Token; 121 | }; 122 | }; 123 | public type Self = actor { 124 | wallet_api_version: shared query () -> async (Text); 125 | 126 | // Wallet Name 127 | name: shared query () -> async (?Text); 128 | set_name: shared (Text) -> async (); 129 | 130 | // Controller Management 131 | get_controllers: shared query () -> async ([Principal]); 132 | add_controller: shared (Principal) -> async (); 133 | remove_controller: shared (Principal) -> async (WalletResult); 134 | 135 | // Custodian Management 136 | get_custodians: shared query () -> async ([Principal]); 137 | authorize: shared (Principal) -> async (); 138 | deauthorize: shared (Principal) -> async (WalletResult); 139 | 140 | // Cycle Management 141 | wallet_balance: shared query () -> async ( { amount: Nat64 }); 142 | wallet_send: shared ( { canister: Principal; amount: Nat64 }) -> async (WalletResult); 143 | wallet_receive: shared () -> async (); // Endpoint for receiving cycles. 144 | 145 | // Managing canister 146 | wallet_create_canister: shared (CreateCanisterArgs) -> async (WalletResultCreate); 147 | 148 | wallet_create_wallet: shared (CreateCanisterArgs) -> async (WalletResultCreate); 149 | 150 | wallet_store_wallet_wasm: shared ( { 151 | wasm_module: Blob; 152 | }) -> async (); 153 | 154 | // Call Forwarding 155 | wallet_call: shared ( { 156 | canister: Principal; 157 | method_name: Text; 158 | args: Blob; 159 | cycles: Nat64; 160 | }) -> async (WalletResultCall); 161 | 162 | // Address book 163 | add_address: shared (address: AddressEntry) -> async (); 164 | list_addresses: shared query () -> async ([AddressEntry]); 165 | remove_address: shared (address: Principal) -> async (WalletResult); 166 | 167 | // Events 168 | get_events: shared query (?{ from: ?Nat32; to: ?Nat32; }) -> async ([Event]); //from,to is Event's id (只有controller才能调) 169 | get_chart: shared query (?{ count: ?Nat32; precision: ?Nat64; } ) -> async ([( Nat64, Nat64 )]); //(time, balance) 170 | 171 | // Assets 172 | http_request: shared query (request: HttpRequest) -> async (HttpResponse); 173 | }; 174 | } 175 | -------------------------------------------------------------------------------- /DRC205Bucket.mo: -------------------------------------------------------------------------------- 1 | /** 2 | * Module : DRC205Bucket.mo 3 | * Author : ICLighthouse Team 4 | * Stability : Experimental 5 | * Github : https://github.com/iclighthouse/DRC_standards/ 6 | */ 7 | import Prim "mo:⛔"; 8 | import Principal "mo:base/Principal"; 9 | import Blob "mo:base/Blob"; 10 | import Time "mo:base/Time"; 11 | import Trie "mo:base/Trie"; 12 | import Cycles "mo:base/ExperimentalCycles"; 13 | import CyclesWallet "./sys/CyclesWallet"; 14 | import SwapRecord "./lib/SwapRecord"; 15 | import DRC207 "./lib/DRC207"; 16 | 17 | shared(installMsg) actor class BucketActor() = this { 18 | type Bucket = SwapRecord.Bucket; 19 | type BucketInfo = SwapRecord.BucketInfo; 20 | type AppId = SwapRecord.AppId; 21 | type Txid = SwapRecord.Txid; 22 | type Sid = SwapRecord.Sid; 23 | type TxnRecord = SwapRecord.TxnRecord; 24 | 25 | private stable var owner: Principal = installMsg.caller; 26 | private var bucketVersion: Nat8 = 1; 27 | private stable var data: Trie.Trie = Trie.empty(); 28 | private stable var txnData: Trie.Trie = Trie.empty(); 29 | private stable var count: Nat = 0; 30 | private stable var lastStorage: (Sid, Time.Time) = (Blob.fromArray([]), 0); 31 | 32 | private func _onlyOwner(_caller: Principal) : Bool { 33 | return _caller == owner; 34 | }; 35 | private func key(t: Sid) : Trie.Key { return { key = t; hash = Blob.hash(t) }; }; 36 | 37 | public shared(msg) func storeBytes(_sid: Sid, _data: [Nat8]) : async (){ 38 | assert(_onlyOwner(msg.caller)); 39 | let now = Time.now(); 40 | let res = Trie.put(data, key(_sid), Blob.equal, (_data, now)); 41 | data := res.0; 42 | switch (res.1){ 43 | case(?(v)){ lastStorage := (_sid, now); }; 44 | case(_){ count += 1; lastStorage := (_sid, now); }; 45 | }; 46 | }; 47 | public shared(msg) func store(_sid: Sid, _txn: TxnRecord) : async (){ 48 | assert(_onlyOwner(msg.caller)); 49 | //let _data = SwapRecord.encode(_txn); 50 | let now = Time.now(); 51 | let res = Trie.put(txnData, key(_sid), Blob.equal, (_txn, now)); 52 | txnData := res.0; 53 | switch (res.1){ 54 | case(?(v)){ lastStorage := (_sid, now); }; 55 | case(_){ count += 1; lastStorage := (_sid, now); }; 56 | }; 57 | }; 58 | public query func txnBytes(_app: AppId, _txid: Txid) : async ?([Nat8], Time.Time){ 59 | let _sid = SwapRecord.generateSid(_app, _txid); 60 | return Trie.get(data, key(_sid), Blob.equal); 61 | }; 62 | public query func txnBytes2(_sid: Sid) : async ?([Nat8], Time.Time){ 63 | return Trie.get(data, key(_sid), Blob.equal); 64 | }; 65 | public query func txn(_app: AppId, _txid: Txid) : async ?(TxnRecord, Time.Time){ 66 | let _sid = SwapRecord.generateSid(_app, _txid); 67 | let _txn = Trie.get(txnData, key(_sid), Blob.equal); 68 | switch (_txn){ 69 | case(?(v)){ 70 | return ?(v.0, v.1); 71 | }; 72 | case(_){ return null; }; 73 | }; 74 | }; 75 | 76 | public query func bucketInfo() : async BucketInfo{ 77 | return { 78 | cycles = Cycles.balance(); 79 | memory = Prim.rts_memory_size(); 80 | heap = Prim.rts_heap_size(); 81 | stableMemory = Prim.stableMemorySize(); 82 | count = count; 83 | }; 84 | }; 85 | public query func last() : async (Sid, Time.Time){ 86 | return lastStorage; 87 | }; 88 | 89 | // receive cycles 90 | public func wallet_receive(): async (){ 91 | let amout = Cycles.available(); 92 | let accepted = Cycles.accept(amout); 93 | }; 94 | //cycles withdraw: _onlyOwner 95 | public shared(msg) func cyclesWithdraw(_wallet: Principal, _amount: Nat): async (){ 96 | assert(_onlyOwner(msg.caller)); 97 | let cyclesWallet: CyclesWallet.Self = actor(Principal.toText(_wallet)); 98 | let balance = Cycles.balance(); 99 | var value: Nat = _amount; 100 | if (balance <= _amount) { 101 | value := balance; 102 | }; 103 | Cycles.add(value); 104 | await cyclesWallet.wallet_receive(); 105 | //Cycles.refunded(); 106 | }; 107 | 108 | 109 | // DRC207 ICMonitor 110 | /// DRC207 support 111 | public func drc207() : async DRC207.DRC207Support{ 112 | return { 113 | monitorable_by_self = true; 114 | monitorable_by_blackhole = { allowed = true; canister_id = ?Principal.fromText("7hdtw-jqaaa-aaaak-aaccq-cai"); }; 115 | cycles_receivable = true; 116 | timer = { enable = false; interval_seconds = null; }; 117 | }; 118 | }; 119 | /// canister_status 120 | public func canister_status() : async DRC207.canister_status { 121 | let ic : DRC207.IC = actor("aaaaa-aa"); 122 | await ic.canister_status({ canister_id = Principal.fromActor(this) }); 123 | }; 124 | /// receive cycles 125 | // public func wallet_receive(): async (){ 126 | // let amout = Cycles.available(); 127 | // let accepted = Cycles.accept(amout); 128 | // }; 129 | /// timer tick 130 | // public func timer_tick(): async (){ 131 | // // 132 | // }; 133 | 134 | } -------------------------------------------------------------------------------- /lib/Types.mo: -------------------------------------------------------------------------------- 1 | import Ledger "../sys/Ledger2"; 2 | import Time "mo:base/Time"; 3 | import Result "mo:base/Result"; 4 | 5 | module { 6 | public type Timestamp = Nat; // seconds (Time.Time/1000000000) 7 | public type Address = Text; 8 | public type AccountId = Blob; 9 | public type Sa = [Nat8]; 10 | public type CyclesWallet = Principal; 11 | public type CyclesAmount = Nat; 12 | public type IcpE8s = Nat; 13 | public type Shares = Nat; 14 | public type Nonce = Nat; 15 | public type Data = Blob; 16 | public type Txid = Blob; 17 | // type Price = (cycles: Nat, icp: Nat); // x cycles per y icp 18 | public type ShareWeighted = { 19 | shareTimeWeighted: Nat; 20 | updateTime: Timestamp; 21 | }; 22 | public type CumulShareWeighted = Nat; 23 | public type Vol = { 24 | swapCyclesVol: CyclesAmount; 25 | swapIcpVol: IcpE8s; 26 | }; 27 | public type PriceWeighted = { 28 | cyclesTimeWeighted: Nat; // cyclesTimeWeighted += cycles*seconds 29 | icpTimeWeighted: Nat; 30 | updateTime: Timestamp; 31 | }; 32 | public type FeeBalance = { 33 | var cyclesBalance: CyclesAmount; 34 | var icpBalance: IcpE8s; 35 | }; 36 | public type Liquidity = { 37 | cycles: Nat; 38 | icpE8s: IcpE8s; 39 | shares: Shares; 40 | shareWeighted: ShareWeighted; 41 | cumulShareWeighted: CumulShareWeighted; 42 | unitValue: (cycles: Float, icpE8s: Float); 43 | vol: Vol; 44 | priceWeighted: PriceWeighted; 45 | swapCount: Nat64; 46 | }; 47 | public type FeeStatus = { 48 | fee: Float; 49 | cumulFee: { 50 | cyclesBalance: CyclesAmount; 51 | icpBalance: IcpE8s; 52 | }; 53 | totalFee: { 54 | cyclesBalance: CyclesAmount; 55 | icpBalance: IcpE8s; 56 | }; 57 | myPortion: ?{ 58 | cyclesBalance: CyclesAmount; 59 | icpBalance: IcpE8s; 60 | }; 61 | }; 62 | public type TransStatus = { 63 | #Processing; 64 | #Success; 65 | #Failure; 66 | #Fallback; 67 | }; 68 | public type IcpTransferLog = {from: AccountId; to: AccountId; value: IcpE8s; fee: IcpE8s; status: TransStatus; updateTime: Timestamp}; 69 | public type CyclesTransferLog = {from: Principal; to: Principal; value: CyclesAmount; status: TransStatus; updateTime: Timestamp}; 70 | public type ErrorLog = { 71 | #IcpSaToMain: { 72 | user: AccountId; 73 | debit: (index: Nat64, sa: AccountId, icp: IcpE8s); 74 | errMsg: Ledger.TransferError; 75 | time: Timestamp; 76 | }; 77 | #Withdraw: { 78 | user: AccountId; 79 | credit: (cyclesWallet: CyclesWallet, cycles: CyclesAmount, icpAccount: AccountId, icp: IcpE8s); 80 | cyclesErrMsg: Text; 81 | icpErrMsg: ?Ledger.TransferError; 82 | time: Timestamp; 83 | }; 84 | }; 85 | public type ErrorAction = {#delete; #fallback; #resendIcp; #resendCycles; #resendIcpCycles;}; 86 | 87 | public type Config = { 88 | MIN_CYCLES: ?Nat; 89 | MIN_ICP_E8S: ?Nat; 90 | ICP_FEE: ?Nat64; 91 | FEE: ?Nat; 92 | ICP_LIMIT: ?Nat; 93 | CYCLES_LIMIT: ?Nat; 94 | MAX_CACHE_TIME: ?Nat; 95 | MAX_CACHE_NUMBER_PER: ?Nat; 96 | STORAGE_CANISTER: ?Text; 97 | MAX_STORAGE_TRIES: ?Nat; 98 | }; 99 | 100 | public type TokenType = { 101 | #Cycles; 102 | #Icp; 103 | #Token: Principal; 104 | }; 105 | public type OperationType = { 106 | #AddLiquidity; 107 | #RemoveLiquidity; 108 | #Claim; 109 | #Swap; 110 | }; 111 | public type BalanceChange = { 112 | #DebitRecord: Nat; 113 | #CreditRecord: Nat; 114 | #NoChange; 115 | }; 116 | public type ShareChange = { 117 | #Mint: Shares; 118 | #Burn: Shares; 119 | #NoChange; 120 | }; 121 | public type TxnRecord = { 122 | txid: Txid; 123 | msgCaller: ?Principal; 124 | caller: AccountId; 125 | operation: OperationType; 126 | account: AccountId; 127 | cyclesWallet: ?CyclesWallet; 128 | token0: TokenType; 129 | token1: TokenType; 130 | token0Value: BalanceChange; 131 | token1Value: BalanceChange; 132 | fee: {token0Fee: Nat; token1Fee: Nat; }; 133 | shares: ShareChange; 134 | time: Time.Time; 135 | index: Nat; 136 | nonce: Nonce; 137 | orderType: { #AMM; #OrderBook; }; 138 | details: [{counterparty: Txid; token0Value: BalanceChange; token1Value: BalanceChange;}]; 139 | data: ?Data; 140 | }; 141 | public type TxnResult = Result.Result<{ //<#ok, #err> 142 | txid: Txid; 143 | cycles: BalanceChange; 144 | icpE8s: BalanceChange; 145 | shares: ShareChange; 146 | }, { 147 | code: { 148 | #NonceError; 149 | #InvalidCyclesAmout; 150 | #InvalidIcpAmout; 151 | #InsufficientShares; 152 | #PoolIsEmpty; 153 | #IcpTransferException; 154 | #UnacceptableVolatility; 155 | #UndefinedError; 156 | }; 157 | message: Text; 158 | }>; 159 | } -------------------------------------------------------------------------------- /lib/SHA224.mo: -------------------------------------------------------------------------------- 1 | import Array "mo:base/Array"; 2 | import Iter "mo:base/Iter"; 3 | import Nat "mo:base/Nat"; 4 | import Nat8 "mo:base/Nat8"; 5 | import Nat32 "mo:base/Nat32"; 6 | import Nat64 "mo:base/Nat64"; 7 | import Blob "mo:base/Blob"; 8 | 9 | module { 10 | 11 | private let K : [Nat32] = [ 12 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 13 | 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 14 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 15 | 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 16 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 17 | 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 18 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 19 | 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 20 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 21 | 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 22 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 23 | 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 24 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 25 | 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 26 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 27 | 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, 28 | ]; 29 | 30 | private let S : [Nat32] = [ 31 | 0xC1059ED8, 0x367CD507, 0x3070DD17, 0xF70E5939, 32 | 0xFFC00B31, 0x68581511, 0x64F98FA7, 0xBEFA4FA4, 33 | ]; 34 | 35 | // Calculate a SHA224 hash. 36 | public func sha224(data : [Nat8]) : [Nat8] { 37 | let digest = Digest(); 38 | digest.write(data); 39 | return digest.sum(); 40 | }; 41 | 42 | public class Digest() { 43 | 44 | private let s = Array.thaw(S); 45 | 46 | private let x = Array.init(64, 0); 47 | 48 | private var nx = 0; 49 | 50 | private var len : Nat64 = 0; 51 | 52 | public func reset() { 53 | for (i in Iter.range(0, 7)) { 54 | s[i] := S[i]; 55 | }; 56 | nx := 0; 57 | len := 0; 58 | }; 59 | 60 | public func write(data : [Nat8]) { 61 | var p = data; 62 | len +%= Nat64.fromIntWrap(p.size()); 63 | if (nx > 0) { 64 | let n = Nat.min(p.size(), 64 - nx); 65 | for (i in Iter.range(0, n - 1)) { 66 | x[nx + i] := p[i]; 67 | }; 68 | nx += n; 69 | if (nx == 64) { 70 | let buf = Array.freeze(x); 71 | block(buf); 72 | nx := 0; 73 | }; 74 | p := Array.tabulate(p.size() - n, func (i) { 75 | return p[n + i]; 76 | }); 77 | }; 78 | if (p.size() >= 64) { 79 | let n = Nat64.toNat(Nat64.fromIntWrap(p.size()) & (^ 63)); 80 | let buf = Array.tabulate(n, func (i) { 81 | return p[i]; 82 | }); 83 | block(buf); 84 | p := Array.tabulate(p.size() - n, func (i) { 85 | return p[n + i]; 86 | }); 87 | }; 88 | if (p.size() > 0) { 89 | for (i in Iter.range(0, p.size() - 1)) { 90 | x[i] := p[i]; 91 | }; 92 | nx := p.size(); 93 | }; 94 | }; 95 | 96 | public func sum() : [Nat8] { 97 | var m = 0; 98 | var n = len; 99 | var t = Nat64.toNat(n) % 64; 100 | var buf : [var Nat8] = [var]; 101 | if (56 > t) { 102 | m := 56 - t; 103 | } else { 104 | m := 120 - t; 105 | }; 106 | n := n << 3; 107 | buf := Array.init(m, 0); 108 | if (m > 0) { 109 | buf[0] := 0x80; 110 | }; 111 | write(Array.freeze(buf)); 112 | buf := Array.init(8, 0); 113 | for (i in Iter.range(0, 7)) { 114 | let j : Nat64 = 56 -% 8 *% Nat64.fromIntWrap(i); 115 | buf[i] := Nat8.fromIntWrap(Nat64.toNat(n >> j)); 116 | }; 117 | write(Array.freeze(buf)); 118 | let hash = Array.init(28, 0); 119 | for (i in Iter.range(0, 6)) { 120 | for (j in Iter.range(0, 3)) { 121 | let k : Nat32 = 24 -% 8 *% Nat32.fromIntWrap(j); 122 | hash[4 * i + j] := Nat8.fromIntWrap(Nat32.toNat(s[i] >> k)); 123 | }; 124 | }; 125 | return Array.freeze(hash); 126 | }; 127 | 128 | private func block(data : [Nat8]) { 129 | var p = data; 130 | var w = Array.init(64, 0); 131 | while (p.size() >= 64) { 132 | var j = 0; 133 | for (i in Iter.range(0, 15)) { 134 | j := i * 4; 135 | w[i] := 136 | Nat32.fromIntWrap(Nat8.toNat(p[j + 0])) << 24 | 137 | Nat32.fromIntWrap(Nat8.toNat(p[j + 1])) << 16 | 138 | Nat32.fromIntWrap(Nat8.toNat(p[j + 2])) << 08 | 139 | Nat32.fromIntWrap(Nat8.toNat(p[j + 3])) << 00; 140 | }; 141 | var v1 : Nat32 = 0; 142 | var v2 : Nat32 = 0; 143 | var t1 : Nat32 = 0; 144 | var t2 : Nat32 = 0; 145 | for (i in Iter.range(16, 63)) { 146 | v1 := w[i - 02]; 147 | v2 := w[i - 15]; 148 | t1 := rot(v1, 17) ^ rot(v1, 19) ^ (v1 >> 10); 149 | t2 := rot(v2, 07) ^ rot(v2, 18) ^ (v2 >> 03); 150 | w[i] := 151 | t1 +% w[i - 07] +% 152 | t2 +% w[i - 16]; 153 | }; 154 | var a = s[0]; 155 | var b = s[1]; 156 | var c = s[2]; 157 | var d = s[3]; 158 | var e = s[4]; 159 | var f = s[5]; 160 | var g = s[6]; 161 | var h = s[7]; 162 | for (i in Iter.range(0, 63)) { 163 | t1 := rot(e, 06) ^ rot(e, 11) ^ rot(e, 25); 164 | t1 +%= (e & f) ^ (^ e & g) +% h +% K[i] +% w[i]; 165 | t2 := rot(a, 02) ^ rot(a, 13) ^ rot(a, 22); 166 | t2 +%= (a & b) ^ (a & c) ^ (b & c); 167 | h := g; 168 | g := f; 169 | f := e; 170 | e := d +% t1; 171 | d := c; 172 | c := b; 173 | b := a; 174 | a := t1 +% t2; 175 | }; 176 | s[0] +%= a; 177 | s[1] +%= b; 178 | s[2] +%= c; 179 | s[3] +%= d; 180 | s[4] +%= e; 181 | s[5] +%= f; 182 | s[6] +%= g; 183 | s[7] +%= h; 184 | p := Array.tabulate(p.size() - 64, func (i) { 185 | return p[i + 64]; 186 | }); 187 | }; 188 | }; 189 | }; 190 | 191 | private let rot : (Nat32, Nat32) -> Nat32 = Nat32.bitrotRight; 192 | }; -------------------------------------------------------------------------------- /lib/Bloom.mo: -------------------------------------------------------------------------------- 1 | /** 2 | * Module : Bloom.mo v 1.0 3 | * Author : DFINITY-Education, Modified by ICLight.house Team 4 | * Stability : Experimental 5 | * Description: BloomFilter. 6 | * Refers : https://github.com/DFINITY-Education/data-structures/tree/main/src/BloomFilter 7 | */ 8 | import Array "mo:base/Array"; 9 | import Blob "mo:base/Blob"; 10 | import Float "mo:base/Float"; 11 | import Hash "mo:base/Hash"; 12 | import Int "mo:base/Int"; 13 | import Iter "mo:base/Iter"; 14 | import Nat "mo:base/Nat"; 15 | import Nat32 "mo:base/Nat32"; 16 | import Nat8 "mo:base/Nat8"; 17 | import Principal "mo:base/Principal"; 18 | import SHA224 "SHA224"; 19 | 20 | module { 21 | 22 | type Hash = Hash.Hash; 23 | 24 | /// Hash function example in case the element's type is Blob: 25 | private func nat8to32 (n : Nat8) : Nat32{ 26 | Nat32.fromIntWrap(Nat8.toNat(n)); 27 | }; 28 | public func blobHash(b: Blob, k: Nat32) : [Hash]{ 29 | if (k == 0){ return [] }; 30 | var s: [Nat8] = Blob.toArray(b); 31 | var res: [Hash] = []; 32 | for (i in Iter.range(1, Nat32.toNat(k))){ 33 | s := SHA224.sha224(s); 34 | let h = nat8to32(s[3]) | nat8to32(s[2]) << 8 | nat8to32(s[1]) << 16 | nat8to32(s[0]) << 24; 35 | res := Array.append(res, [h]); 36 | }; 37 | return res; 38 | }; 39 | public func principalHash(p: Principal, k: Nat32) : [Hash]{ 40 | return blobHash(Principal.toBlob(p), k); 41 | }; 42 | 43 | /// Manages BloomFilters, deploys new BloomFilters, and checks for element membership across filters. 44 | /// Args: 45 | /// |n| The maximum number of elements a BlooomFilter may store. 46 | /// |p| The maximum false positive rate a BloomFilter may maintain. 47 | /// |f| The hash function used to hash element. 48 | public class AutoScalingBloomFilter(n: Nat, p: Float, f: (S, Nat32) -> [Hash]) { 49 | 50 | var filters: [BloomFilter] = []; 51 | var numItems = 0; 52 | var m: Float = Float.ceil(Float.fromInt(n) * Float.abs(Float.log(p)) / (Float.log(2) ** 2)); 53 | m := Float.ceil(m / 8) * 8; 54 | let m_: Nat32 = Nat32.fromNat(Int.abs(Float.toInt(m))); 55 | let k: Float = Float.ceil(0.7 * m / Float.fromInt(n)); 56 | let k_: Nat32 = Nat32.fromNat(Int.abs(Float.toInt(k))); 57 | 58 | public func getM() : Nat32 { 59 | return m_; 60 | }; 61 | public func getK() : Nat32 { 62 | return k_; 63 | }; 64 | 65 | /// Adds an element to the BloomFilter's bitmap and deploys new BloomFilter if previous is at n. 66 | /// Args: 67 | /// |item| The item to be added. 68 | public func add(item: S) { 69 | var newFilter: Bool = false; 70 | var filter: BloomFilter = do { 71 | if (filters.size() > 0) { 72 | let last_filter = filters[filters.size() - 1]; 73 | if (last_filter.getNumItems() < n) { 74 | last_filter 75 | } else { 76 | newFilter := true; 77 | BloomFilter(m_, k_, f) 78 | } 79 | } else { 80 | newFilter := true; 81 | BloomFilter(m_, k_, f) 82 | } 83 | }; 84 | filter.add(item); 85 | numItems += 1; 86 | if (newFilter) { 87 | filters := Array.append>(filters, [filter]); 88 | }; 89 | }; 90 | 91 | /// Checks if an item is contained in any BloomFilters 92 | /// Args: 93 | /// |item| The item to be searched for. 94 | /// Returns: 95 | /// A boolean indicating set membership. 96 | public func check(item: S) : Bool { 97 | for (filter in Iter.fromArray(filters)) { 98 | if (filter.check(item)) { return true; }; 99 | }; 100 | false 101 | }; 102 | 103 | public func getNumItems() : Nat { 104 | return numItems; 105 | }; 106 | 107 | public func getBitMap() : [[Nat8]] { 108 | var size = filters.size(); 109 | if (size ==0 ) { return [] }; 110 | let bitMaps = Array.init<[Nat8]>(size, []); 111 | for (i in Iter.range(0, size-1)){ 112 | bitMaps[i] := filters[i].getBitMap(); 113 | }; 114 | return Array.freeze(bitMaps); 115 | }; 116 | 117 | public func setData(data: [[Nat8]]) { 118 | var size = data.size(); 119 | if (size ==0 ) { return () }; 120 | let filters_ = Array.init>(size, BloomFilter(m_, k_, f)); 121 | for (i in Iter.range(0, size-1)){ 122 | filters_[i].setData(data[i]); 123 | }; 124 | filters := Array.freeze(filters_); 125 | }; 126 | 127 | }; 128 | 129 | /// The specific BloomFilter implementation used in AutoScalingBloomFilter. 130 | /// Args: 131 | /// |m| The size of the bitmap (as determined in AutoScalingBloomFilter). 132 | /// |k| Number of hash functions. 133 | /// |f| The hash function of element. 134 | public class BloomFilter(m: Nat32, k: Nat32, f: (S, Nat32) -> [Hash]) { 135 | 136 | var numItems = 0; 137 | //let bitMap: [var Bool] = Array.init(Nat32.toNat(m), false); 138 | var mapSize: Nat = Nat32.toNat(m / 8); 139 | if (m % 8 > 0){ mapSize += 1; }; 140 | let bitMap_: [var Nat8] = Array.init(mapSize, 0); 141 | let bit8: [Nat8] = [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]; 142 | 143 | public func add(item: S) { 144 | for (h in Iter.fromArray(f(item, k))) { 145 | let pos = Nat32.toNat((h-1) % m); 146 | let mapPos = pos / 8; 147 | let bitPos = pos % 8; 148 | bitMap_[mapPos] |= bit8[bitPos]; 149 | }; 150 | numItems += 1; 151 | }; 152 | 153 | public func check(item: S) : Bool { 154 | for (h in Iter.fromArray(f(item, k))) { 155 | let pos = Nat32.toNat((h-1) % m); 156 | let mapPos = pos / 8; 157 | let bitPos = pos % 8; 158 | if (bitMap_[mapPos] ^ bit8[bitPos] == bit8[bitPos]) return false; 159 | }; 160 | return true; 161 | }; 162 | 163 | public func getNumItems() : Nat { 164 | return numItems; 165 | }; 166 | 167 | public func getBitMap() : [Nat8] { 168 | return Array.freeze(bitMap_); 169 | }; 170 | 171 | public func setData(data: [Nat8]) { 172 | assert(data.size() == mapSize); 173 | for (i in Iter.range(0, data.size() - 1)) { 174 | bitMap_[i] := data[i]; 175 | }; 176 | }; 177 | 178 | }; 179 | 180 | }; 181 | -------------------------------------------------------------------------------- /lib/BASE32.mo: -------------------------------------------------------------------------------- 1 | /// This library lets you encode and decode in either RFC4648 Base32 or in Crockford Base32. 2 | 3 | import Array "mo:base/Array"; 4 | import Iter "mo:base/Iter"; 5 | import Text "mo:base/Text"; 6 | import Char "mo:base/Char"; 7 | import Nat8 "mo:base/Nat8"; 8 | import Int8 "mo:base/Int8"; 9 | import Nat "mo:base/Nat"; 10 | import Nat32 "mo:base/Nat32"; 11 | import Int "mo:base/Int"; 12 | 13 | // refers: https://docs.rs/crate/base32/0.4.0/source/src/lib.rs 14 | module { 15 | let RFC4648_ALPHABET: [Nat8]= [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 50, 51, 52, 53, 54, 55]; // b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" 16 | let CROCKFORD_ALPHABET: [Nat8] = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 77, 78, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90]; // b"0123456789ABCDEFGHJKMNPQRSTVWXYZ" 17 | let RFC4648_INV_ALPHABET: [Int8] = [-1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, 0, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]; 18 | let CROCKFORD_INV_ALPHABET: [Int8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, 16, 17, 1, 18, 19, 1, 20, 21, 0, 22, 23, 24, 25, 26, -1, 27, 28, 29, 30, 31]; 19 | 20 | /// RFC4648 Base32 or Crockford Base32 21 | public type Alphabet = { 22 | #RFC4648: { padding: Bool; }; 23 | #Crockford; 24 | }; 25 | 26 | /// encode the bytes 27 | public func encode(alphabet: Alphabet, data: [Nat8]) : Text { 28 | let (alpha, padding) = switch alphabet { 29 | case (#RFC4648 { padding }) { (RFC4648_ALPHABET, padding); }; 30 | case (#Crockford) { (CROCKFORD_ALPHABET, false); }; 31 | }; 32 | let len =(data.size() + 3)/4*5; 33 | var ret: [var Nat8] = [var]; 34 | var res: Text = ""; 35 | let chunks = bytesToChunks(data, 5); 36 | for (i in chunks.keys()) { 37 | let buf: [var Nat8] = Array.init(5, 0); 38 | for (j in chunks[i].keys()) { 39 | buf[j] := chunks[i][j]; 40 | }; 41 | ret := Array.thaw(Array.append(Array.freeze(ret), [alpha[Nat8.toNat((buf[0] & 0xF8) >> 3)]])); 42 | ret := Array.thaw(Array.append(Array.freeze(ret), [alpha[Nat8.toNat(((buf[0] & 0x07) << 2) | ((buf[1] & 0xC0) >> 6))]])); 43 | ret := Array.thaw(Array.append(Array.freeze(ret), [alpha[Nat8.toNat((buf[1] & 0x3E) >> 1)]])); 44 | ret := Array.thaw(Array.append(Array.freeze(ret), [alpha[Nat8.toNat(((buf[1] & 0x01) << 4) | ((buf[2] & 0xF0) >> 4))]])); 45 | ret := Array.thaw(Array.append(Array.freeze(ret), [alpha[Nat8.toNat(((buf[2] & 0x0F) << 1) | (buf[3] >> 7))]])); 46 | ret := Array.thaw(Array.append(Array.freeze(ret), [alpha[Nat8.toNat((buf[3] & 0x7C) >> 2)]])); 47 | ret := Array.thaw(Array.append(Array.freeze(ret), [alpha[Nat8.toNat(((buf[3] & 0x03) << 3) | ((buf[4] & 0xE0) >> 5))]])); 48 | ret := Array.thaw(Array.append(Array.freeze(ret), [alpha[Nat8.toNat(buf[4] & 0x1F)]])); 49 | }; 50 | var len_ret: Nat = ret.size(); 51 | if ((data.size() % 5) != 0) { 52 | let len = ret.size(); 53 | var num_extra = 0; 54 | if (8 < ((data.size() % 5 * 8 + 4) / 5)) { 55 | num_extra := 0; 56 | } else { 57 | num_extra := 8 - ((data.size() % 5 * 8 + 4) / 5); 58 | }; 59 | if padding { 60 | for (i in Iter.range(1, num_extra)) { 61 | ret[len - i] := 61; // b'=' == 61 62 | }; 63 | } else { 64 | len_ret := len - num_extra; 65 | }; 66 | }; 67 | for (i in Iter.range(0, len_ret-1)) { 68 | res := res # Char.toText(Char.fromNat32(Nat32.fromNat(Nat8.toNat(ret[i]) ))); 69 | }; 70 | return res; 71 | }; 72 | 73 | /// decode the text 74 | public func decode(alphabet: Alphabet, data: Text) : ?[Nat8] { 75 | if (not is_ascii(data)) { 76 | return null; 77 | }; 78 | var bytes: [Nat8] = []; 79 | for (i in Text.toIter(data)) { 80 | bytes := Array.append(bytes, [Nat8.fromNat(Nat32.toNat(Char.toNat32(i)))]); 81 | }; 82 | let alpha = switch (alphabet) { 83 | case (#RFC4648 { padding }) { RFC4648_INV_ALPHABET; }; 84 | case (#Crockford) { CROCKFORD_INV_ALPHABET; }; 85 | }; 86 | var unpadded_bytes_length = bytes.size(); 87 | label l for (i in Iter.range(1, Nat.min(6, bytes.size()))) { 88 | if (bytes[bytes.size() - i] != 61) { // b'=' == 61 89 | break l; 90 | }; 91 | unpadded_bytes_length -= 1; 92 | }; 93 | let output_length = unpadded_bytes_length*5/8; 94 | var ret: [Nat8] = []; 95 | let ret_len = (output_length+4)/5*5; 96 | let chunks = bytesToChunks(bytes, 8); 97 | for (i in chunks.keys()) { 98 | let buf: [var Nat8] = Array.init(8, 0); 99 | for (j in chunks[i].keys()) { 100 | switch (get_element(alpha, Nat8.toNat(wrapping_sub(to_ascii_uppercase(chunks[i][j]), 48)) )) { // b'0' == 48 101 | case (?-1 or null) { return null; }; 102 | case (?val) { buf[j] := Int8.toNat8(val); }; 103 | } 104 | }; 105 | ret := Array.append(ret, [((buf[0] << 3) | (buf[1] >> 2))]); 106 | ret := Array.append(ret, [((buf[1] << 6) | (buf[2] << 1) | (buf[3] >> 4))]); 107 | ret := Array.append(ret, [((buf[3] << 4) | (buf[4] >> 1))]); 108 | ret := Array.append(ret, [((buf[4] << 7) | (buf[5] << 2)) | (buf[6] >> 3)]); 109 | ret := Array.append(ret, [((buf[6] << 5) | buf[7])]); 110 | }; 111 | var res = Array.init(output_length, 0); 112 | for (i in res.keys()) { 113 | res[i] := ret[i]; 114 | }; 115 | return ?Array.freeze(res); 116 | }; 117 | 118 | func bytesToChunks(bytes: [Nat8], interval: Nat) : [[Nat8]] { 119 | let len = bytes.size(); 120 | var ret: [[Nat8]] = []; 121 | for (i in Iter.range(1, len)) { 122 | var chunk: [var Nat8] = Array.init(interval, 0); 123 | if (i % interval == 0) { 124 | for (j in Iter.range(0, interval-1)) { 125 | chunk[j] := bytes[i-(interval-j)]; 126 | }; 127 | ret := Array.append(ret, [Array.freeze(chunk)]); 128 | }; 129 | }; 130 | if (len % interval != 0) { 131 | var chunk: [Nat8] = []; 132 | for (i in Iter.range(0, (len % interval) - 1)) { 133 | chunk := Array.append(chunk, [bytes[len - (len % interval) + i]]); 134 | }; 135 | ret := Array.append<[Nat8]>(ret, [chunk]); 136 | }; 137 | return ret; 138 | }; 139 | 140 | func is_ascii(a: Text) : Bool { 141 | for (i in Text.toIter(a)) { 142 | if (Char.toNat32(i) > 0x7F) { 143 | return false; 144 | }; 145 | }; 146 | return true; 147 | }; 148 | 149 | func to_ascii_uppercase(a: Nat8) : Nat8 { 150 | if (is_ascii_lowercase(Char.fromNat32(Nat32.fromNat(Nat8.toNat(a))))) { 151 | return 32 ^ a; 152 | } else { 153 | return a; 154 | }; 155 | }; 156 | 157 | func is_ascii_lowercase(a: Char) : Bool { 158 | return (a >= 'a' and a <= 'z'); 159 | }; 160 | 161 | func get_element(a: [Int8], index: Nat) : ?Int8 { 162 | if (index < a.size()) { 163 | return ?a[index]; 164 | } else { 165 | return null; 166 | }; 167 | }; 168 | 169 | func wrapping_sub(a: Nat8, b: Nat8) : Nat8 { 170 | if (a < b) { 171 | return 255 - b + a + 1; 172 | } else { 173 | return a - b; 174 | }; 175 | }; 176 | }; 177 | -------------------------------------------------------------------------------- /CyclesMarket.did: -------------------------------------------------------------------------------- 1 | type definite_canister_settings = 2 | record { 3 | compute_allocation: nat; 4 | controllers: vec principal; 5 | freezing_threshold: nat; 6 | memory_allocation: nat; 7 | }; 8 | type canister_status = 9 | record { 10 | cycles: nat; 11 | memory_size: nat; 12 | module_hash: opt vec nat8; 13 | settings: definite_canister_settings; 14 | status: variant { 15 | running; 16 | stopped; 17 | stopping; 18 | }; 19 | }; 20 | type Vol = 21 | record { 22 | swapCyclesVol: CyclesAmount; 23 | swapIcpVol: IcpE8s; 24 | }; 25 | type TxnResult = 26 | variant { 27 | err: 28 | record { 29 | code: 30 | variant { 31 | IcpTransferException; 32 | InsufficientShares; 33 | InvalidCyclesAmout; 34 | InvalidIcpAmout; 35 | NonceError; 36 | PoolIsEmpty; 37 | UnacceptableVolatility; 38 | UndefinedError; 39 | }; 40 | message: text; 41 | }; 42 | ok: 43 | record { 44 | cycles: BalanceChange; 45 | icpE8s: BalanceChange; 46 | shares: ShareChange; 47 | txid: Txid; 48 | }; 49 | }; 50 | type TxnRecord = 51 | record { 52 | account: AccountId; 53 | caller: AccountId; 54 | cyclesWallet: opt CyclesWallet; 55 | data: opt Data; 56 | details: 57 | vec 58 | record { 59 | counterparty: Txid; 60 | token0Value: BalanceChange; 61 | token1Value: BalanceChange; 62 | }; 63 | fee: record { 64 | token0Fee: nat; 65 | token1Fee: nat; 66 | }; 67 | index: nat; 68 | msgCaller: opt principal; 69 | nonce: Nonce; 70 | operation: OperationType; 71 | orderType: variant { 72 | AMM; 73 | OrderBook; 74 | }; 75 | shares: ShareChange; 76 | time: Time; 77 | token0: TokenType; 78 | token0Value: BalanceChange; 79 | token1: TokenType; 80 | token1Value: BalanceChange; 81 | txid: Txid; 82 | }; 83 | type Txid = blob; 84 | type TransferError = 85 | variant { 86 | BadFee: record {expected_fee: ICP;}; 87 | InsufficientFunds: record {balance: ICP;}; 88 | TxCreatedInFuture; 89 | TxDuplicate: record {duplicate_of: BlockIndex;}; 90 | TxTooOld: record {allowed_window_nanos: nat64;}; 91 | }; 92 | type TransStatus = 93 | variant { 94 | Failure; 95 | Fallback; 96 | Processing; 97 | Success; 98 | }; 99 | type TokenType = 100 | variant { 101 | Cycles; 102 | Icp; 103 | Token: principal; 104 | }; 105 | type Timestamp = nat; 106 | type Time = int; 107 | type Shares = nat; 108 | type ShareWeighted = 109 | record { 110 | shareTimeWeighted: nat; 111 | updateTime: Timestamp; 112 | }; 113 | type ShareChange = 114 | variant { 115 | Burn: Shares; 116 | Mint: Shares; 117 | NoChange; 118 | }; 119 | type Sa = vec nat8; 120 | type PriceWeighted = 121 | record { 122 | cyclesTimeWeighted: nat; 123 | icpTimeWeighted: nat; 124 | updateTime: Timestamp; 125 | }; 126 | type OperationType = 127 | variant { 128 | AddLiquidity; 129 | Claim; 130 | RemoveLiquidity; 131 | Swap; 132 | }; 133 | type Nonce = nat; 134 | type Liquidity = 135 | record { 136 | cycles: nat; 137 | icpE8s: IcpE8s; 138 | priceWeighted: PriceWeighted; 139 | shareWeighted: ShareWeighted; 140 | shares: Shares; 141 | swapCount: nat64; 142 | unitValue: record { 143 | float64; 144 | float64; 145 | }; 146 | vol: Vol; 147 | }; 148 | type IcpTransferLog = 149 | record { 150 | fee: IcpE8s; 151 | from: AccountId; 152 | status: TransStatus; 153 | to: AccountId; 154 | updateTime: Timestamp; 155 | value: IcpE8s; 156 | }; 157 | type IcpE8s = nat; 158 | type ICP = record {e8s: nat64;}; 159 | type FeeStatus = 160 | record { 161 | cumulFee: record { 162 | cyclesBalance: CyclesAmount; 163 | icpBalance: IcpE8s; 164 | }; 165 | fee: float64; 166 | totalFee: record { 167 | cyclesBalance: CyclesAmount; 168 | icpBalance: IcpE8s; 169 | }; 170 | }; 171 | type ErrorLog = 172 | variant { 173 | IcpSaToMain: 174 | record { 175 | debit: record { 176 | nat64; 177 | AccountId; 178 | IcpE8s; 179 | }; 180 | errMsg: TransferError; 181 | time: Timestamp; 182 | user: AccountId; 183 | }; 184 | Withdraw: 185 | record { 186 | credit: record { 187 | CyclesWallet; 188 | CyclesAmount; 189 | AccountId; 190 | IcpE8s; 191 | }; 192 | cyclesErrMsg: text; 193 | icpErrMsg: opt TransferError; 194 | time: Timestamp; 195 | user: AccountId; 196 | }; 197 | }; 198 | type ErrorAction = 199 | variant { 200 | delete; 201 | fallback; 202 | resendCycles; 203 | resendIcp; 204 | resendIcpCycles; 205 | }; 206 | type Data = blob; 207 | type DRC207Support = 208 | record { 209 | cycles_receivable: bool; 210 | monitorable_by_blackhole: 211 | record { 212 | allowed: bool; 213 | canister_id: opt principal; 214 | }; 215 | monitorable_by_self: bool; 216 | timer: record { 217 | enable: bool; 218 | interval_seconds: opt nat; 219 | }; 220 | }; 221 | type CyclesWallet = principal; 222 | type CyclesTransferLog = 223 | record { 224 | from: principal; 225 | status: TransStatus; 226 | to: principal; 227 | updateTime: Timestamp; 228 | value: CyclesAmount; 229 | }; 230 | type CyclesAmount = nat; 231 | type Config = 232 | record { 233 | CYCLES_LIMIT: opt nat; 234 | FEE: opt nat; 235 | ICP_FEE: opt nat64; 236 | ICP_LIMIT: opt nat; 237 | MAX_CACHE_NUMBER_PER: opt nat; 238 | MAX_CACHE_TIME: opt nat; 239 | MAX_STORAGE_TRIES: opt nat; 240 | MIN_CYCLES: opt nat; 241 | MIN_ICP_E8S: opt nat; 242 | STORAGE_CANISTER: opt text; 243 | CYCLESFEE_RETENTION_RATE: opt nat; 244 | }; 245 | type BlockIndex = nat64; 246 | type BalanceChange = 247 | variant { 248 | CreditRecord: nat; 249 | DebitRecord: nat; 250 | NoChange; 251 | }; 252 | type Address = text; 253 | type AccountId = blob; 254 | type CyclesMarket = service { 255 | getAccountId: (Address) -> (text) query; 256 | add: (Address, opt Nonce, opt Data) -> (TxnResult); 257 | remove: (opt Shares, CyclesWallet, opt Nonce, opt Sa, opt Data) -> (TxnResult); 258 | cyclesToIcp: (Address, opt Nonce, opt Data) -> (TxnResult); 259 | icpToCycles: (IcpE8s, CyclesWallet, opt Nonce, opt Sa, opt Data) -> (TxnResult); 260 | claim: (CyclesWallet, opt Nonce, opt Sa, opt Data) -> (TxnResult); 261 | count: (opt Address) -> (nat) query; 262 | canister_status: () -> (canister_status); 263 | feeStatus: () -> (FeeStatus) query; 264 | getConfig: () -> (Config) query; 265 | getEvents: (opt Address) -> (vec TxnRecord) query; 266 | lastTxids: (opt Address) -> (vec Txid) query; 267 | liquidity: (opt Address) -> (Liquidity) query; 268 | lpRewards: (Address) -> (record { cycles: nat; icp: nat;}) query; 269 | txnRecord: (Txid) -> (opt TxnRecord) query; 270 | txnRecord2: (Txid) -> (opt TxnRecord); 271 | yield: () -> (record { apyCycles: float64; apyIcp: float64;}, record {apyCycles: float64; apyIcp: float64;}) query; 272 | version: () -> (text) query; 273 | }; 274 | service : () -> CyclesMarket 275 | -------------------------------------------------------------------------------- /lib/CF.mo: -------------------------------------------------------------------------------- 1 | /** 2 | * Module : CF.mo (CyclesFinance Types) 3 | * Author : ICLight.house Team 4 | * License : GNU General Public License v3.0 5 | * Stability : Experimental 6 | * Canister : 6nmrm-laaaa-aaaak-aacfq-cai 7 | * Website : https://cycles.finance 8 | * Github : https://github.com/iclighthouse/ 9 | */ 10 | 11 | import Time "mo:base/Time"; 12 | import Result "mo:base/Result"; 13 | 14 | module { 15 | public type ICP = { 16 | e8s : Nat64; 17 | }; 18 | public type BlockIndex = Nat64; 19 | public type TransferError = { 20 | #BadFee : { expected_fee : ICP; }; 21 | #InsufficientFunds : { balance: ICP; }; 22 | #TxTooOld : { allowed_window_nanos: Nat64 }; 23 | #TxCreatedInFuture; 24 | #TxDuplicate : { duplicate_of: BlockIndex; }; 25 | }; 26 | public type Timestamp = Nat; // seconds (Time.Time/1000000000) 27 | public type Address = Text; 28 | public type AccountId = Blob; 29 | public type Sa = [Nat8]; 30 | public type CyclesWallet = Principal; 31 | public type CyclesAmount = Nat; 32 | public type IcpE8s = Nat; 33 | public type Shares = Nat; 34 | public type Nonce = Nat; 35 | public type Data = Blob; 36 | public type Txid = Blob; 37 | // type Price = (cycles: Nat, icp: Nat); // x cycles per y icp 38 | public type ShareWeighted = { 39 | shareTimeWeighted: Nat; 40 | updateTime: Timestamp; 41 | }; 42 | public type CumulShareWeighted = Nat; 43 | public type Vol = { 44 | swapCyclesVol: CyclesAmount; 45 | swapIcpVol: IcpE8s; 46 | }; 47 | public type PriceWeighted = { 48 | cyclesTimeWeighted: Nat; // cyclesTimeWeighted += cycles*seconds 49 | icpTimeWeighted: Nat; 50 | updateTime: Timestamp; 51 | }; 52 | public type FeeBalance = { 53 | var cyclesBalance: CyclesAmount; 54 | var icpBalance: IcpE8s; 55 | }; 56 | public type Yield = { 57 | accrued: {cycles: CyclesAmount; icp: IcpE8s;}; 58 | rate: {rateCycles: Nat; rateIcp: Nat; }; // per 1000000 shares 59 | unitValue: {cycles: CyclesAmount; icp: IcpE8s;}; // per 1000000 shares 60 | updateTime: Timestamp; 61 | isClosed: Bool; 62 | }; 63 | public type Liquidity = { 64 | cycles: Nat; 65 | icpE8s: IcpE8s; 66 | shares: Shares; 67 | shareWeighted: ShareWeighted; 68 | unitValue: (cycles: Float, icpE8s: Float); 69 | vol: Vol; 70 | priceWeighted: PriceWeighted; 71 | swapCount: Nat64; 72 | }; 73 | public type FeeStatus = { 74 | fee: Float; 75 | cumulFee: { 76 | cyclesBalance: CyclesAmount; 77 | icpBalance: IcpE8s; 78 | }; 79 | totalFee: { 80 | cyclesBalance: CyclesAmount; 81 | icpBalance: IcpE8s; 82 | }; 83 | }; 84 | public type TransStatus = { 85 | #Processing; 86 | #Success; 87 | #Failure; 88 | #Fallback; 89 | }; 90 | public type IcpTransferLog = {from: AccountId; to: AccountId; value: IcpE8s; fee: IcpE8s; status: TransStatus; updateTime: Timestamp}; 91 | public type CyclesTransferLog = {from: Principal; to: Principal; value: CyclesAmount; status: TransStatus; updateTime: Timestamp}; 92 | public type ErrorLog = { 93 | #IcpSaToMain: { 94 | user: AccountId; 95 | debit: (index: Nat64, sa: AccountId, icp: IcpE8s); 96 | errMsg: TransferError; 97 | time: Timestamp; 98 | }; 99 | #Withdraw: { 100 | user: AccountId; 101 | credit: (cyclesWallet: CyclesWallet, cycles: CyclesAmount, icpAccount: AccountId, icp: IcpE8s); 102 | cyclesErrMsg: Text; 103 | icpErrMsg: ?TransferError; 104 | time: Timestamp; 105 | }; 106 | }; 107 | public type ErrorAction = {#delete; #fallback; #resendIcp; #resendCycles; #resendIcpCycles;}; 108 | 109 | public type Config = { 110 | MIN_CYCLES: ?Nat; 111 | MIN_ICP_E8S: ?Nat; 112 | ICP_FEE: ?Nat64; 113 | FEE: ?Nat; 114 | ICP_LIMIT: ?Nat; 115 | CYCLES_LIMIT: ?Nat; 116 | MAX_CACHE_TIME: ?Nat; 117 | MAX_CACHE_NUMBER_PER: ?Nat; 118 | STORAGE_CANISTER: ?Text; 119 | MAX_STORAGE_TRIES: ?Nat; 120 | CYCLESFEE_RETENTION_RATE: ?Nat; 121 | }; 122 | 123 | public type TokenType = { 124 | #Cycles; 125 | #Icp; 126 | #Token: Principal; 127 | }; 128 | public type OperationType = { 129 | #AddLiquidity; 130 | #RemoveLiquidity; 131 | #Claim; 132 | #Swap; 133 | }; 134 | public type BalanceChange = { 135 | #DebitRecord: Nat; 136 | #CreditRecord: Nat; 137 | #NoChange; 138 | }; 139 | public type ShareChange = { 140 | #Mint: Shares; 141 | #Burn: Shares; 142 | #NoChange; 143 | }; 144 | public type TxnRecord = { 145 | txid: Txid; 146 | msgCaller: ?Principal; 147 | caller: AccountId; 148 | operation: OperationType; 149 | account: AccountId; 150 | cyclesWallet: ?CyclesWallet; 151 | token0: TokenType; 152 | token1: TokenType; 153 | token0Value: BalanceChange; 154 | token1Value: BalanceChange; 155 | fee: {token0Fee: Nat; token1Fee: Nat; }; 156 | shares: ShareChange; 157 | time: Time.Time; 158 | index: Nat; 159 | nonce: Nonce; 160 | orderType: { #AMM; #OrderBook; }; 161 | details: [{counterparty: Txid; token0Value: BalanceChange; token1Value: BalanceChange;}]; 162 | data: ?Data; 163 | }; 164 | public type TxnResult = Result.Result<{ //<#ok, #err> 165 | txid: Txid; 166 | cycles: BalanceChange; 167 | icpE8s: BalanceChange; 168 | shares: ShareChange; 169 | }, { 170 | code: { 171 | #NonceError; 172 | #InvalidCyclesAmout; 173 | #InvalidIcpAmout; 174 | #InsufficientShares; 175 | #PoolIsEmpty; 176 | #IcpTransferException; 177 | #UnacceptableVolatility; 178 | #UndefinedError; 179 | }; 180 | message: Text; 181 | }>; 182 | public type Self = actor { 183 | getAccountId : shared query Address -> async Text; 184 | add : shared (Address, ?Nonce, ?Data) -> async TxnResult; 185 | remove : shared (?Shares, CyclesWallet, ?Nonce, ?Sa, ?Data) -> async TxnResult; 186 | cyclesToIcp : shared (Address, ?Nonce, ?Data) -> async TxnResult; 187 | icpToCycles : shared (IcpE8s, CyclesWallet, ?Nonce, ?Sa, ?Data) -> async TxnResult; 188 | claim : shared (CyclesWallet, ?Nonce, ?Sa, ?Data) -> async TxnResult; 189 | count : shared query ?Address -> async Nat; 190 | feeStatus : shared query () -> async FeeStatus; 191 | getConfig : shared query () -> async Config; 192 | getEvents : shared query ?Address -> async [TxnRecord]; 193 | lastTxids : shared query ?Address -> async [Txid]; 194 | liquidity : shared query ?Address -> async Liquidity; 195 | lpRewards : shared query Address -> async { cycles: Nat; icp: Nat; }; 196 | txnRecord : shared query Txid -> async ?TxnRecord; 197 | txnRecord2 : shared Txid -> async ?TxnRecord; 198 | yield : shared query () -> async (apy24h: { apyCycles: Float; apyIcp: Float; }, apy7d: { apyCycles: Float; apyIcp: Float; }); 199 | version : shared query () -> async Text; 200 | } 201 | } -------------------------------------------------------------------------------- /lib/Tools.mo: -------------------------------------------------------------------------------- 1 | /** 2 | * Module : Tools.mo v 1.0 3 | * Author : Modified by ICLight.house Team 4 | * Stability : Experimental 5 | * Description: Convert subaccount to principal; Convert principal to accoundId. 6 | * Refers : https://github.com/stephenandrews/motoko-accountid 7 | * https://github.com/flyq/ic_codec 8 | */ 9 | 10 | import Prim "mo:⛔"; 11 | import Nat "mo:base/Nat"; 12 | import Nat8 "mo:base/Nat8"; 13 | import Nat32 "mo:base/Nat32"; 14 | import Char "mo:base/Char"; 15 | import Array "mo:base/Array"; 16 | import Text "mo:base/Text"; 17 | import Principal "mo:base/Principal"; 18 | import Option "mo:base/Option"; 19 | import Blob "mo:base/Blob"; 20 | import Iter "mo:base/Iter"; 21 | import P "mo:base/Prelude"; 22 | import SHA224 "./SHA224"; 23 | import BASE32 "./BASE32"; 24 | import CRC32 "./CRC32"; 25 | import Hex "./Hex"; 26 | import Nat16 "mo:base/Nat16"; 27 | import Nat64 "mo:base/Nat64"; 28 | import Binary "Binary"; 29 | //for test 30 | import Time "mo:base/Time"; 31 | import Int "mo:base/Int"; 32 | 33 | module { 34 | 35 | public type PrincipalForm = { 36 | #OpaqueId; //01 37 | #SelfAuthId; //02 38 | #DerivedId; //03 39 | #AnonymousId; //04 40 | #NoneId; //trap 41 | }; 42 | public func slice(a: [T], from: Nat, to: ?Nat): [T]{ 43 | let len = a.size(); 44 | if (len == 0) { return []; }; 45 | var to_: Nat = Option.get(to, Nat.sub(len, 1)); 46 | if (len <= to_){ to_ := len - 1; }; 47 | var na: [T] = []; 48 | var i: Nat = from; 49 | while ( i <= to_ ){ 50 | na := Array.append(na, Array.make(a[i])); 51 | i += 1; 52 | }; 53 | return na; 54 | }; 55 | // principalArr to principalText 56 | public func principalArrToText(pa: [Nat8]) : Text{ 57 | var res: [Nat8] = []; 58 | res := Array.append(res, CRC32.crc32(pa)); 59 | res := Array.append(res, pa); 60 | let s = BASE32.encode(#RFC4648 {padding=false}, res); 61 | let lowercase_s = Text.map(s , Prim.charToLower); 62 | let len = lowercase_s.size(); 63 | let s_slice = Iter.toArray(Text.toIter(lowercase_s)); 64 | var ret = ""; 65 | var i:Nat = 1; 66 | for (v in s_slice.vals()){ 67 | ret := ret # Char.toText(v); 68 | if (i % 5 == 0 and i != len){ 69 | ret := ret # "-"; 70 | }; 71 | i += 1; 72 | }; 73 | return ret; 74 | }; 75 | // principalBlob to principal 76 | public func principalBlobToPrincipal(pb: Blob) : Principal{ 77 | let pa = Blob.toArray(pb); 78 | let text = principalArrToText(pa); 79 | return Principal.fromText(text); 80 | }; 81 | // Generate SubAccount 82 | public func getSubAccount(p: Principal, subIndex: Nat64) : [Nat8]{ 83 | let pa = Blob.toArray(Principal.toBlob(p)); 84 | return subAccount(pa, subIndex: Nat64); 85 | }; 86 | public func subAccount(pa: [Nat8], val: Nat64) : [Nat8]{ 87 | let len = pa.size(); 88 | var res = Array.append([Nat8.fromNat(len)], pa); 89 | let subLength = Nat.sub(31, len); 90 | assert(subLength >= 2); 91 | var suba = Array.init(subLength, 0); 92 | if (subLength < 8){ 93 | let suba16 = Binary.BigEndian.fromNat16(Nat16.fromNat(Nat64.toNat(val))); 94 | for (k in suba.keys()){ 95 | if (k >= Nat.sub(subLength, suba16.size())){ 96 | suba[k] := suba16[k - Nat.sub(subLength, suba16.size())]; 97 | }else{ 98 | suba[k] := 0; 99 | }; 100 | }; 101 | } else{ 102 | let suba64 = Binary.BigEndian.fromNat64(val); 103 | for (k in suba.keys()){ 104 | if (k >= Nat.sub(subLength, suba64.size())){ 105 | suba[k] := suba64[k - Nat.sub(subLength, suba64.size())]; 106 | }else{ 107 | suba[k] := 0; 108 | }; 109 | }; 110 | }; 111 | res := Array.append(res, Array.freeze(suba)); 112 | assert(res.size() == 32); 113 | return res; 114 | }; 115 | //Get SubAccount Index (32 bytes) 116 | public func getSA(subIndex: Nat64) : [Nat8]{ 117 | let sa = Array.init(32, 0); 118 | let sa64 = Binary.BigEndian.fromNat64(subIndex); 119 | for (i in Iter.range(24, 31)){ 120 | sa[i] := sa64[i-24]; 121 | }; 122 | return Array.freeze(sa); 123 | }; 124 | //Convert subaccount to SA(32 bytes) 125 | public func subToSA(a: [Nat8]) : [Nat8] { 126 | let principalLength : Nat = Nat8.toNat(a[0]); 127 | var subIndex : [var Nat8] = Array.init(a.size(), 0); 128 | for (i in Iter.range(0, a.size()-1)) { 129 | if (i <= principalLength){ 130 | subIndex[i] := 0; 131 | }else{ 132 | subIndex[i] := a[i]; 133 | }; 134 | }; 135 | return Array.freeze(subIndex); 136 | }; 137 | //Convert subaccount to principal 138 | public func subToPrincipal(a: [Nat8]) : Principal { 139 | let length : Nat = Nat.min(Nat8.toNat(a[0]), a.size()-1); 140 | var bytes : [var Nat8] = Array.init(length, 0); 141 | for (i in Iter.range(1, length)) { 142 | bytes[i-1] := a[i]; 143 | }; 144 | return Principal.fromText(principalArrToText(Array.freeze(bytes))); 145 | }; 146 | public func subHexToPrincipal(h: Hex.Hex) : Principal { 147 | switch(Hex.decode(h)){ 148 | case (#ok(a)) subToPrincipal(a); 149 | case (#err(e)) P.unreachable(); 150 | } 151 | }; 152 | 153 | //Convert principal to account 154 | private let ads : [Nat8] = [10, 97, 99, 99, 111, 117, 110, 116, 45, 105, 100]; //b"\x0Aaccount-id" 155 | private let sa_zero : [Nat8] = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]; 156 | 157 | public func principalTextToAccount(t : Text, sa : ?[Nat8]) : [Nat8] { 158 | return principalToAccount(Principal.fromText(t), sa); 159 | }; 160 | public func principalToAccount(p : Principal, sa : ?[Nat8]) : [Nat8] { 161 | return principalBlobToAccount(Principal.toBlob(p), sa); 162 | }; 163 | public func principalBlobToAccount(b : Blob, sa : ?[Nat8]) : [Nat8] { //Blob & [Nat8] 164 | return generate(Blob.toArray(b), sa); 165 | }; 166 | private func generate(data : [Nat8], sa : ?[Nat8]) : [Nat8] { 167 | var _sa : [Nat8] = sa_zero; 168 | if (Option.isSome(sa)) { 169 | _sa := Option.get(sa, _sa); 170 | while (_sa.size() < 32){ 171 | _sa := Array.append([0:Nat8], _sa); 172 | }; 173 | }; 174 | var hash : [Nat8] = SHA224.sha224(Array.append(Array.append(ads, data), _sa)); 175 | var crc : [Nat8] = CRC32.crc32(hash); 176 | return Array.append(crc, hash); 177 | }; 178 | // To Account Blob 179 | public func principalTextToAccountBlob(t : Text, sa : ?[Nat8]) : Blob { 180 | return Blob.fromArray(principalTextToAccount(t, sa)); 181 | }; 182 | public func principalToAccountBlob(p : Principal, sa : ?[Nat8]) : Blob { 183 | return Blob.fromArray(principalToAccount(p, sa)); 184 | }; 185 | public func principalBlobToAccountBlob(b : Blob, sa : ?[Nat8]) : Blob { 186 | return Blob.fromArray(principalBlobToAccount(b, sa)); 187 | }; 188 | // To Account Hex 189 | public func principalTextToAccountHex(t : Text, sa : ?[Nat8]) : Hex.Hex { 190 | return Hex.encode(principalTextToAccount(t, sa)); 191 | }; 192 | public func principalToAccountHex(p : Principal, sa : ?[Nat8]) : Hex.Hex { 193 | return Hex.encode(principalToAccount(p, sa)); 194 | }; 195 | public func principalBlobToAccountHex(b : Blob, sa : ?[Nat8]) : Hex.Hex { 196 | return Hex.encode(principalBlobToAccount(b, sa)); 197 | }; 198 | // Account Hex to Account blob 199 | public func accountHexToAccountBlob(h: Hex.Hex) : ?Blob { 200 | let a = Hex.decode(h); 201 | switch (a){ 202 | case (#ok(account:[Nat8])){ 203 | if (isValidAccount(account)){ 204 | return ?(Blob.fromArray(account)); 205 | } else { 206 | return null; 207 | }; 208 | }; 209 | case(#err(_)){ 210 | return null; 211 | } 212 | }; 213 | }; 214 | 215 | //Other principal tools 216 | public func principalForm(p : Principal) : PrincipalForm { 217 | let pArr = Blob.toArray(Principal.toBlob(p)); 218 | if (pArr.size() == 0){ 219 | return #NoneId; 220 | } else { 221 | switch(pArr[pArr.size()-1]){ 222 | case (1) { return #OpaqueId; }; 223 | case (2) { return #SelfAuthId; }; 224 | case (3) { return #DerivedId; }; 225 | case (4) { return #AnonymousId; }; 226 | case (_) { return #NoneId; }; 227 | }; 228 | }; 229 | }; 230 | public func isValidAccount(account: [Nat8]): Bool{ 231 | if (account.size() == 32){ 232 | let checksum = slice(account, 0, ?3); 233 | let hash = slice(account, 4, ?31); 234 | if (Array.equal(CRC32.crc32(hash), checksum, Nat8.equal)){ 235 | return true; 236 | }; 237 | }; 238 | return false; 239 | }; 240 | public func blackhole(): Blob{ 241 | var hash = Array.init(28, 0); 242 | var crc : [Nat8] = CRC32.crc32(Array.freeze(hash)); 243 | return Blob.fromArray(Array.append(crc, Array.freeze(hash))); 244 | }; 245 | // get DRC calldata 246 | public func getDrcCalldata(_data: ?Blob): [Nat8]{ 247 | var data = Blob.toArray(Option.get(_data, Blob.fromArray([]))); 248 | if (data.size() >= 4){ 249 | let protocol = slice(data, 0, ?2); 250 | let version: Nat8 = data[3]; 251 | if (protocol[0] == 68 and protocol[1] == 82 and protocol[2] == 67){ 252 | data := slice(data, 4, null); 253 | }; 254 | }; 255 | return data; 256 | }; 257 | // set DRC calldata 258 | public func setDrcCalldata(_data: [Nat8]): Blob{ 259 | let protocol: [Nat8] = [68,82,67]; //DRC 260 | let version: [Nat8] = [1]; 261 | let data = Array.append(Array.append(protocol, version), _data); 262 | return Blob.fromArray(data); 263 | }; 264 | //for test 265 | public func generateFromNat(n: Nat): Blob{ 266 | var hash = SHA224.sha224(Blob.toArray(Text.encodeUtf8(Nat.toText(n)#Int.toText(Time.now())))); 267 | var crc : [Nat8] = CRC32.crc32(hash); 268 | return Blob.fromArray(Array.append(crc, hash)); 269 | }; 270 | 271 | }; -------------------------------------------------------------------------------- /DRC205Proxy.mo: -------------------------------------------------------------------------------- 1 | /** 2 | * Module : DRC205Proxy.mo 3 | * Author : ICLighthouse Team 4 | * Stability : Experimental 5 | * Canister : 6ylab-kiaaa-aaaak-aacga-cai 6 | * Github : https://github.com/iclighthouse/DRC_standards/ 7 | */ 8 | import Prim "mo:⛔"; 9 | import Principal "mo:base/Principal"; 10 | import Array "mo:base/Array"; 11 | import Nat32 "mo:base/Nat32"; 12 | import Blob "mo:base/Blob"; 13 | import Option "mo:base/Option"; 14 | import Time "mo:base/Time"; 15 | import Hash "mo:base/Hash"; 16 | import Binary "./lib/Binary"; 17 | import SHA224 "./lib/SHA224"; 18 | import Tools "./lib/Tools"; 19 | import Bloom "./lib/Bloom"; 20 | import Deque "mo:base/Deque"; 21 | import List "mo:base/List"; 22 | import Trie "mo:base/Trie"; 23 | import TrieMap "mo:base/TrieMap"; 24 | import Cycles "mo:base/ExperimentalCycles"; 25 | import CyclesWallet "./sys/CyclesWallet"; 26 | import SwapRecord "./lib/SwapRecord"; 27 | import DRC205 "./lib/DRC205"; 28 | import DRC205Bucket "DRC205Bucket"; 29 | import DRC207 "./lib/DRC207"; 30 | 31 | shared(installMsg) actor class ProxyActor() = this { 32 | type Bucket = SwapRecord.Bucket; 33 | type BucketInfo = SwapRecord.BucketInfo; 34 | type AppId = SwapRecord.AppId; 35 | type AppInfo = SwapRecord.AppInfo; 36 | type AppCertification = SwapRecord.AppCertification; 37 | type Txid = SwapRecord.Txid; 38 | type Sid = SwapRecord.Sid; 39 | type AccountId = SwapRecord.AccountId; 40 | type TxnRecord = SwapRecord.TxnRecord; 41 | type BloomFilter = Bloom.AutoScalingBloomFilter; 42 | type DataType = { 43 | #Txn: TxnRecord; 44 | #Bytes: {txid: Txid; data: [Nat8]}; 45 | }; 46 | 47 | private var version_: Nat8 = 1; 48 | private var bucketCyclesInit: Nat = 200000000000; 49 | private var maxStorageTries: Nat = 3; 50 | private stable var owner: Principal = installMsg.caller; 51 | private stable var fee_: Nat = 100000000; //cycles 52 | private stable var maxMemory: Nat = 3900 * 1024 * 1024; //3.8GB 53 | private stable var bucketCount: Nat = 0; 54 | private stable var appCount: Nat = 0; 55 | private stable var txnCount: Nat = 0; 56 | private stable var errCount: Nat = 0; 57 | private stable var lastTxns = Deque.empty<(index: Nat, app: AppId, indexInApp: Nat, txid: Txid)>(); 58 | private stable var currentBucket: [(Bucket, BucketInfo)] = []; 59 | private stable var buckets: [Bucket] = []; 60 | private var blooms = TrieMap.TrieMap(Principal.equal, Principal.hash); 61 | private stable var bloomsEntries : [(Bucket, [[Nat8]])] = []; // for upgrade 62 | private stable var apps: Trie.Trie = Trie.empty(); 63 | private stable var storeTxns = List.nil<(AppId, DataType, Nat)>(); 64 | private stable var storeErrPool = List.nil<(AppId, DataType, Nat)>(); 65 | // TODO private stable var certifications: Trie.Trie = Trie.empty(); 66 | 67 | private func _onlyOwner(_caller: Principal) : Bool { 68 | return _caller == owner; 69 | }; 70 | private func keyb(t: Blob) : Trie.Key { return { key = t; hash = Blob.hash(t) }; }; 71 | private func keyp(t: Principal) : Trie.Key { return { key = t; hash = Principal.hash(t) }; }; 72 | private func _newBucket() : async Bucket { 73 | Cycles.add(bucketCyclesInit); 74 | let bucketActor = await DRC205Bucket.BucketActor(); 75 | let bucket: Bucket = Principal.fromActor(bucketActor); 76 | let bucketInfo: BucketInfo = await bucketActor.bucketInfo(); 77 | buckets := Array.append(buckets, [bucket]); 78 | currentBucket := [(bucket, bucketInfo)]; 79 | blooms.put(bucket, Bloom.AutoScalingBloomFilter(100000, 0.002, Bloom.blobHash)); 80 | bucketCount += 1; 81 | return bucket; 82 | }; 83 | private func _getBucket() : async Bucket{ 84 | if (currentBucket.size() > 0){ 85 | var bucket: Bucket = currentBucket[0].0; 86 | let bucketActor: DRC205Bucket.BucketActor = actor(Principal.toText(bucket)); 87 | let bucketInfo: BucketInfo = await bucketActor.bucketInfo(); 88 | currentBucket := [(bucket, bucketInfo)]; 89 | if (bucketInfo.cycles < bucketCyclesInit/2){ 90 | Cycles.add(bucketCyclesInit); 91 | let res = /*await*/ bucketActor.wallet_receive(); 92 | }; 93 | if (bucketInfo.memory >= maxMemory){ 94 | bucket := await _newBucket(); 95 | }; 96 | return bucket; 97 | } else { 98 | return await _newBucket(); 99 | }; 100 | }; 101 | private func _pushLastTxns(_app: AppId, _data: DataType) : (){ 102 | switch(_data){ 103 | case(#Txn(txn)){ 104 | lastTxns := Deque.pushFront(lastTxns, (txnCount, _app, txn.index, txn.txid)); 105 | }; 106 | case(#Bytes(txn)){ 107 | lastTxns := Deque.pushFront(lastTxns, (txnCount, _app, 0, txn.txid)); 108 | }; 109 | }; 110 | var size = List.size(lastTxns.0) + List.size(lastTxns.1); 111 | while (size > 200){ 112 | size -= 1; 113 | switch (Deque.popBack(lastTxns)){ 114 | case(?(q, v)){ 115 | lastTxns := q; 116 | }; 117 | case(_){}; 118 | }; 119 | }; 120 | }; 121 | private func _putApp(_app: AppId, _data: DataType) : (){ 122 | var _count: Nat = 0; 123 | switch(Trie.get(apps, keyp(_app), Principal.equal)){ 124 | case(?(info)){ 125 | _count := info.count+1; 126 | }; 127 | case(_){ 128 | _count := 1; 129 | appCount += 1; 130 | }; 131 | }; 132 | switch(_data){ 133 | case(#Txn(_txn)){ 134 | apps := Trie.put(apps, keyp(_app), Principal.equal, { 135 | lastIndex = _txn.index; 136 | lastTxid = _txn.txid; 137 | count = _count; 138 | }).0; 139 | }; 140 | case(#Bytes(txn)){ 141 | apps := Trie.put(apps, keyp(_app), Principal.equal, { 142 | lastIndex = 0; 143 | lastTxid = txn.txid; 144 | count = _count; 145 | }).0; 146 | }; 147 | }; 148 | }; 149 | private func _addBloom(_bucket: Bucket, _sid: Sid) : (){ 150 | switch(blooms.get(_bucket)){ 151 | case(?(bloom)){ 152 | bloom.add(_sid); 153 | blooms.put(_bucket, bloom); 154 | }; 155 | case(_){ 156 | let bloom = Bloom.AutoScalingBloomFilter(100000, 0.002, Bloom.blobHash); 157 | bloom.add(_sid); 158 | blooms.put(_bucket, bloom); 159 | }; 160 | }; 161 | }; 162 | private func _checkBloom(_sid: Sid, _step: Nat) : ?Bucket{ 163 | var step: Nat = 0; 164 | for ((bucket, bloom) in blooms.entries()){ 165 | if (step < _step and bloom.check(_sid)){ 166 | step += 1; 167 | }else if (step == _step and bloom.check(_sid)){ 168 | return ?bucket; 169 | }; 170 | }; 171 | return null; 172 | }; 173 | private func _execStorage() : async (){ 174 | let bucket: Bucket = await _getBucket(); 175 | let bucketActor: DRC205Bucket.BucketActor = actor(Principal.toText(bucket)); 176 | var _storeTxns = List.nil<(AppId, DataType, Nat)>(); 177 | var item = List.pop(storeTxns); 178 | while (Option.isSome(item.0)){ 179 | switch(item.0){ 180 | case(?(app, dataType, callCount)){ 181 | if (callCount < maxStorageTries){ 182 | try{ 183 | switch(dataType){ 184 | case(#Txn(txn)){ 185 | let sid = SwapRecord.generateSid(app, txn.txid); 186 | await bucketActor.store(sid, txn); 187 | _addBloom(bucket, sid); 188 | }; 189 | case(#Bytes(txn)){ 190 | let sid = SwapRecord.generateSid(app, txn.txid); 191 | await bucketActor.storeBytes(sid, txn.data); 192 | _addBloom(bucket, sid); 193 | }; 194 | }; 195 | _putApp(app, dataType); 196 | _pushLastTxns(app, dataType); 197 | txnCount += 1; 198 | } catch(e){ //push 199 | errCount += 1; 200 | _storeTxns := List.push((app, dataType, callCount+1), _storeTxns); 201 | }; 202 | } else { 203 | storeErrPool := List.push((app, dataType, 0), storeErrPool); 204 | }; 205 | }; 206 | case(_){}; 207 | }; 208 | item := List.pop(item.1); 209 | }; 210 | storeTxns := _storeTxns; 211 | }; 212 | private func _reExecStorage() : async (){ 213 | var item = List.pop(storeErrPool); 214 | while (Option.isSome(item.0)){ 215 | switch(item.0){ 216 | case(?(v)){ 217 | storeTxns := List.push(v, storeTxns); 218 | }; 219 | case(_){}; 220 | }; 221 | item := List.pop(item.1); 222 | }; 223 | await _execStorage(); 224 | }; 225 | 226 | public query func generateTxid(_app: Principal, _caller: AccountId, _nonce: Nat): async Txid{ 227 | return DRC205.generateTxid(_app, _caller, _nonce); 228 | }; 229 | 230 | 231 | public query func version() : async Nat8{ 232 | return version_; 233 | }; 234 | public query func fee() : async (cycles: Nat){ 235 | return fee_; 236 | }; 237 | public query func maxBucketMemory() : async (memory: Nat){ 238 | return maxMemory; 239 | }; 240 | public query func stats() : async {bucketCount: Nat; appCount: Nat; txnCount: Nat; errCount: Nat; storeErrPool: Nat}{ 241 | return { 242 | bucketCount = bucketCount; 243 | appCount = appCount; 244 | txnCount = txnCount; 245 | errCount = errCount; 246 | storeErrPool = List.size(storeErrPool); 247 | }; 248 | }; 249 | public /*query*/ func bucketInfo(_bucket: ?Bucket) : async (Bucket, BucketInfo){ 250 | switch(_bucket){ 251 | case(?(bucket)){ 252 | let bucketActor: DRC205Bucket.BucketActor = actor(Principal.toText(bucket)); 253 | return (bucket, await bucketActor.bucketInfo()); 254 | }; 255 | case(_){ 256 | return currentBucket[0]; 257 | }; 258 | }; 259 | }; 260 | public query func appInfo(_app: AppId) : async ?AppInfo{ 261 | return Trie.get(apps, keyp(_app), Principal.equal); 262 | }; 263 | public query func getLastTxns() : async [(index: Nat, app: AppId, indexInApp: Nat, txid: Txid)]{ 264 | var l = List.append(lastTxns.0, List.reverse(lastTxns.1)); 265 | return List.toArray(l); 266 | }; 267 | public shared(msg) func store(_txn: TxnRecord) : async (){ 268 | let amout = Cycles.available(); 269 | assert(amout >= fee_ or _onlyOwner(msg.caller)); 270 | let accepted = Cycles.accept(fee_); 271 | let app: AppId = msg.caller; 272 | storeTxns := List.push((app, #Txn(_txn), 0), storeTxns); 273 | await _execStorage(); 274 | }; 275 | public shared(msg) func storeBytes(_txid: Txid, _data: [Nat8]) : async (){ 276 | assert(_data.size() <= 128 * 1024); // 128 KB 277 | let amout = Cycles.available(); 278 | assert(amout >= fee_ or _onlyOwner(msg.caller)); 279 | let accepted = Cycles.accept(fee_); 280 | let _app: AppId = msg.caller; 281 | storeTxns := List.push((_app, #Bytes({txid = _txid; data = _data;}), 0), storeTxns); 282 | await _execStorage(); 283 | }; 284 | public query func bucket(_app: Principal, _txid: Txid, _step: Nat, _version: ?Nat8) : async (bucket: ?Principal){ 285 | let _sid = SwapRecord.generateSid(_app, _txid); 286 | return _checkBloom(_sid, _step); 287 | }; 288 | 289 | /* 290 | * Owner's Management 291 | */ 292 | public query func getOwner() : async Principal{ 293 | return owner; 294 | }; 295 | public shared(msg) func changeOwner(_newOwner: Principal) : async Bool{ 296 | assert(_onlyOwner(msg.caller)); 297 | owner := _newOwner; 298 | return true; 299 | }; 300 | public shared(msg) func setFee(_fee: Nat) : async Bool{ 301 | assert(_onlyOwner(msg.caller)); 302 | fee_ := _fee; 303 | return true; 304 | }; 305 | public shared(msg) func setMaxMemory(_memory: Nat) : async Bool{ 306 | assert(_onlyOwner(msg.caller)); 307 | maxMemory := _memory; 308 | return true; 309 | }; 310 | public shared(msg) func reStore() : async (){ 311 | assert(_onlyOwner(msg.caller)); 312 | await _reExecStorage(); 313 | }; 314 | public shared(msg) func clearStoreErrPool() : async (){ 315 | assert(_onlyOwner(msg.caller)); 316 | storeErrPool := List.nil<(AppId, DataType, Nat)>(); 317 | }; 318 | // receive cycles 319 | public func wallet_receive(): async (){ 320 | let amout = Cycles.available(); 321 | let accepted = Cycles.accept(amout); 322 | }; 323 | //cycles withdraw 324 | public shared(msg) func cyclesWithdraw(_wallet: Principal, _amount: Nat): async (){ 325 | assert(_onlyOwner(msg.caller)); 326 | let cyclesWallet: CyclesWallet.Self = actor(Principal.toText(_wallet)); 327 | let balance = Cycles.balance(); 328 | var value: Nat = _amount; 329 | if (balance <= _amount) { 330 | value := balance; 331 | }; 332 | Cycles.add(value); 333 | await cyclesWallet.wallet_receive(); 334 | //Cycles.refunded(); 335 | }; 336 | /// canister memory 337 | public query func getMemory() : async (Nat,Nat,Nat,Nat32){ 338 | return (Prim.rts_memory_size(), Prim.rts_heap_size(), Prim.rts_total_allocation(),Prim.stableMemorySize()); 339 | }; 340 | /// canister cycles 341 | public query func getCycles() : async Nat{ 342 | return return Cycles.balance(); 343 | }; 344 | 345 | // DRC207 ICMonitor 346 | /// DRC207 support 347 | public func drc207() : async DRC207.DRC207Support{ 348 | return { 349 | monitorable_by_self = true; 350 | monitorable_by_blackhole = { allowed = true; canister_id = ?Principal.fromText("7hdtw-jqaaa-aaaak-aaccq-cai"); }; 351 | cycles_receivable = true; 352 | timer = { enable = false; interval_seconds = null; }; 353 | }; 354 | }; 355 | /// canister_status 356 | public func canister_status() : async DRC207.canister_status { 357 | let ic : DRC207.IC = actor("aaaaa-aa"); 358 | await ic.canister_status({ canister_id = Principal.fromActor(this) }); 359 | }; 360 | /// receive cycles 361 | // public func wallet_receive(): async (){ 362 | // let amout = Cycles.available(); 363 | // let accepted = Cycles.accept(amout); 364 | // }; 365 | /// timer tick 366 | // public func timer_tick(): async (){ 367 | // // 368 | // }; 369 | 370 | /* 371 | * upgrade functions 372 | */ 373 | system func preupgrade() { 374 | var size : Nat = blooms.size(); 375 | var temp : [var (Bucket, [[Nat8]])] = Array.init<(Bucket, [[Nat8]])>(size, (owner, [])); 376 | size := 0; 377 | for ((k, v) in blooms.entries()) { 378 | temp[size] := (k, v.getBitMap()); 379 | size += 1; 380 | }; 381 | bloomsEntries := Array.freeze(temp); 382 | }; 383 | 384 | system func postupgrade() { 385 | for ((k, v) in bloomsEntries.vals()) { 386 | let temp = Bloom.AutoScalingBloomFilter(100000, 0.002, Bloom.blobHash); 387 | temp.setData(v); 388 | blooms.put(k, temp); 389 | }; 390 | }; 391 | } 392 | -------------------------------------------------------------------------------- /README中文.md: -------------------------------------------------------------------------------- 1 | # Cycles.Finance 2 | 3 | **Website**: http://cycles.finance 4 | **Canister Id**: 6nmrm-laaaa-aaaak-aacfq-cai 5 | **Module hash**: 070a8e3cfb65204e29241278f19c5c440dabfbf6913e080441e647759102847e 6 | **Version**: 0.6 7 | 8 | ### 申明: 9 | 10 | 项目正处于测试期,可能存在缺陷。这是一个Dapp,请了解相关知识,并自愿参与,自行承担所有风险。 11 | 12 | ## 概述 13 | 14 | Cycles.Finance是一个ICP/Cycles去中心化市场,支持ICP、Cycles的双向兑换,采用乘法恒定K模型(A*B=K),类似UniSwapV2。 15 | 16 | #### 交易限制 17 | 18 | 项目仍然处于测试期,为了控制风险,对单笔交易进行了限额。 19 | - ICP:单笔交易最大10 icp,最小10000 e8s。 20 | - Cycles:最大3*10^14 cycles,最小10^8 cycles。 21 | - 交易波动性限制:单笔交易引起价格波动超过20%会被拒绝。 22 | 23 | #### 交易费用 24 | 25 | 交易费:1%,采取后收费模式,收取ICP或者Cycles。 26 | ICP转账费用: 每笔ICP转账被IC网络收取10000 e8s。 27 | 交易费用途:收取的ICP全部进入流动性奖励池,收取的Cycles的80%进入流动性奖励池(另外20%用于Canister的消耗)。 28 | 29 | #### 流动性做市 30 | 31 | 做市模型:AMM自动做市模型。采用乘法恒定K模型(AB=K)。 32 | 33 | #### 流动性做市收益 34 | 35 | - 流动性提供者(LP)按照持有份额的平均分配流动性奖励池资产,LP可以随时提取(Claim)奖励收益。 36 | - [计划] 参与ICLighthouse流动性挖矿计划,获得ICL代币奖励。 37 | 38 | 注意:参与流动性做市,需要添加ICP和Cycles两种资产到流动池,这两项资产的数量随着用户交易而发生变化。例如你添加了1 ICP和30 TCycles进入流动池,过一段时间后提取出来可能是0.9 ICP和33.3 TCycles. 39 | 40 | 41 | ## 它是如何工作的? 42 | 43 | CyclesFinance旨在以不同于传统交易所的方式进行ICP和Cycles的互换。 44 | 45 | 它通过使用Canister智能合约来做到这一点,允许用户(称为流动性提供者)将ICP和Cycles存入池中。智能合约允许交易者购买和出售这些资产。交易这些资产的用户支付交易费用,该费用按比例分配给所有流动性提供者(基于他们对资产池的贡献)。 46 | 47 | ![image](cf-swap.png) 48 | 49 | **流动性池** 50 | 51 | 流动性池持有ICP和Cycles,它们组成该资产池的交易对。 52 | 53 | CyclesFinance使用一种叫做 "乘法常数k做市商模型 "的定价机制。该公式(A * B = k)用于确定交易对的价格。 54 | A和B代表两种资产的池子余额,而k是池子的总恒定价格。 55 | 在流动性池中,第一个流动性提供者通过向两个代币提供同等价值来设定池中资产的初始价格。 56 | 57 | **交易** 58 | 59 | 然后,买方可以根据公式,在池内交易ICP/Cycles。运行该规则的智能合约使用上述公式,从买方那里获取一种资产的数量,并将另一种资产的同等数量送回给买方,保持总池的稳定(k)。 60 | 61 | **例子** 62 | 63 | 假设ICP/Cycles流动性池包含10个ICP(A)和300个TCycles(B),因此池子的恒定值为3000(k)。 64 | 这意味着池子的起始价格是30TCycles每个ICP。 65 | 66 | 现在,让我们想象一下,一个交易者进来,想买0.1个ICP。 67 | 68 | 交易后,ICP/Cycles池将有: 69 | 70 | 新A: 9.9 ICP (10 - 0.1) 71 | k: 3000 (保持不变) 72 | 新B:303.03TCycles (3000 / 9.9) 73 | 因此,为了保持k不变,这意味着每个ICP的价格为30.303TCycles,因为交易者必须在池子里增加3.03TCycles(303.03TCycles-300TCycles)来购买0.1ICP。 74 | 75 | 在上面的例子中,如果有人再购买0.1 ICP,ICP的下一个隐含价格将是每个ICP的30.609TCycles(303.03TCycles/9.9ICP)左右。 76 | 77 | 当一种资产的价格开始偏离市场价格进行交易时,套利者认为这是一个赚取无风险收益的机会。因此,他们进来交易,使价格回到市场价格。这是ICP/Cycles生态系统的一个重要部分。 78 | 79 | 80 | ## 技术特性 81 | 82 | #### 实现最终一致性 83 | 84 | CyclesFinance面临的原子性问题主要有ICP内部转账和Cycles发送在异步过程中失败问题,我们采取了最大努力处理(Best Effort Commit)策略加上错误处理机制来保障最终一致性。 85 | 86 | 具体做法是: 87 | - 在更新状态变量前,遇到异常则报错拒绝交易; 88 | - 已经有状态变量更新的情况下,确保本合约内部的状态变量能成功保存,外部调用采取了最大努力处理(Best Effort Commit)策略,但要防止重复交易,所以加入了错误处理机制; 89 | - 对于异常错误,需要管理者或者治理合约触发重发交易。对于无法接收Cycles的账户,管理者或者治理合约可以修改接收账户。 90 | 91 | #### 支持幂等性 92 | 93 | 外部应用调用CyclesFinance遇到错误时,如果需要重复发送交易,可以避免重复交易的情况发生。 94 | - 交易txid是可计算的,并全局唯一。 95 | - 支持账户的nonce机制。 96 | 97 | #### Oracle报价支持 98 | 99 | ICP/Cycles交易形成的价格,可以作为IC网络上原生Oracle使用。CyclesFinance提供两种形式的Oracle价格,包括: 100 | - 最新价格:通过CyclesFinance容器的liquidity(null)方法查询,返回值中cycles / icp.e8s 即表示每e8s多少cycles。 101 | - 时间加权价格:通过CyclesFinance容器的liquidity(null)方法查询,返回值中icpTimeWeighted表示icp的时间加权累计值,cyclesTimeWeighted表示cycles的时间加权累计值。可供外部用于各种时间加权价格的计算。 102 | ![image](cf-priceweighted.png) 103 | 104 | #### 流动性挖矿支持 105 | 106 | CyclesFinance可以为流动性挖矿合约提供数据依据,为社区治理和项目经济模型提供创新空间。通过CyclesFinance容器的liquidity(null)方法查询,返回值中shareTimeWeighted表示全局的流动性池份额的时间加权累计值。 107 | ![image](cf-shareweighted.png) 108 | 109 | #### 交易挖矿支持 110 | 111 | CyclesFinance可以为交易挖矿提供数据依据,为社区治理和项目经济模型提供创新空间。通过CyclesFinance容器的liquidity()方法查询,返回值中vol值表示全局或账户的交易量累计值。 112 | 113 | #### 可扩展性存储 114 | 115 | CyclesFinance容器只存储近期交易记录,通过外部可扩展容器持久化存储交易记录,确保CyclesFinance能支撑大规模应用场景。 116 | 117 | 118 | 119 | ## 使用(命令行界面) 120 | 121 | **Notes** 122 | - UI交互界面请使用:http://cycles.finance 123 | - ICP在本合约的基本单位是e8s,1 icp = 10^8 e8s; 124 | - IC网络的Cycles汇率会动态变化,盯住XDR价值,1 XDR = 10^12 cycles (价值约1.4 USD); 125 | - 本合约的ICP/Cycles汇率由市场自动形成,与其他市场可能存在偏差; 126 | - 与本合约交互需要使用你的`ICP账户Principal`和`Cycles钱包账户Principal`,请注意两者区别。 127 | 128 | ### 查询ICP/Cycles兑换比例 129 | ```` 130 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai liquidity '(null)' 131 | ```` 132 | 返回值中的`cycles`(或`2_190_693_645`)字段 除以 `icpE8s`(或`1_180_746_538`)字段,就表示当前1个e8s可以兑换多少个cycles,乘以10^8就表示1个icp可以兑换多少个cycles,这是个估算值。 133 | ```` 134 | ( 135 | record { 136 | icpE8s = 48_521_783 : nat; 137 | vol = record { 138 | swapIcpVol = 1_740_878 : nat; 139 | swapCyclesVol = 573_069_740_022 : nat; 140 | }; 141 | shareWeighted = record { 142 | updateTime = 1_638_592_854 : nat; 143 | shareTimeWeighted = 3_894_326_391_123 : nat; 144 | }; 145 | unitValue = record { 329155.999121 : float64; 0.972376 : float64 }; 146 | shares = 809_508_285 : nat; 147 | cycles = 266_454_525_225_963 : nat; 148 | priceWeighted = record { 149 | updateTime = 1_638_592_854 : nat; 150 | icpTimeWeighted = 3_800_565_037_457 : nat; 151 | cyclesTimeWeighted = 1_277_301_377_584_917_917 : nat; 152 | }; 153 | swapCount = 0 : nat64; 154 | }, 155 | ) 156 | ```` 157 | 158 | ### ICP兑换成Cycles(icpToCycles) 159 | 160 | Step1: 获取你专用的ICP充值地址(称之为**DepositAccountId**) 161 | ```` 162 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai getAccountId '("")' 163 | ```` 164 | 返回`DepositAccountId`(示例) 165 | ```` 166 | ("f2d1945ebc293bdc2cc6ef**************e84cf61f51ce6798fc4283") 167 | ```` 168 | 169 | Step2: 向`DepositAccountId`发送ICP 170 | ```` 171 | dfx ledger --network ic transfer --memo 0 --e8s 172 | ```` 173 | 174 | Step3: 提取Cycles,参数`icp_e8s_amount`输入在Step2中发送的数量,`your_cycles_wallet_principal`输入你的cycles钱包的Principal(注意:不是你的ICP账户)。 175 | ```` 176 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai icpToCycles '(:nat, principal "", null, null, null)' 177 | ```` 178 | 查看你账户的余额变化 179 | ```` 180 | dfx wallet --network ic balance 181 | ```` 182 | 183 | ### Cycles兑换成ICP(cyclesToIcp) 184 | 185 | Step1: 使用didc工具编码参数。注:didc工具地址:https://github.com/dfinity/candid/tree/master/tools/didc 186 | ```` 187 | didc encode '("",null,null)' -t '(text,opt nat,opt blob)' -f blob 188 | ```` 189 | 返回`CallArgs`(示例) 190 | ```` 191 | blob "DIDL\02n\01m{\02h\00\01\**************\88\01\e1\18\fd6G\02\00" 192 | ```` 193 | 194 | Step2: 兑换成ICP。参数`cycles_amount`输入你想用于兑换的cycles数量,参数`call_args`输入Step1得到的`CallArgs` 195 | ```` 196 | dfx canister --network ic call wallet_call '(record {canister=principal "6nmrm-laaaa-aaaak-aacfq-cai"; method_name="cyclesToIcp"; cycles=:nat64; args=})' 197 | ```` 198 | 查看你账户的余额变化 199 | ```` 200 | dfx ledger --network ic balance 201 | ```` 202 | 203 | ### 添加流动性(add) 204 | 205 | 添加流动性操作,需要同时向流动性池子加入ICP和Cycles,比例根据当前价格计算,多余部分会退回。 206 | 207 | Step1: 获取你专用的ICP充值地址(称之为**DepositAccountId**) 208 | ```` 209 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai getAccountId '("")' 210 | ```` 211 | 返回(示例) 212 | ```` 213 | ("f2d1945ebc293bdc2cc6ef**************e84cf61f51ce6798fc4283") 214 | ```` 215 | 216 | Step2: 向`DepositAccountId`发送ICP 217 | ```` 218 | dfx ledger --network ic transfer --memo 0 --e8s 219 | ```` 220 | 221 | Step3: 使用didc工具编码参数。注:didc工具地址:https://github.com/dfinity/candid/tree/master/tools/didc 222 | ```` 223 | didc encode '("",null,null)' -t '(text,opt nat,opt blob)' -f blob 224 | ```` 225 | 返回`CallArgs`(示例) 226 | ```` 227 | blob "DIDL\02n\01m{\02h\00\01\**************\88\01\e1\18\fd6G\02\00" 228 | ```` 229 | 230 | Step4: 发送Cycles,添加流动性。需要指定发送的Cycles数量,并填入Step3得到的`CallArgs` 231 | ```` 232 | dfx canister --network ic call wallet_call '(record {canister=principal "6nmrm-laaaa-aaaak-aacfq-cai"; method_name="add"; cycles=:nat64; args=})' 233 | ```` 234 | 235 | Step5: 查询持有流动性份额 236 | ```` 237 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai liquidity '(opt "")' 238 | ```` 239 | 返回(示例) 240 | ```` 241 | ( 242 | record { 243 | icpE8s = 48_521_783 : nat; 244 | vol = record { 245 | swapIcpVol = 1_648_218 : nat; 246 | swapCyclesVol = 541_650_948_359 : nat; 247 | }; 248 | shareWeighted = record { 249 | updateTime = 1_638_528_867 : nat; 250 | shareTimeWeighted = 695_045_889_662 : nat; 251 | }; 252 | unitValue = record { 329748.544469 : float64; 0.970629 : float64 }; 253 | shares = 49_990_000 : nat; 254 | cycles = 16_484_143_085_896 : nat; 255 | priceWeighted = record { 256 | updateTime = 1_638_528_867 : nat; 257 | icpTimeWeighted = 689_683_291_306 : nat; 258 | cyclesTimeWeighted = 224_229_508_922_468_505 : nat; 259 | }; 260 | swapCount = 0 : nat64; 261 | }, 262 | ) 263 | ```` 264 | 265 | ### 提取流动性(remove) 266 | 267 | Step1: 查询自己的流动性份额,返回值中的`shares`(或`489_381_556`)字段为当前所占份额。 268 | 269 | ```` 270 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai liquidity '(opt "")' 271 | ```` 272 | 273 | Step2: 提取流动性. 参数`share_amount`必须是等于或小于Step1查询到的数值, 参数`your_cycles_wallet_principal`用于接收cycles。 274 | 275 | ```` 276 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai remove '(opt :opt nat, principal "", null, null, null)' 277 | ```` 278 | 查看你账户的余额变化 279 | ```` 280 | dfx ledger --network ic balance 281 | dfx wallet --network ic balance 282 | ```` 283 | 284 | ### 提取流动性做市收益(claim) 285 | 286 | 提取收益。需指定`your_cycles_wallet_principal` 287 | ```` 288 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai claim '(principal "", null, null, null)' 289 | ```` 290 | 查看你账户的余额变化 291 | ```` 292 | dfx ledger --network ic balance 293 | dfx wallet --network ic balance 294 | ```` 295 | 296 | ## did文件 297 | 298 | ```` 299 | type definite_canister_settings = 300 | record { 301 | compute_allocation: nat; 302 | controllers: vec principal; 303 | freezing_threshold: nat; 304 | memory_allocation: nat; 305 | }; 306 | type canister_status = 307 | record { 308 | cycles: nat; 309 | memory_size: nat; 310 | module_hash: opt vec nat8; 311 | settings: definite_canister_settings; 312 | status: variant { 313 | running; 314 | stopped; 315 | stopping; 316 | }; 317 | }; 318 | type Vol = 319 | record { 320 | swapCyclesVol: CyclesAmount; 321 | swapIcpVol: IcpE8s; 322 | }; 323 | type TxnResult = 324 | variant { 325 | err: 326 | record { 327 | code: 328 | variant { 329 | IcpTransferException; 330 | InsufficientShares; 331 | InvalidCyclesAmout; 332 | InvalidIcpAmout; 333 | NonceError; 334 | PoolIsEmpty; 335 | UnacceptableVolatility; 336 | UndefinedError; 337 | }; 338 | message: text; 339 | }; 340 | ok: 341 | record { 342 | cycles: BalanceChange; 343 | icpE8s: BalanceChange; 344 | shares: ShareChange; 345 | txid: Txid; 346 | }; 347 | }; 348 | type TxnRecord = 349 | record { 350 | account: AccountId; 351 | caller: AccountId; 352 | cyclesWallet: opt CyclesWallet; 353 | data: opt Data; 354 | details: 355 | vec 356 | record { 357 | counterparty: Txid; 358 | token0Value: BalanceChange; 359 | token1Value: BalanceChange; 360 | }; 361 | fee: record { 362 | token0Fee: nat; 363 | token1Fee: nat; 364 | }; 365 | index: nat; 366 | msgCaller: opt principal; 367 | nonce: Nonce; 368 | operation: OperationType; 369 | orderType: variant { 370 | AMM; 371 | OrderBook; 372 | }; 373 | shares: ShareChange; 374 | time: Time; 375 | token0: TokenType; 376 | token0Value: BalanceChange; 377 | token1: TokenType; 378 | token1Value: BalanceChange; 379 | txid: Txid; 380 | }; 381 | type Txid = blob; 382 | type TransferError = 383 | variant { 384 | BadFee: record {expected_fee: ICP;}; 385 | InsufficientFunds: record {balance: ICP;}; 386 | TxCreatedInFuture; 387 | TxDuplicate: record {duplicate_of: BlockIndex;}; 388 | TxTooOld: record {allowed_window_nanos: nat64;}; 389 | }; 390 | type TransStatus = 391 | variant { 392 | Failure; 393 | Fallback; 394 | Processing; 395 | Success; 396 | }; 397 | type TokenType = 398 | variant { 399 | Cycles; 400 | Icp; 401 | Token: principal; 402 | }; 403 | type Timestamp = nat; 404 | type Time = int; 405 | type Shares = nat; 406 | type ShareWeighted = 407 | record { 408 | shareTimeWeighted: nat; 409 | updateTime: Timestamp; 410 | }; 411 | type ShareChange = 412 | variant { 413 | Burn: Shares; 414 | Mint: Shares; 415 | NoChange; 416 | }; 417 | type Sa = vec nat8; 418 | type PriceWeighted = 419 | record { 420 | cyclesTimeWeighted: nat; 421 | icpTimeWeighted: nat; 422 | updateTime: Timestamp; 423 | }; 424 | type OperationType = 425 | variant { 426 | AddLiquidity; 427 | Claim; 428 | RemoveLiquidity; 429 | Swap; 430 | }; 431 | type Nonce = nat; 432 | type Liquidity = 433 | record { 434 | cycles: nat; 435 | icpE8s: IcpE8s; 436 | priceWeighted: PriceWeighted; 437 | shareWeighted: ShareWeighted; 438 | shares: Shares; 439 | swapCount: nat64; 440 | unitValue: record { 441 | float64; 442 | float64; 443 | }; 444 | vol: Vol; 445 | }; 446 | type IcpTransferLog = 447 | record { 448 | fee: IcpE8s; 449 | from: AccountId; 450 | status: TransStatus; 451 | to: AccountId; 452 | updateTime: Timestamp; 453 | value: IcpE8s; 454 | }; 455 | type IcpE8s = nat; 456 | type ICP = record {e8s: nat64;}; 457 | type FeeStatus = 458 | record { 459 | cumulFee: record { 460 | cyclesBalance: CyclesAmount; 461 | icpBalance: IcpE8s; 462 | }; 463 | fee: float64; 464 | totalFee: record { 465 | cyclesBalance: CyclesAmount; 466 | icpBalance: IcpE8s; 467 | }; 468 | }; 469 | type ErrorLog = 470 | variant { 471 | IcpSaToMain: 472 | record { 473 | debit: record { 474 | nat64; 475 | AccountId; 476 | IcpE8s; 477 | }; 478 | errMsg: TransferError; 479 | time: Timestamp; 480 | user: AccountId; 481 | }; 482 | Withdraw: 483 | record { 484 | credit: record { 485 | CyclesWallet; 486 | CyclesAmount; 487 | AccountId; 488 | IcpE8s; 489 | }; 490 | cyclesErrMsg: text; 491 | icpErrMsg: opt TransferError; 492 | time: Timestamp; 493 | user: AccountId; 494 | }; 495 | }; 496 | type ErrorAction = 497 | variant { 498 | delete; 499 | fallback; 500 | resendCycles; 501 | resendIcp; 502 | resendIcpCycles; 503 | }; 504 | type Data = blob; 505 | type DRC207Support = 506 | record { 507 | cycles_receivable: bool; 508 | monitorable_by_blackhole: 509 | record { 510 | allowed: bool; 511 | canister_id: opt principal; 512 | }; 513 | monitorable_by_self: bool; 514 | timer: record { 515 | enable: bool; 516 | interval_seconds: opt nat; 517 | }; 518 | }; 519 | type CyclesWallet = principal; 520 | type CyclesTransferLog = 521 | record { 522 | from: principal; 523 | status: TransStatus; 524 | to: principal; 525 | updateTime: Timestamp; 526 | value: CyclesAmount; 527 | }; 528 | type CyclesAmount = nat; 529 | type Config = 530 | record { 531 | CYCLES_LIMIT: opt nat; 532 | FEE: opt nat; 533 | ICP_FEE: opt nat64; 534 | ICP_LIMIT: opt nat; 535 | MAX_CACHE_NUMBER_PER: opt nat; 536 | MAX_CACHE_TIME: opt nat; 537 | MAX_STORAGE_TRIES: opt nat; 538 | MIN_CYCLES: opt nat; 539 | MIN_ICP_E8S: opt nat; 540 | STORAGE_CANISTER: opt text; 541 | CYCLESFEE_RETENTION_RATE: opt nat; 542 | }; 543 | type BlockIndex = nat64; 544 | type BalanceChange = 545 | variant { 546 | CreditRecord: nat; 547 | DebitRecord: nat; 548 | NoChange; 549 | }; 550 | type Address = text; 551 | type AccountId = blob; 552 | type CyclesMarket = service { 553 | getAccountId: (Address) -> (text) query; 554 | add: (Address, opt Nonce, opt Data) -> (TxnResult); 555 | remove: (opt Shares, CyclesWallet, opt Nonce, opt Sa, opt Data) -> (TxnResult); 556 | cyclesToIcp: (Address, opt Nonce, opt Data) -> (TxnResult); 557 | icpToCycles: (IcpE8s, CyclesWallet, opt Nonce, opt Sa, opt Data) -> (TxnResult); 558 | claim: (CyclesWallet, opt Nonce, opt Sa, opt Data) -> (TxnResult); 559 | count: (opt Address) -> (nat) query; 560 | canister_status: () -> (canister_status); 561 | feeStatus: () -> (FeeStatus) query; 562 | getConfig: () -> (Config) query; 563 | getEvents: (opt Address) -> (vec TxnRecord) query; 564 | lastTxids: (opt Address) -> (vec Txid) query; 565 | liquidity: (opt Address) -> (Liquidity) query; 566 | lpRewards: (Address) -> (record { cycles: nat; icp: nat;}) query; 567 | txnRecord: (Txid) -> (opt TxnRecord) query; 568 | txnRecord2: (Txid) -> (opt TxnRecord); 569 | yield: () -> (record { apyCycles: float64; apyIcp: float64;}, record {apyCycles: float64; apyIcp: float64;}) query; 570 | version: () -> (text) query; 571 | }; 572 | service : () -> CyclesMarket 573 | ```` 574 | 575 | 576 | ## 路线图 577 | 578 | 开发UI界面,开源合约代码; 579 | 580 | (doing) 升级至V1.0版本,功能完善; 581 | 582 | 推出ICL代币,开启流动性挖矿。 583 | 584 | 585 | ## 关于我们 586 | 587 | Web: http://cycles.finance/ 588 | 589 | Github: https://github.com/iclighthouse/Cycles.Finance 590 | 591 | Twitter: https://twitter.com/ICLighthouse 592 | 593 | Medium: https://medium.com/@ICLighthouse 594 | 595 | Discord: https://discord.gg/FQZFGGq7zv -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Cycles.Finance 2 | 3 | **Website**: http://cycles.finance 4 | **Canister Id**: 6nmrm-laaaa-aaaak-aacfq-cai 5 | **Module hash**: 070a8e3cfb65204e29241278f19c5c440dabfbf6913e080441e647759102847e 6 | **Version**: 0.6 7 | 8 | ### Disclaimers. 9 | 10 | This project is in beta and may have defects. It‘s a Dapp, please be knowledgeable and participate voluntarily at your own risk. 11 | 12 | ## Overview 13 | 14 | Cycles.Finance is an ICP/Cycles marketplace that supports bidirectional exchange of ICP, Cycles, using a multiplicative constant K model (A*B=K), similar to UniSwapV2. 15 | 16 | #### Restrictions on Swapping 17 | 18 | The project is still in beta and limits have been placed on a swap in order to control risk. 19 | - ICP: max 10 icp each swap, min 10,000 e8s each swap. 20 | - Cycles: max 3*10^14 cycles each swap, min 10^8 cycles each swap. 21 | - Swap volatility limit: a swap causing price fluctuations more than 20% will be rejected. 22 | 23 | #### Swap fees 24 | 25 | Swapping fee: 1%, on a post-fee model, charged in ICPs or Cycles. 26 | ICP transfer fee: 10,000 e8s per transfer, deducted by ic network. 27 | Swapping fee usage: All ICP charged is moved to the liquidity reward pool, 80% of Cycles charged is moved to the liquidity reward pool (the other 20% is used for Canister gas). 28 | 29 | #### Liquidity (AMM) 30 | 31 | Market making model: automatic market making model(AMM). Using a multiplicative constant K model (AB=K). 32 | 33 | #### Liquidity reward pool 34 | 35 | - Liquidity providers can claim liquidity rewards in proportion to the share they hold. 36 | - [Plan] Participate in the ICLighthouse liquidity mining program and receive ICL token rewards. 37 | 38 | Note: To participate in AMM, you need to add both ICP and Cycles assets to the liquidity pool. The amount of these two assets will change as users trade. For example, if you add 1 ICP and 30 TCycles to the liquidity pool, after a period of time you may withdraw 0.9 ICP and 33.3 TCycles or other possible amounts. 39 | 40 | 41 | ## How does it work? 42 | 43 | CyclesFinance is designed to facilitate the swap of ICPs and Cycles in a different way to traditional exchanges. 44 | 45 | It does this by using Canister smart contracts, which allow users (called liquidity providers) to deposit ICPs/Cycles into pool. These smart contracts allow traders to buy and sell these assets. Users who trade these assets pay a fee which is then distributed to all liquidity providers proportionally (based on their contribution to the asset pool). 46 | 47 | ![image](cf-swap.png) 48 | 49 | **Liquidity pool** 50 | 51 | The liquidity pool holds ICPs and Cycles, which together represent a trading pair for those assets. 52 | 53 | CyclesFinance uses a pricing mechanism called the ‘multiplicative constant k market maker model’. The formula (A * B = k) is used to determine the pricing for the pair. 54 | A and B represent the pool balance of each asset, and k is the total constant price of said pool. 55 | In the liquidity pool, the first liquidity provider sets the initial price of the assets in the pool by supplying an equal value to both tokens. 56 | 57 | **Swap** 58 | 59 | Buyers can then swap ICP/Cycles within the pool, based on the formula. Smart contracts running the rule use the above formula to take the amount of one asset from the buyer and send an equivalent amount of another asset purchased back to the buyer, keeping the total pool constant stable (k). 60 | 61 | **Example**: 62 | 63 | Let us imagine the ICP/Cycles liquidity pool contains 10 ICP(A) and 300 TCycles (B), therefore making the pool constant value 3000 (k). 64 | This implies that the pool’s starting price is 30 TCycles per ICP. 65 | 66 | Now, let us imagine a trader comes in and wants to buy 0.1 ICP. 67 | 68 | The ICP/Cycles pool will now have: 69 | 70 | New A: 9.9 ICP (10 - 0.1) 71 | k: 3000 (stays constant) 72 | New B: 303.03 TCycles (3000 / 9.9) 73 | Therefore, the pool would imply a price of 30.303 TCycles per ICP to keep k constant since you had to add 3.03 TCycles (303.03 TCycles – 300 TCycles) to the pool to buy 0.1 ICP. 74 | 75 | In the above example, the next implied rate for ICP will be around 30.609 TCycles per ICP (303.03 TCycles/9.9 ICP). 76 | 77 | When the price of an asset starts to trade away from market prices, arbitragers see this as an opportunity to make risk-free returns. Therefore, they come in to trade the price back to market rates. This is a vital part of the ICP/Cycles ecosystem. 78 | 79 | 80 | ## Technical features 81 | 82 | #### Achieving eventually consistency 83 | 84 | CyclesFinance faces atomicity problems mainly with ICP internal transfer failures and Cycles send failures. We use a Best Effort Commit strategy together with an error handling mechanism to ensure ultimate consistency. 85 | 86 | - Before updating state variables, canister will throw an exception when an error is encountered. 87 | - It ensures that all internal state variables are successfully saved when some of them have already been updated, and external calls take a Best Effort Commit strategy, but to prevent duplicate transactions, so an error handling mechanism is added. 88 | - With regard to the error handling mechanism, it requires the administrator or governance contract to trigger a retransaction. For accounts that are unable to receive Cycles, the manager or governance contract can modify the receiving account. 89 | 90 | #### Enhanced idempotency 91 | 92 | The idempotency prevents repeated executions when an external canister is submitted repeatedly in the event of an error in the call to CyclesFinance. 93 | - The transaction txid is computable and globally unique. 94 | - The nonce mechanism for accounts is supported. 95 | 96 | #### Oracle quotes support 97 | 98 | ICP/Cycles swap prices could be used as native Oracle quotes on the IC network. 99 | CyclesFinance offers two forms of Oracle quotes, including 100 | - Latest prices: The liquidity(null) method of the CyclesFinance canister is used to query the number of ICPs and Cycles in the liquidity pool. `cycles/icp.e8s` means the ICP/Cycles price. 101 | - Time-weighted prices: The liquidity(null) method of the CyclesFinance canister is used to query the time-weighted cumulative value of ICPs and Cycles. 102 | ![image](cf-priceweighted.png) 103 | 104 | #### liquidity mining support 105 | 106 | CyclesFinance can provide a data resource for liquidity mining contracts as well as a space for innovation in community governance and economic models. 107 | The liquidity() method of the CyclesFinance canister is used to query the time-weighted cumulative value of the LP's liquidity pool share. 108 | ![image](cf-shareweighted.png) 109 | 110 | #### Trading mining support 111 | 112 | CyclesFinance can provide data resources for trading mining. It can query the cumulative value of trading volume on a global or account basis. 113 | 114 | #### Scalable storage of transaction records 115 | 116 | To ensure that CyclesFinance can support large-scale application scenarios, the CyclesFinance canister stores only recent transactions, which are stored persistently via an external scalable canisters. 117 | 118 | 119 | ## Usage (Command line interface) 120 | 121 | **Notes** 122 | - UI interaction interface: http://cycles.finance 123 | - The basic unit of ICP in canister is e8s, 1 icp = 10^8 e8s; 124 | - The ICP/Cycles rate on IC network changes dynamically and is pegged to the XDR value, 1 XDR = 10^12 cycles (value approx. 1.4 USD). 125 | - The ICP/Cycles rate on this canister is automatically formed by the market and may deviate from other markets. 126 | - Your `ICP account principal` and `Cycles wallet account principal` are used to interact with this canister, please note the difference between them. 127 | 128 | ### Query ICP/Cycles price 129 | ```` 130 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai liquidity '(null)' 131 | ```` 132 | The `cycles` (or `2_190_693_645`) field in the return value is divided by the `icpE8s` (or `1_180_746_538`) field to indicate how many cycles can be exchanged for 1 e8s. This value is multiplied by 10^8 to indicate how many cycles can be exchanged for 1 icp. this is an estimate. 133 | ```` 134 | ( 135 | record { 136 | icpE8s = 48_521_783 : nat; 137 | vol = record { 138 | swapIcpVol = 1_740_878 : nat; 139 | swapCyclesVol = 573_069_740_022 : nat; 140 | }; 141 | shareWeighted = record { 142 | updateTime = 1_638_592_854 : nat; 143 | shareTimeWeighted = 3_894_326_391_123 : nat; 144 | }; 145 | unitValue = record { 329155.999121 : float64; 0.972376 : float64 }; 146 | shares = 809_508_285 : nat; 147 | cycles = 266_454_525_225_963 : nat; 148 | priceWeighted = record { 149 | updateTime = 1_638_592_854 : nat; 150 | icpTimeWeighted = 3_800_565_037_457 : nat; 151 | cyclesTimeWeighted = 1_277_301_377_584_917_917 : nat; 152 | }; 153 | swapCount = 0 : nat64; 154 | }, 155 | ) 156 | ```` 157 | 158 | ### ICP to Cycles 159 | 160 | Step1: Get your dedicated ICP deposit account-id (**DepositAccountId**) 161 | ```` 162 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai getAccountId '("")' 163 | ```` 164 | Return `DepositAccountId`(example) 165 | ```` 166 | ("f2d1945ebc293bdc2cc6ef**************e84cf61f51ce6798fc4283") 167 | ```` 168 | 169 | Step2: Send ICP to `DepositAccountId` 170 | ```` 171 | dfx ledger --network ic transfer --memo 0 --e8s 172 | ```` 173 | 174 | Step3: Converting to Cycles. Parameters `icp_e8s_amount` is the amount sent in Step2 and `your_cycles_wallet_principal` is the principal of your cycles wallet (note: not your ICP account principal). 175 | ```` 176 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai icpToCycles '(:nat, principal "", null, null, null)' 177 | ```` 178 | Check your wallet balance 179 | ```` 180 | dfx wallet --network ic balance 181 | ```` 182 | 183 | ### Cycles to ICP 184 | 185 | Step1: Use the didc tool to encode the parameters. Note, didc tool resources: https://github.com/dfinity/candid/tree/master/tools/didc 186 | ```` 187 | didc encode '("",null,null)' -t '(text,opt nat,opt blob)' -f blob 188 | ```` 189 | Return `CallArgs`(example) 190 | ```` 191 | blob "DIDL\02n\01m{\02h\00\01\**************\88\01\e1\18\fd6G\02\00" 192 | ```` 193 | 194 | Step2: Converting to ICP. The parameter `cycles_amount` is the amount of cycles you want to convert, and the parameter `call_args` is the `CallArgs` got from Step1. 195 | ```` 196 | dfx canister --network ic call wallet_call '(record {canister=principal "6nmrm-laaaa-aaaak-aacfq-cai"; method_name="cyclesToIcp"; cycles=:nat64; args=})' 197 | ```` 198 | Check your account balance 199 | ```` 200 | dfx ledger --network ic balance 201 | ```` 202 | 203 | ### Add liquidity 204 | 205 | To add liquidity, both ICP and Cycles to be added to the liquidity pool, the proportion is calculated based on the current price and the excess will refunded. 206 | 207 | Step1: Get your dedicated ICP deposit account-id(**DepositAccountId**) 208 | ```` 209 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai getAccountId '("")' 210 | ```` 211 | Return (example) 212 | ```` 213 | ("f2d1945ebc293bdc2cc6ef**************e84cf61f51ce6798fc4283") 214 | ```` 215 | 216 | Step2: Send ICP to `DepositAccountId` 217 | ```` 218 | dfx ledger --network ic transfer --memo 0 --e8s 219 | ```` 220 | 221 | Step3: Use the didc tool to encode the parameters. Note, didc tool resources: https://github.com/dfinity/candid/tree/master/tools/didc 222 | ```` 223 | didc encode '("",null,null)' -t '(text,opt nat,opt blob)' -f blob 224 | ```` 225 | Return `CallArgs`(example) 226 | ```` 227 | blob "DIDL\02n\01m{\02h\00\01\**************\88\01\e1\18\fd6G\02\00" 228 | ```` 229 | 230 | Step4: Send Cycles, add liquidity. The parameter `cycles_amount` is the amount of cycles you want to add, and the parameter `call_args` is the `CallArgs` got from Step3. 231 | ```` 232 | dfx canister --network ic call wallet_call '(record {canister=principal "6nmrm-laaaa-aaaak-aacfq-cai"; method_name="add"; cycles=:nat64; args=})' 233 | ```` 234 | 235 | Step5: Enquire about liquidity shares 236 | ```` 237 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai liquidity '(opt "")' 238 | ```` 239 | Return (example). The `shares` (or `489_381_556`) field is the share of liquidity you hold. 240 | ```` 241 | ( 242 | record { 243 | icpE8s = 48_521_783 : nat; 244 | vol = record { 245 | swapIcpVol = 1_648_218 : nat; 246 | swapCyclesVol = 541_650_948_359 : nat; 247 | }; 248 | shareWeighted = record { 249 | updateTime = 1_638_528_867 : nat; 250 | shareTimeWeighted = 695_045_889_662 : nat; 251 | }; 252 | unitValue = record { 329748.544469 : float64; 0.970629 : float64 }; 253 | shares = 49_990_000 : nat; 254 | cycles = 16_484_143_085_896 : nat; 255 | priceWeighted = record { 256 | updateTime = 1_638_528_867 : nat; 257 | icpTimeWeighted = 689_683_291_306 : nat; 258 | cyclesTimeWeighted = 224_229_508_922_468_505 : nat; 259 | }; 260 | swapCount = 0 : nat64; 261 | }, 262 | ) 263 | ```` 264 | 265 | ### Remove liquidity 266 | 267 | Step1: Query your liquidity share, the `shares` (or `489_381_556`) field in the return is your share held. 268 | 269 | ```` 270 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai liquidity '(opt "")' 271 | ```` 272 | 273 | Step2: Remove liquidity. The parameter `share_amount` must be equal to or less than the value queried by Step1, and the parameter `your_cycles_wallet_principal` is wallet principal used to receive the cycles, and caller principal will receive icp. 274 | 275 | ```` 276 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai remove '(opt :opt nat, principal "", null, null, null)' 277 | ```` 278 | Check your account balance 279 | ```` 280 | dfx ledger --network ic balance 281 | dfx wallet --network ic balance 282 | ```` 283 | 284 | ### Claim Rewards 285 | 286 | Claim Rewards. The parameter `your_cycles_wallet_principal` is wallet principal used to receive cycles, and caller principal will receive icp. 287 | ```` 288 | dfx canister --network ic call 6nmrm-laaaa-aaaak-aacfq-cai claim '(principal "", null, null, null)' 289 | ```` 290 | Check your account balance 291 | ```` 292 | dfx ledger --network ic balance 293 | dfx wallet --network ic balance 294 | ```` 295 | 296 | ## DID 297 | 298 | ```` 299 | type definite_canister_settings = 300 | record { 301 | compute_allocation: nat; 302 | controllers: vec principal; 303 | freezing_threshold: nat; 304 | memory_allocation: nat; 305 | }; 306 | type canister_status = 307 | record { 308 | cycles: nat; 309 | memory_size: nat; 310 | module_hash: opt vec nat8; 311 | settings: definite_canister_settings; 312 | status: variant { 313 | running; 314 | stopped; 315 | stopping; 316 | }; 317 | }; 318 | type Vol = 319 | record { 320 | swapCyclesVol: CyclesAmount; 321 | swapIcpVol: IcpE8s; 322 | }; 323 | type TxnResult = 324 | variant { 325 | err: 326 | record { 327 | code: 328 | variant { 329 | IcpTransferException; 330 | InsufficientShares; 331 | InvalidCyclesAmout; 332 | InvalidIcpAmout; 333 | NonceError; 334 | PoolIsEmpty; 335 | UnacceptableVolatility; 336 | UndefinedError; 337 | }; 338 | message: text; 339 | }; 340 | ok: 341 | record { 342 | cycles: BalanceChange; 343 | icpE8s: BalanceChange; 344 | shares: ShareChange; 345 | txid: Txid; 346 | }; 347 | }; 348 | type TxnRecord = 349 | record { 350 | account: AccountId; 351 | caller: AccountId; 352 | cyclesWallet: opt CyclesWallet; 353 | data: opt Data; 354 | details: 355 | vec 356 | record { 357 | counterparty: Txid; 358 | token0Value: BalanceChange; 359 | token1Value: BalanceChange; 360 | }; 361 | fee: record { 362 | token0Fee: nat; 363 | token1Fee: nat; 364 | }; 365 | index: nat; 366 | msgCaller: opt principal; 367 | nonce: Nonce; 368 | operation: OperationType; 369 | orderType: variant { 370 | AMM; 371 | OrderBook; 372 | }; 373 | shares: ShareChange; 374 | time: Time; 375 | token0: TokenType; 376 | token0Value: BalanceChange; 377 | token1: TokenType; 378 | token1Value: BalanceChange; 379 | txid: Txid; 380 | }; 381 | type Txid = blob; 382 | type TransferError = 383 | variant { 384 | BadFee: record {expected_fee: ICP;}; 385 | InsufficientFunds: record {balance: ICP;}; 386 | TxCreatedInFuture; 387 | TxDuplicate: record {duplicate_of: BlockIndex;}; 388 | TxTooOld: record {allowed_window_nanos: nat64;}; 389 | }; 390 | type TransStatus = 391 | variant { 392 | Failure; 393 | Fallback; 394 | Processing; 395 | Success; 396 | }; 397 | type TokenType = 398 | variant { 399 | Cycles; 400 | Icp; 401 | Token: principal; 402 | }; 403 | type Timestamp = nat; 404 | type Time = int; 405 | type Shares = nat; 406 | type ShareWeighted = 407 | record { 408 | shareTimeWeighted: nat; 409 | updateTime: Timestamp; 410 | }; 411 | type ShareChange = 412 | variant { 413 | Burn: Shares; 414 | Mint: Shares; 415 | NoChange; 416 | }; 417 | type Sa = vec nat8; 418 | type PriceWeighted = 419 | record { 420 | cyclesTimeWeighted: nat; 421 | icpTimeWeighted: nat; 422 | updateTime: Timestamp; 423 | }; 424 | type OperationType = 425 | variant { 426 | AddLiquidity; 427 | Claim; 428 | RemoveLiquidity; 429 | Swap; 430 | }; 431 | type Nonce = nat; 432 | type Liquidity = 433 | record { 434 | cycles: nat; 435 | icpE8s: IcpE8s; 436 | priceWeighted: PriceWeighted; 437 | shareWeighted: ShareWeighted; 438 | shares: Shares; 439 | swapCount: nat64; 440 | unitValue: record { 441 | float64; 442 | float64; 443 | }; 444 | vol: Vol; 445 | }; 446 | type IcpTransferLog = 447 | record { 448 | fee: IcpE8s; 449 | from: AccountId; 450 | status: TransStatus; 451 | to: AccountId; 452 | updateTime: Timestamp; 453 | value: IcpE8s; 454 | }; 455 | type IcpE8s = nat; 456 | type ICP = record {e8s: nat64;}; 457 | type FeeStatus = 458 | record { 459 | cumulFee: record { 460 | cyclesBalance: CyclesAmount; 461 | icpBalance: IcpE8s; 462 | }; 463 | fee: float64; 464 | totalFee: record { 465 | cyclesBalance: CyclesAmount; 466 | icpBalance: IcpE8s; 467 | }; 468 | }; 469 | type ErrorLog = 470 | variant { 471 | IcpSaToMain: 472 | record { 473 | debit: record { 474 | nat64; 475 | AccountId; 476 | IcpE8s; 477 | }; 478 | errMsg: TransferError; 479 | time: Timestamp; 480 | user: AccountId; 481 | }; 482 | Withdraw: 483 | record { 484 | credit: record { 485 | CyclesWallet; 486 | CyclesAmount; 487 | AccountId; 488 | IcpE8s; 489 | }; 490 | cyclesErrMsg: text; 491 | icpErrMsg: opt TransferError; 492 | time: Timestamp; 493 | user: AccountId; 494 | }; 495 | }; 496 | type ErrorAction = 497 | variant { 498 | delete; 499 | fallback; 500 | resendCycles; 501 | resendIcp; 502 | resendIcpCycles; 503 | }; 504 | type Data = blob; 505 | type DRC207Support = 506 | record { 507 | cycles_receivable: bool; 508 | monitorable_by_blackhole: 509 | record { 510 | allowed: bool; 511 | canister_id: opt principal; 512 | }; 513 | monitorable_by_self: bool; 514 | timer: record { 515 | enable: bool; 516 | interval_seconds: opt nat; 517 | }; 518 | }; 519 | type CyclesWallet = principal; 520 | type CyclesTransferLog = 521 | record { 522 | from: principal; 523 | status: TransStatus; 524 | to: principal; 525 | updateTime: Timestamp; 526 | value: CyclesAmount; 527 | }; 528 | type CyclesAmount = nat; 529 | type Config = 530 | record { 531 | CYCLES_LIMIT: opt nat; 532 | FEE: opt nat; 533 | ICP_FEE: opt nat64; 534 | ICP_LIMIT: opt nat; 535 | MAX_CACHE_NUMBER_PER: opt nat; 536 | MAX_CACHE_TIME: opt nat; 537 | MAX_STORAGE_TRIES: opt nat; 538 | MIN_CYCLES: opt nat; 539 | MIN_ICP_E8S: opt nat; 540 | STORAGE_CANISTER: opt text; 541 | CYCLESFEE_RETENTION_RATE: opt nat; 542 | }; 543 | type BlockIndex = nat64; 544 | type BalanceChange = 545 | variant { 546 | CreditRecord: nat; 547 | DebitRecord: nat; 548 | NoChange; 549 | }; 550 | type Address = text; 551 | type AccountId = blob; 552 | type CyclesMarket = service { 553 | getAccountId: (Address) -> (text) query; 554 | add: (Address, opt Nonce, opt Data) -> (TxnResult); 555 | remove: (opt Shares, CyclesWallet, opt Nonce, opt Sa, opt Data) -> (TxnResult); 556 | cyclesToIcp: (Address, opt Nonce, opt Data) -> (TxnResult); 557 | icpToCycles: (IcpE8s, CyclesWallet, opt Nonce, opt Sa, opt Data) -> (TxnResult); 558 | claim: (CyclesWallet, opt Nonce, opt Sa, opt Data) -> (TxnResult); 559 | count: (opt Address) -> (nat) query; 560 | canister_status: () -> (canister_status); 561 | feeStatus: () -> (FeeStatus) query; 562 | getConfig: () -> (Config) query; 563 | getEvents: (opt Address) -> (vec TxnRecord) query; 564 | lastTxids: (opt Address) -> (vec Txid) query; 565 | liquidity: (opt Address) -> (Liquidity) query; 566 | lpRewards: (Address) -> (record { cycles: nat; icp: nat;}) query; 567 | txnRecord: (Txid) -> (opt TxnRecord) query; 568 | txnRecord2: (Txid) -> (opt TxnRecord); 569 | yield: () -> (record { apyCycles: float64; apyIcp: float64;}, record {apyCycles: float64; apyIcp: float64;}) query; 570 | version: () -> (text) query; 571 | }; 572 | service : () -> CyclesMarket 573 | ```` 574 | 575 | 576 | ## Roadmap 577 | 578 | Development of UI interface, open source contract code. 579 | 580 | (doing) Upgrade to v1.0. 581 | 582 | Opening up liquidity mining. 583 | 584 | 585 | ## Community 586 | 587 | Web: http://cycles.finance/ 588 | 589 | Github: https://github.com/iclighthouse/Cycles.Finance 590 | 591 | Twitter: https://twitter.com/ICLighthouse 592 | 593 | Medium: https://medium.com/@ICLighthouse 594 | 595 | Discord: https://discord.gg/FQZFGGq7zv -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------