├── .gitignore ├── canisters ├── faucet │ ├── js.png │ ├── package.json │ ├── index.html │ └── elements │ │ └── jsonic-app.ts └── jsonic │ ├── jsonic.did │ └── jsonic.ts ├── canister_ids.json ├── dfx.json ├── package.json ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .dfx 3 | target 4 | Cargo.toml 5 | Cargo.lock 6 | canisters/jsonic/src 7 | build -------------------------------------------------------------------------------- /canisters/faucet/js.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lastmjs/extendable-token-typescript/HEAD/canisters/faucet/js.png -------------------------------------------------------------------------------- /canister_ids.json: -------------------------------------------------------------------------------- 1 | { 2 | "faucet": { 3 | "ic": "nceop-maaaa-aaaae-qaavq-cai" 4 | }, 5 | "jsonic": { 6 | "ic": "nmgdh-xqaaa-aaaae-qaauq-cai" 7 | } 8 | } -------------------------------------------------------------------------------- /canisters/faucet/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "faucet", 3 | "version": "0.0.0", 4 | "description": "", 5 | "scripts": { 6 | "build": "snowpack build --polyfill-node" 7 | }, 8 | "keywords": [], 9 | "author": "Jordan Last ", 10 | "license": "MIT", 11 | "dependencies": { 12 | "ic-stoic-identity": "2.0.0", 13 | "lit-html": "2.0.1", 14 | "reduxular": "0.0.6" 15 | }, 16 | "devDependencies": { 17 | "snowpack": "3.8.8" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /dfx.json: -------------------------------------------------------------------------------- 1 | { 2 | "canisters": { 3 | "jsonic": { 4 | "type": "custom", 5 | "build": "node_modules/.bin/azle jsonic", 6 | "root": "canisters/jsonic", 7 | "js": "canisters/jsonic/jsonic.ts", 8 | "candid": "canisters/jsonic/jsonic.did", 9 | "wasm": "target/wasm32-unknown-unknown/release/jsonic-optimized.wasm" 10 | }, 11 | "faucet": { 12 | "type": "assets", 13 | "source": ["canisters/faucet/build"] 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "extendable-token-typescript", 3 | "version": "0.0.0", 4 | "description": "", 5 | "scripts": { 6 | "build": "cd canisters/faucet && npm install && npm run build" 7 | }, 8 | "repository": { 9 | "type": "git", 10 | "url": "git+https://github.com/lastmjs/extendable-token-typescript.git" 11 | }, 12 | "keywords": [], 13 | "author": "Jordan Last ", 14 | "license": "MIT", 15 | "bugs": { 16 | "url": "https://github.com/lastmjs/extendable-token-typescript/issues" 17 | }, 18 | "homepage": "https://github.com/lastmjs/extendable-token-typescript#readme", 19 | "dependencies": { 20 | "azle": "0.0.3" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Jordan Last 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # extendable-token-typescript 2 | 3 | ## Installation 4 | 5 | Install the following: 6 | 7 | * [Node.js](https://github.com/nvm-sh/nvm) 8 | * [Rust](https://www.rust-lang.org/tools/install) 9 | * [dfx](https://sdk.dfinity.org/docs/quickstart/local-quickstart.html#download-and-install) 10 | 11 | Run the following terminal commands: 12 | 13 | ```bash 14 | git clone https://github.com/lastmjs/extendable-token-typescript 15 | cd extendable-token-typescript 16 | npm install 17 | ``` 18 | 19 | ## Development deployment 20 | 21 | Run the following terminal commands: 22 | 23 | ```bash 24 | dfx start --background 25 | dfx deploy 26 | ``` 27 | 28 | Open `http://r7inp-6aaaa-aaaaa-aaabq-cai.localhost:8000` in a web browser. Enter `ryjl3-tyaaa-aaaaa-aaaba-cai` as the canister id in the web interface, and upload `extendable-token-typescript/canisters/jsonic/jsonic.did` as the did file. 29 | 30 | You can then use the web interface to call the methods on the JSONIC canister. 31 | 32 | ## Production deployment 33 | 34 | If you want to deploy your own canisters to the IC then make sure to delete `extendable-token-typescript/canister_ids.json`. 35 | 36 | Run the following terminal commands: 37 | 38 | ```bash 39 | dfx deploy --network ic 40 | ``` -------------------------------------------------------------------------------- /canisters/faucet/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | JSONIC Faucet 6 | 7 | 8 | 33 | 34 | 35 | 36 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /canisters/jsonic/jsonic.did: -------------------------------------------------------------------------------- 1 | type Account = record { AccountIdentifier; Balance; }; 2 | type Accounts = vec Account; 3 | 4 | type AccountIdentifier = text; 5 | 6 | type Balance = nat; 7 | 8 | type BalanceRequest = record { 9 | user: User; 10 | token: TokenIdentifier; 11 | }; 12 | 13 | type BalanceResponse = variant { 14 | ok: Balance; 15 | err: CommonError; 16 | }; 17 | 18 | type CommonError = variant { 19 | InvalidToken: TokenIdentifier; 20 | Other: text; 21 | }; 22 | 23 | type Extension = text; 24 | type Extensions = vec Extension; 25 | 26 | type FungibleMetadata = record { 27 | name: text; 28 | symbol: text; 29 | decimals: nat8; 30 | metadata: opt blob; 31 | }; 32 | 33 | type Memo = blob; 34 | 35 | type Metadata = variant { 36 | fungible: FungibleMetadata; 37 | nonfungible: NonFungibleMetadata; 38 | }; 39 | 40 | type MetadataResponse = variant { 41 | ok: Metadata; 42 | err: CommonError; 43 | }; 44 | 45 | type NonFungibleMetadata = record { 46 | metadata: opt blob; 47 | }; 48 | 49 | type SupplyResponse = variant { 50 | ok: Balance; 51 | err: CommonError; 52 | }; 53 | 54 | type TokenIdentifier = text; 55 | 56 | type TransferRequest = record { 57 | from: User; 58 | to: User; 59 | token: TokenIdentifier; 60 | amount: Balance; 61 | memo: Memo; 62 | notify: bool; 63 | }; 64 | 65 | type TransferResponse = variant { 66 | ok: Balance; 67 | err: TransferResponseError; 68 | }; 69 | 70 | type TransferResponseError = variant { 71 | Unauthorized: AccountIdentifier; 72 | InsufficientBalance: null; 73 | Rejected: null; 74 | InvalidToken: TokenIdentifier; 75 | CannotNotify: AccountIdentifier; 76 | Other: text; 77 | }; 78 | 79 | type User = variant { 80 | address: text; 81 | "principal": principal; 82 | }; 83 | 84 | service : { 85 | "balance": (BalanceRequest) -> (BalanceResponse) query; 86 | "claim": () -> (bool); 87 | "extensions": () -> (Extensions) query; 88 | "metadata": (TokenIdentifier) -> (MetadataResponse) query; 89 | "registry": () -> (Accounts) query; 90 | "supply": (TokenIdentifier) -> (SupplyResponse) query; 91 | "transfer": (TransferRequest) -> (TransferResponse); 92 | } -------------------------------------------------------------------------------- /canisters/faucet/elements/jsonic-app.ts: -------------------------------------------------------------------------------- 1 | import { 2 | html, 3 | render as litRender, 4 | TemplateResult 5 | } from 'lit-html'; 6 | import { StoicIdentity } from 'ic-stoic-identity'; 7 | import { createObjectStore } from 'reduxular'; 8 | import { 9 | Actor, 10 | HttpAgent, 11 | Identity 12 | } from '@dfinity/agent'; 13 | import { 14 | SupplyResponse, 15 | Accounts 16 | } from '../../jsonic/jsonic'; 17 | 18 | type State = Readonly<{ 19 | claiming: boolean; 20 | holders: Accounts | null, 21 | identity: Identity | null; 22 | supply: bigint | null; 23 | }>; 24 | 25 | const InitialState: State = { 26 | claiming: false, 27 | holders: null, 28 | identity: null, 29 | supply: null 30 | }; 31 | 32 | class JSONICApp extends HTMLElement { 33 | shadow = this.attachShadow({ 34 | mode: 'closed' 35 | }); 36 | store = createObjectStore(InitialState, (state: State) => litRender(this.render(state), this.shadow), this); 37 | 38 | async connectedCallback() { 39 | await this.getAndSetSupply(); 40 | await this.getAndSetHolders(); 41 | } 42 | 43 | async claim() { 44 | this.store.claiming = true; 45 | 46 | const identity = await StoicIdentity.connect(); 47 | 48 | const idlFactory = ({ IDL }) => { 49 | return IDL.Service({ 50 | 'claim': IDL.Func([], [IDL.Bool], []) 51 | }); 52 | }; 53 | 54 | const agent = new HttpAgent({ 55 | identity 56 | }); 57 | 58 | const actor = Actor.createActor(idlFactory, { 59 | agent, 60 | canisterId: 'nmgdh-xqaaa-aaaae-qaauq-cai' 61 | }); 62 | 63 | const result = await actor.claim(); 64 | 65 | if (result === true) { 66 | alert('You have successfully claimed 1 JSONIC'); 67 | 68 | await this.getAndSetSupply(); 69 | await this.getAndSetHolders(); 70 | } 71 | else { 72 | alert('Something went wrong...try again?'); 73 | } 74 | 75 | StoicIdentity.disconnect(); 76 | 77 | this.store.claiming = false; 78 | } 79 | 80 | async getAndSetSupply() { 81 | const idlFactory = ({ IDL }) => { 82 | return IDL.Service({ 83 | 'supply': IDL.Func([IDL.Text], [IDL.Variant({ 'ok' : IDL.Nat })], ['query']) 84 | }); 85 | }; 86 | 87 | const agent = new HttpAgent(); 88 | 89 | const actor = Actor.createActor(idlFactory, { 90 | agent, 91 | canisterId: 'nmgdh-xqaaa-aaaae-qaauq-cai' 92 | }); 93 | 94 | const result = await actor.supply('0') as SupplyResponse; 95 | 96 | this.store.supply = result.ok as unknown as bigint / BigInt(10 ** 8); 97 | } 98 | 99 | async getAndSetHolders() { 100 | const idlFactory = ({ IDL }) => { 101 | return IDL.Service({ 102 | 'registry': IDL.Func([], [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat))], ['query']) 103 | }); 104 | }; 105 | 106 | const agent = new HttpAgent(); 107 | 108 | const actor = Actor.createActor(idlFactory, { 109 | agent, 110 | canisterId: 'nmgdh-xqaaa-aaaae-qaauq-cai' 111 | }); 112 | 113 | const holders = await actor.registry() as Accounts; 114 | 115 | const sortedHolders = [...holders].sort((a, b) => { 116 | if (a[1] < b[1]) { 117 | return 1; 118 | } 119 | 120 | if (a[1] > b[1]) { 121 | return -1; 122 | } 123 | 124 | return 0; 125 | }); 126 | 127 | this.store.holders = sortedHolders; 128 | } 129 | 130 | render(state: State): TemplateResult { 131 | return html` 132 | 180 | 181 |
182 |
183 |
184 | 189 |
190 | 191 |
192 |

193 | JSONIC is the first EXT token written in TypeScript/JavaScript and deployed to the Internet Computer. 194 | The original code can be found in this repository. 195 |

196 | 197 |

198 | Anyone can claim tokens at any time, and there is no supply cap. 199 |

200 | 201 |

202 | The controllers for JSONIC and this frontend have both been set to a black hole address. 203 | This essentially means they are autonomous and can only be practically updated through NNS proposals. 204 |

205 | 206 |

207 | JSONIC canister id: nmgdh-xqaaa-aaaae-qaauq-cai 208 |
209 | Faucet canister id: nceop-maaaa-aaaae-qaavq-cai 210 |

211 |
212 |
213 | 214 |
215 |

Total Supply

216 |
${state.supply === null ? 'Loading...' : `${state.supply} JSONIC`}
217 |
218 | 219 |
220 |

Holders

221 |
222 | ${state.holders === null ? 'Loading...' : state.holders.map((holder) => { 223 | const numJSONIC = holder[1] as unknown as bigint / BigInt(10 ** 8); 224 | const percentJSONIC = (Number(numJSONIC) / Number(state.supply) * 100).toFixed(2); 225 | 226 | return html` 227 |
${holder[0]}: ${numJSONIC} JSONIC, ${percentJSONIC}%
228 | `; 229 | })} 230 |
231 |
232 |
233 | `; 234 | } 235 | } 236 | 237 | window.customElements.define('jsonic-app', JSONICApp); -------------------------------------------------------------------------------- /canisters/jsonic/jsonic.ts: -------------------------------------------------------------------------------- 1 | // this file is based on https://github.com/Toniq-Labs/extendable-token which does not yet have a license 2 | 3 | import { 4 | Candid, 5 | Enum, 6 | ICBlob, 7 | Nat, 8 | Principal, 9 | Query, 10 | Result, 11 | Update, 12 | u8 13 | } from 'azle'; 14 | 15 | declare var ic: { 16 | caller: Principal; 17 | }; 18 | 19 | type Account = Candid<[AccountIdentifier, Balance]>; 20 | export type Accounts = Candid; 21 | 22 | type AccountIdentifier = Candid; 23 | 24 | type Balance = Candid; 25 | 26 | type BalanceRequest = Candid<{ 27 | user: User; 28 | token: TokenIdentifier; 29 | }>; 30 | 31 | type BalanceResponse = Candid>; 32 | 33 | type CommonError = Candid>; 37 | 38 | type Extension = Candid; 39 | type Extensions = Candid; 40 | 41 | type FungibleMetadata = Candid<{ 42 | name: string; 43 | symbol: string; 44 | decimals: u8; 45 | metadata?: ICBlob 46 | }>; 47 | 48 | type Memo = Candid; 49 | 50 | type Metadata = Candid>; 54 | 55 | type MetadataResponse = Candid>; 56 | 57 | type NonFungibleMetadata = Candid<{ 58 | metadata?: ICBlob 59 | }>; 60 | 61 | export type SupplyResponse = Candid>; 62 | 63 | type TokenIdentifier = Candid; 64 | 65 | type TransferRequest = Candid<{ 66 | from: User; 67 | to: User; 68 | token: TokenIdentifier; 69 | amount: Balance; 70 | memo: Memo; 71 | notify: boolean; 72 | }>; 73 | 74 | type TransferResponse = Candid>; 75 | 76 | type TransferResponseError = Candid>; 84 | 85 | type User = Candid>; 89 | 90 | type State = { 91 | balances: { 92 | [key: AccountIdentifier]: Balance | undefined; 93 | }; 94 | extensions: Extension[]; 95 | supply: Balance; 96 | }; 97 | 98 | let state: State = { 99 | balances: {}, 100 | extensions: ['@ext/common'], 101 | supply: 0 102 | }; 103 | 104 | export function balance(request: BalanceRequest): Query { 105 | const aid = getUserAID(request.user); 106 | 107 | const balance = state.balances[aid]; 108 | 109 | if (balance === undefined) { 110 | return { 111 | ok: 0 112 | }; 113 | } 114 | 115 | return { 116 | ok: balance 117 | }; 118 | } 119 | 120 | export function claim(): Update { 121 | const callerAddress = addressFromPrincipal(ic.caller); 122 | 123 | const callerBalance = state.balances[callerAddress] ?? 0; 124 | 125 | state.balances[callerAddress] = callerBalance + 100000000; 126 | 127 | const totalSupply = state.supply; 128 | 129 | state.supply = totalSupply + 100000000; 130 | 131 | return true; 132 | } 133 | 134 | export function extensions(): Query { 135 | return state.extensions; 136 | } 137 | 138 | export function metadata(token: TokenIdentifier): Query { 139 | return { 140 | ok: { 141 | fungible: { 142 | name: 'JS on the IC', 143 | symbol: 'JSONIC', 144 | decimals: 8 145 | } 146 | } 147 | }; 148 | } 149 | 150 | export function registry(): Query { 151 | return Object.entries(state.balances); 152 | } 153 | 154 | export function supply(token: TokenIdentifier): Query { 155 | return { 156 | ok: state.supply 157 | }; 158 | } 159 | 160 | export function transfer(request: TransferRequest): Update { 161 | const sender = getUserAID(request.from); 162 | const spender = addressFromPrincipal(ic.caller); 163 | const receiver = getUserAID(request.to); 164 | 165 | if (sender !== spender) { 166 | return { 167 | err: { 168 | Unauthorized: spender 169 | } 170 | }; 171 | } 172 | 173 | const senderBalance = state.balances[sender]; 174 | 175 | if ( 176 | senderBalance === undefined || 177 | senderBalance < request.amount 178 | ) { 179 | return { 180 | err: { 181 | InsufficientBalance: null 182 | } 183 | }; 184 | } 185 | 186 | const newSenderBalance = senderBalance - request.amount; 187 | 188 | state.balances[sender] = newSenderBalance; 189 | 190 | const receiverBalance = state.balances[receiver] ?? 0; 191 | const newReceiverBalance = receiverBalance + request.amount; 192 | 193 | state.balances[receiver] = newReceiverBalance; 194 | 195 | return { 196 | ok: request.amount 197 | }; 198 | } 199 | 200 | function addressFromPrincipal(principal: Principal): AccountIdentifier { 201 | const decodedPrincipalUint8Array = decodePrincipalFromText(principal); 202 | const decodedPrincipalText = [...decodedPrincipalUint8Array].map(x => String.fromCharCode(x)).join(''); 203 | 204 | const subaccountZero = [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].map(x => String.fromCharCode(x)).join(''); 205 | 206 | const finalString = `\x0Aaccount-id${decodedPrincipalText}${subaccountZero}`; 207 | 208 | const hash: string = sha224(finalString); 209 | const crc = crc32(new Uint8Array(hash.match(/.{1,2}/g).map(x => parseInt(x, 16)))); 210 | 211 | return crc + hash; 212 | } 213 | 214 | function getUserAID(user: User): AccountIdentifier { 215 | return user.address ?? addressFromPrincipal(user.principal); 216 | } 217 | 218 | /* All below is third-party libraries included directly in this file because imports/modules are not yet working */ 219 | 220 | // TODO begin principal decoding section, put in module once supported 221 | 222 | // Licensing is under the Apache License included below 223 | 224 | // Jordan Last has changed the original files licensed under the Apache License 225 | 226 | function decodePrincipalFromText(text: string): Uint8Array { 227 | const canisterIdNoDash = text.toLowerCase().replace(/-/g, ''); 228 | 229 | let arr = decode(canisterIdNoDash); 230 | arr = arr.slice(4, arr.length); 231 | 232 | return arr; 233 | } 234 | 235 | const alphabet = 'abcdefghijklmnopqrstuvwxyz234567'; 236 | 237 | // Build a lookup table for decoding. 238 | const lookupTable: Record = Object.create(null); 239 | for (let lookupTableI = 0; lookupTableI < alphabet.length; lookupTableI++) { 240 | lookupTable[alphabet[lookupTableI]] = lookupTableI; 241 | } 242 | 243 | // Add aliases for rfc4648. 244 | lookupTable['0'] = lookupTable.o; 245 | lookupTable['1'] = lookupTable.i; 246 | 247 | function decode(input: string): Uint8Array { 248 | // how many bits we have from the previous character. 249 | let skip = 0; 250 | // current byte we're producing. 251 | let byte = 0; 252 | 253 | const output = new Uint8Array(((input.length * 4) / 3) | 0); 254 | let o = 0; 255 | 256 | function decodeChar(char: string) { 257 | // Consume a character from the stream, store 258 | // the output in this.output. As before, better 259 | // to use update(). 260 | let val = lookupTable[char.toLowerCase()]; 261 | if (val === undefined) { 262 | throw new Error(`Invalid character: ${JSON.stringify(char)}`); 263 | } 264 | 265 | // move to the high bits 266 | // val <<= 3; // TODO modified 267 | val = val << 3; 268 | // byte |= val >>> skip; // TODO modified 269 | byte = byte | (val >>> skip); 270 | // skip += 5; // TODO modified 271 | skip = skip + 5; 272 | 273 | if (skip >= 8) { 274 | // We have enough bytes to produce an output 275 | // output[o++] = byte; // TODO modified 276 | // output[o++] = byte; 277 | output[o] = byte; 278 | o++; 279 | // skip -= 8; 280 | skip = skip - 8; 281 | 282 | if (skip > 0) { 283 | byte = (val << (5 - skip)) & 255; 284 | } else { 285 | byte = 0; 286 | } 287 | } 288 | } 289 | 290 | for (const c of input) { 291 | decodeChar(c); 292 | } 293 | 294 | return output.slice(0, o); 295 | } 296 | 297 | // TODO end principal decoding section, put in module once supported 298 | 299 | // TODO begin sha224 section, put in module once supported 300 | 301 | // https://github.com/litejs/crypto-lite 302 | // THE MIT LICENSE 303 | 304 | // Copyright (c) Lauri Rooden 305 | 306 | // Permission is hereby granted, free of charge, to any person obtaining a copy 307 | // of this software and associated documentation files (the "Software"), to deal 308 | // in the Software without restriction, including without limitation the rights 309 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 310 | // copies of the Software, and to permit persons to whom the Software is 311 | // furnished to do so, subject to the following conditions: 312 | 313 | // The above copyright notice and this permission notice shall be included in 314 | // all copies or substantial portions of the Software. 315 | 316 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 317 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 318 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 319 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 320 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 321 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 322 | // THE SOFTWARE. 323 | 324 | function intToHex(arr) { 325 | for (let i = arr.length; i--;) arr[i] = ("0000000" + (arr[i] >>> 0).toString(16)).slice(-8); 326 | return arr.join(""); 327 | } 328 | 329 | // TODO the i++ operation seemed to be messing things up, open issue with boa 330 | function strToInt(str) { 331 | var i = 0, arr: any = [], len = arr.len = str.length 332 | 333 | for (; i < len;) { 334 | arr[i>>2] = str.charCodeAt(i)<<24 | str.charCodeAt(i+1)<<16 | str.charCodeAt(i+2)<<8 | str.charCodeAt(i+3) 335 | i += 4 336 | } 337 | return arr 338 | } 339 | 340 | function rotL(val, count) { 341 | return (val << count) | (val >>> (32 - count)) 342 | } 343 | 344 | // TODO the <<= operation seemed to be messing things up, open issue with boa 345 | function shaInit(bin, len) { 346 | if (typeof bin == "string") { 347 | bin = strToInt(bin) 348 | len = bin.len 349 | } else len = len || bin.length<<2 350 | 351 | bin[len>>2] = bin[len>>2] | 0x80 << (24 - (31 & (len<<3))) 352 | 353 | len = len<<3 354 | 355 | bin[((len + 64 >> 9) << 4) + 15] = len 356 | 357 | return bin 358 | } 359 | 360 | //** sha256 361 | var initial_map = [], constants_map = [] 362 | 363 | function buildMaps() { 364 | // getFractionalBits 365 | function powFraction(c, e) { 366 | c = Math.pow(c, e) 367 | return (c - (c>>>0)) * 0x100000000 | 0 368 | } 369 | 370 | outer: for (var b = 0, c = 2, d; b < 64; c++) { 371 | // isPrime 372 | for (d = 2; d * d <= c; d++) if (c % d === 0) continue outer; 373 | if (b < 8) initial_map[b] = powFraction(c, 0.5) 374 | constants_map[b] = powFraction(c, 1 / 3) 375 | b += 1 376 | } 377 | } 378 | 379 | function sha256(data, _len, is224) { 380 | if (!initial_map[0]) buildMaps() 381 | 382 | var a, b, c, d, e, f, g, h, t1, t2, j, i = 0, w = [], A = initial_map[0], B = initial_map[1], C = initial_map[2], D = initial_map[3], E = initial_map[4], F = initial_map[5], G = initial_map[6], H = initial_map[7], bin = shaInit(data, _len), len = bin.length, K = constants_map 383 | 384 | if (is224) { 385 | A = 0xc1059ed8 386 | B = 0x367cd507 387 | C = 0x3070dd17 388 | D = 0xf70e5939 389 | E = 0xffc00b31 390 | F = 0x68581511 391 | G = 0x64f98fa7 392 | H = 0xbefa4fa4 393 | } 394 | 395 | for (; i < len; i+=16, A+=a, B+=b, C+=c, D+=d, E+=e, F+=f, G+=g, H+=h) { 396 | for (j=0, a=A, b=B, c=C, d=D, e=E, f=F, g=G, h=H; j < 64; ) { 397 | if (j < 16) w[j] = bin[i+j] 398 | else { 399 | t1 = w[j-2] 400 | t2 = w[j-15] 401 | w[j] = (rotL(t1, 15)^rotL(t1, 13)^t1>>>10) + (w[j-7]|0) + (rotL(t2, 25)^rotL(t2, 14)^t2>>>3) + (w[j-16]|0) 402 | } 403 | 404 | t1 = (w[j]|0) + h + (rotL(e, 26)^rotL(e, 21)^rotL(e, 7)) + ((e&f)^((~e)&g)) + K[j++] 405 | t2 = (rotL(a, 30)^rotL(a, 19)^rotL(a, 10)) + ((a&b)^(a&c)^(b&c)) 406 | 407 | h = g 408 | g = f 409 | f = e 410 | e = (d + t1)|0 411 | d = c 412 | c = b 413 | b = a 414 | a = (t1 + t2)|0 415 | } 416 | } 417 | return [A, B, C, D, E, F, G, H] 418 | } 419 | 420 | function sha224(data) { 421 | return intToHex(sha256(data, 0, 1)).slice(0, -8) 422 | } 423 | // TODO end sha224 section, put in module once supported 424 | 425 | // TODO begin crc32 section, put in module once supported 426 | 427 | // Copyright © 2016–2019 by Alex I. Kuznetsov 428 | 429 | // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 430 | 431 | // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 432 | 433 | // THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 434 | 435 | // Jordan Last has changed the original files licensed under the Apache License 436 | 437 | // Apache License 438 | // Version 2.0, January 2004 439 | // http://www.apache.org/licenses/ 440 | 441 | // TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 442 | 443 | // 1. Definitions. 444 | 445 | // "License" shall mean the terms and conditions for use, reproduction, 446 | // and distribution as defined by Sections 1 through 9 of this document. 447 | 448 | // "Licensor" shall mean the copyright owner or entity authorized by 449 | // the copyright owner that is granting the License. 450 | 451 | // "Legal Entity" shall mean the union of the acting entity and all 452 | // other entities that control, are controlled by, or are under common 453 | // control with that entity. For the purposes of this definition, 454 | // "control" means (i) the power, direct or indirect, to cause the 455 | // direction or management of such entity, whether by contract or 456 | // otherwise, or (ii) ownership of fifty percent (50%) or more of the 457 | // outstanding shares, or (iii) beneficial ownership of such entity. 458 | 459 | // "You" (or "Your") shall mean an individual or Legal Entity 460 | // exercising permissions granted by this License. 461 | 462 | // "Source" form shall mean the preferred form for making modifications, 463 | // including but not limited to software source code, documentation 464 | // source, and configuration files. 465 | 466 | // "Object" form shall mean any form resulting from mechanical 467 | // transformation or translation of a Source form, including but 468 | // not limited to compiled object code, generated documentation, 469 | // and conversions to other media types. 470 | 471 | // "Work" shall mean the work of authorship, whether in Source or 472 | // Object form, made available under the License, as indicated by a 473 | // copyright notice that is included in or attached to the work 474 | // (an example is provided in the Appendix below). 475 | 476 | // "Derivative Works" shall mean any work, whether in Source or Object 477 | // form, that is based on (or derived from) the Work and for which the 478 | // editorial revisions, annotations, elaborations, or other modifications 479 | // represent, as a whole, an original work of authorship. For the purposes 480 | // of this License, Derivative Works shall not include works that remain 481 | // separable from, or merely link (or bind by name) to the interfaces of, 482 | // the Work and Derivative Works thereof. 483 | 484 | // "Contribution" shall mean any work of authorship, including 485 | // the original version of the Work and any modifications or additions 486 | // to that Work or Derivative Works thereof, that is intentionally 487 | // submitted to Licensor for inclusion in the Work by the copyright owner 488 | // or by an individual or Legal Entity authorized to submit on behalf of 489 | // the copyright owner. For the purposes of this definition, "submitted" 490 | // means any form of electronic, verbal, or written communication sent 491 | // to the Licensor or its representatives, including but not limited to 492 | // communication on electronic mailing lists, source code control systems, 493 | // and issue tracking systems that are managed by, or on behalf of, the 494 | // Licensor for the purpose of discussing and improving the Work, but 495 | // excluding communication that is conspicuously marked or otherwise 496 | // designated in writing by the copyright owner as "Not a Contribution." 497 | 498 | // "Contributor" shall mean Licensor and any individual or Legal Entity 499 | // on behalf of whom a Contribution has been received by Licensor and 500 | // subsequently incorporated within the Work. 501 | 502 | // 2. Grant of Copyright License. Subject to the terms and conditions of 503 | // this License, each Contributor hereby grants to You a perpetual, 504 | // worldwide, non-exclusive, no-charge, royalty-free, irrevocable 505 | // copyright license to reproduce, prepare Derivative Works of, 506 | // publicly display, publicly perform, sublicense, and distribute the 507 | // Work and such Derivative Works in Source or Object form. 508 | 509 | // 3. Grant of Patent License. Subject to the terms and conditions of 510 | // this License, each Contributor hereby grants to You a perpetual, 511 | // worldwide, non-exclusive, no-charge, royalty-free, irrevocable 512 | // (except as stated in this section) patent license to make, have made, 513 | // use, offer to sell, sell, import, and otherwise transfer the Work, 514 | // where such license applies only to those patent claims licensable 515 | // by such Contributor that are necessarily infringed by their 516 | // Contribution(s) alone or by combination of their Contribution(s) 517 | // with the Work to which such Contribution(s) was submitted. If You 518 | // institute patent litigation against any entity (including a 519 | // cross-claim or counterclaim in a lawsuit) alleging that the Work 520 | // or a Contribution incorporated within the Work constitutes direct 521 | // or contributory patent infringement, then any patent licenses 522 | // granted to You under this License for that Work shall terminate 523 | // as of the date such litigation is filed. 524 | 525 | // 4. Redistribution. You may reproduce and distribute copies of the 526 | // Work or Derivative Works thereof in any medium, with or without 527 | // modifications, and in Source or Object form, provided that You 528 | // meet the following conditions: 529 | 530 | // (a) You must give any other recipients of the Work or 531 | // Derivative Works a copy of this License; and 532 | 533 | // (b) You must cause any modified files to carry prominent notices 534 | // stating that You changed the files; and 535 | 536 | // (c) You must retain, in the Source form of any Derivative Works 537 | // that You distribute, all copyright, patent, trademark, and 538 | // attribution notices from the Source form of the Work, 539 | // excluding those notices that do not pertain to any part of 540 | // the Derivative Works; and 541 | 542 | // (d) If the Work includes a "NOTICE" text file as part of its 543 | // distribution, then any Derivative Works that You distribute must 544 | // include a readable copy of the attribution notices contained 545 | // within such NOTICE file, excluding those notices that do not 546 | // pertain to any part of the Derivative Works, in at least one 547 | // of the following places: within a NOTICE text file distributed 548 | // as part of the Derivative Works; within the Source form or 549 | // documentation, if provided along with the Derivative Works; or, 550 | // within a display generated by the Derivative Works, if and 551 | // wherever such third-party notices normally appear. The contents 552 | // of the NOTICE file are for informational purposes only and 553 | // do not modify the License. You may add Your own attribution 554 | // notices within Derivative Works that You distribute, alongside 555 | // or as an addendum to the NOTICE text from the Work, provided 556 | // that such additional attribution notices cannot be construed 557 | // as modifying the License. 558 | 559 | // You may add Your own copyright statement to Your modifications and 560 | // may provide additional or different license terms and conditions 561 | // for use, reproduction, or distribution of Your modifications, or 562 | // for any such Derivative Works as a whole, provided Your use, 563 | // reproduction, and distribution of the Work otherwise complies with 564 | // the conditions stated in this License. 565 | 566 | // 5. Submission of Contributions. Unless You explicitly state otherwise, 567 | // any Contribution intentionally submitted for inclusion in the Work 568 | // by You to the Licensor shall be under the terms and conditions of 569 | // this License, without any additional terms or conditions. 570 | // Notwithstanding the above, nothing herein shall supersede or modify 571 | // the terms of any separate license agreement you may have executed 572 | // with Licensor regarding such Contributions. 573 | 574 | // 6. Trademarks. This License does not grant permission to use the trade 575 | // names, trademarks, service marks, or product names of the Licensor, 576 | // except as required for reasonable and customary use in describing the 577 | // origin of the Work and reproducing the content of the NOTICE file. 578 | 579 | // 7. Disclaimer of Warranty. Unless required by applicable law or 580 | // agreed to in writing, Licensor provides the Work (and each 581 | // Contributor provides its Contributions) on an "AS IS" BASIS, 582 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 583 | // implied, including, without limitation, any warranties or conditions 584 | // of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 585 | // PARTICULAR PURPOSE. You are solely responsible for determining the 586 | // appropriateness of using or redistributing the Work and assume any 587 | // risks associated with Your exercise of permissions under this License. 588 | 589 | // 8. Limitation of Liability. In no event and under no legal theory, 590 | // whether in tort (including negligence), contract, or otherwise, 591 | // unless required by applicable law (such as deliberate and grossly 592 | // negligent acts) or agreed to in writing, shall any Contributor be 593 | // liable to You for damages, including any direct, indirect, special, 594 | // incidental, or consequential damages of any character arising as a 595 | // result of this License or out of the use or inability to use the 596 | // Work (including but not limited to damages for loss of goodwill, 597 | // work stoppage, computer failure or malfunction, or any and all 598 | // other commercial damages or losses), even if such Contributor 599 | // has been advised of the possibility of such damages. 600 | 601 | // 9. Accepting Warranty or Additional Liability. While redistributing 602 | // the Work or Derivative Works thereof, You may choose to offer, 603 | // and charge a fee for, acceptance of support, warranty, indemnity, 604 | // or other liability obligations and/or rights consistent with this 605 | // License. However, in accepting such obligations, You may act only 606 | // on Your own behalf and on Your sole responsibility, not on behalf 607 | // of any other Contributor, and only if You agree to indemnify, 608 | // defend, and hold each Contributor harmless for any liability 609 | // incurred by, or claims asserted against, such Contributor by reason 610 | // of your accepting any such warranty or additional liability. 611 | 612 | // END OF TERMS AND CONDITIONS 613 | 614 | // APPENDIX: How to apply the Apache License to your work. 615 | 616 | // To apply the Apache License to your work, attach the following 617 | // boilerplate notice, with the fields enclosed by brackets "[]" 618 | // replaced with your own identifying information. (Don't include 619 | // the brackets!) The text should be enclosed in the appropriate 620 | // comment syntax for the file format. We also recommend that a 621 | // file or class name and description of purpose be included on the 622 | // same "printed page" as the copyright notice for easier 623 | // identification within third-party archives. 624 | 625 | // Copyright 2020 DFINITY LLC. 626 | 627 | // Licensed under the Apache License, Version 2.0 (the "License"); 628 | // you may not use this file except in compliance with the License. 629 | // You may obtain a copy of the License at 630 | 631 | // http://www.apache.org/licenses/LICENSE-2.0 632 | 633 | // Unless required by applicable law or agreed to in writing, software 634 | // distributed under the License is distributed on an "AS IS" BASIS, 635 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 636 | // See the License for the specific language governing permissions and 637 | // limitations under the License. 638 | 639 | // https://github.com/dfinity/agent-js/blob/90b073dc735bfae9f3b1c7fc537bd97347c5cc68/packages/principal/src/utils/getCrc.ts 640 | // This file is translated to JavaScript from 641 | // https://lxp32.github.io/docs/a-simple-example-crc32-calculation/ 642 | const lookUpTable: Uint32Array = new Uint32Array([ 643 | 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 644 | 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 645 | 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 646 | 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 647 | 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 648 | 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 649 | 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 650 | 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 651 | 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 652 | 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 653 | 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 654 | 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 655 | 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 656 | 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 657 | 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 658 | 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 659 | 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 660 | 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 661 | 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 662 | 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 663 | 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 664 | 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 665 | 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 666 | 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 667 | 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 668 | 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 669 | 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 670 | 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 671 | 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 672 | 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 673 | 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 674 | 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, 675 | ]); 676 | 677 | /** 678 | * Calculate the CRC32 of an ArrayBufferLike. 679 | * @param buf The BufferLike to calculate the CRC32 of. 680 | */ 681 | export function crc32(buf: ArrayBufferLike): string { 682 | const b = new Uint8Array(buf); 683 | let crc = -1; 684 | 685 | // tslint:disable-next-line:prefer-for-of 686 | for (let i = 0; i < b.length; i++) { 687 | const byte = b[i]; 688 | const t = (byte ^ crc) & 0xff; 689 | crc = lookUpTable[t] ^ (crc >>> 8); 690 | } 691 | 692 | return ((crc ^ -1) >>> 0).toString(16).padStart(8, '0'); 693 | } 694 | 695 | // TODO end crc32 section, put in module once supported --------------------------------------------------------------------------------