├── .envrc ├── .eslintignore ├── .eslintrc.js ├── .github ├── dependabot.yml └── workflows │ ├── programs-e2e.yml │ ├── programs-unit.yml │ └── release.yml ├── .gitignore ├── .husky └── pre-commit ├── .mocharc.js ├── .prettierignore ├── .vscode ├── extensions.json └── settings.json ├── .yarn ├── plugins │ └── @yarnpkg │ │ ├── plugin-interactive-tools.cjs │ │ └── plugin-typescript.cjs ├── releases │ └── yarn-3.2.0.cjs └── sdks │ ├── eslint │ ├── bin │ │ └── eslint.js │ ├── lib │ │ └── api.js │ └── package.json │ ├── integrations.yml │ ├── prettier │ ├── index.js │ └── package.json │ └── typescript │ ├── bin │ ├── tsc │ └── tsserver │ ├── lib │ ├── tsc.js │ ├── tsserver.js │ ├── tsserverlibrary.js │ └── typescript.js │ └── package.json ├── .yarnrc.yml ├── Anchor.toml ├── Cargo.lock ├── Cargo.toml ├── LICENSE.txt ├── README.md ├── ci.nix ├── flake.lock ├── flake.nix ├── images └── banner.png ├── package.json ├── programs ├── crate-redeem-in-kind │ ├── Cargo.toml │ ├── README.md │ ├── Xargo.toml │ └── src │ │ ├── account_validators.rs │ │ ├── events.rs │ │ └── lib.rs └── crate-token │ ├── Cargo.toml │ ├── README.md │ ├── Xargo.toml │ └── src │ ├── account_validators.rs │ ├── events.rs │ ├── lib.rs │ ├── macros.rs │ └── state.rs ├── scripts ├── generate-idl-types.sh └── parse-idls.sh ├── shell.nix ├── src ├── constants.ts ├── crateToken.ts ├── index.ts ├── pda.ts └── programs │ ├── crateRedeemInKind.ts │ ├── crateToken.ts │ └── index.ts ├── tests ├── crate-token.ts ├── fixture-key.json └── workspace.ts ├── tsconfig.build.json ├── tsconfig.esm.json ├── tsconfig.json └── yarn.lock /.envrc: -------------------------------------------------------------------------------- 1 | watch_file flake.nix 2 | watch_file flake.lock 3 | mkdir -p .direnv 4 | dotenv 5 | eval "$(nix print-dev-env --profile "$(direnv_layout_dir)/flake-profile")" 6 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | target/ 2 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | require("@rushstack/eslint-patch/modern-module-resolution"); 2 | 3 | module.exports = { 4 | extends: ["@saberhq/eslint-config"], 5 | parserOptions: { 6 | project: "tsconfig.json", 7 | }, 8 | }; 9 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "daily" 7 | - package-ecosystem: "npm" 8 | directory: "/" 9 | schedule: 10 | interval: "daily" 11 | - package-ecosystem: "cargo" 12 | directory: "/" 13 | schedule: 14 | interval: "daily" 15 | -------------------------------------------------------------------------------- /.github/workflows/programs-e2e.yml: -------------------------------------------------------------------------------- 1 | name: E2E 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | SOLANA_VERSION: "1.9.16" 12 | RUST_TOOLCHAIN: nightly-2021-12-18 13 | 14 | jobs: 15 | sdk: 16 | runs-on: ubuntu-latest 17 | name: Build the SDK 18 | steps: 19 | - uses: actions/checkout@v2 20 | 21 | - uses: cachix/install-nix-action@v16 22 | with: 23 | install_url: https://nixos-nix-install-tests.cachix.org/serve/i6laym9jw3wg9mw6ncyrk6gjx4l34vvx/install 24 | install_options: "--tarball-url-prefix https://nixos-nix-install-tests.cachix.org/serve" 25 | extra_nix_config: | 26 | experimental-features = nix-command flakes 27 | - name: Setup Cachix 28 | uses: cachix/cachix-action@v10 29 | with: 30 | name: crate 31 | extraPullNames: quarry, saber 32 | authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} 33 | - name: Parse IDLs 34 | run: nix shell .#ci --command ./scripts/parse-idls.sh 35 | 36 | - name: Setup Node 37 | uses: actions/setup-node@v3.0.0 38 | - name: Get yarn cache directory path 39 | id: yarn-cache-dir-path 40 | run: echo "::set-output name=dir::$(yarn config get cacheFolder)" 41 | - name: Yarn Cache 42 | uses: actions/cache@v2 43 | with: 44 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 45 | key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }} 46 | restore-keys: | 47 | ${{ runner.os }}-modules- 48 | - name: Install Yarn dependencies 49 | run: yarn install 50 | - run: ./scripts/generate-idl-types.sh 51 | - run: yarn build 52 | - run: yarn typecheck 53 | - run: yarn lint 54 | - run: yarn doctor 55 | 56 | integration-tests: 57 | runs-on: ubuntu-latest 58 | steps: 59 | - uses: actions/checkout@v2 60 | 61 | # Install Rust and Anchor 62 | - name: Install Rust nightly 63 | uses: actions-rs/toolchain@v1 64 | with: 65 | override: true 66 | profile: minimal 67 | toolchain: ${{ env.RUST_TOOLCHAIN }} 68 | - uses: Swatinem/rust-cache@v1 69 | - name: Install Linux dependencies 70 | run: | 71 | sudo apt-get update 72 | sudo apt-get install -y pkg-config build-essential libudev-dev 73 | 74 | # Install Solana 75 | - name: Cache Solana binaries 76 | uses: actions/cache@v2 77 | with: 78 | path: ~/.cache/solana 79 | key: ${{ runner.os }}-${{ env.SOLANA_VERSION }} 80 | - name: Install Solana 81 | run: | 82 | sh -c "$(curl -sSfL https://release.solana.com/v${{ env.SOLANA_VERSION }}/install)" 83 | echo "$HOME/.local/share/solana/install/active_release/bin" >> $GITHUB_PATH 84 | export PATH="/home/runner/.local/share/solana/install/active_release/bin:$PATH" 85 | solana --version 86 | 87 | # Run build 88 | - uses: cachix/install-nix-action@v16 89 | with: 90 | install_url: https://nixos-nix-install-tests.cachix.org/serve/i6laym9jw3wg9mw6ncyrk6gjx4l34vvx/install 91 | install_options: "--tarball-url-prefix https://nixos-nix-install-tests.cachix.org/serve" 92 | extra_nix_config: | 93 | experimental-features = nix-command flakes 94 | - name: Setup Cachix 95 | uses: cachix/cachix-action@v10 96 | with: 97 | name: crate 98 | extraPullNames: quarry, saber 99 | authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} 100 | - name: Build program 101 | run: nix shell .#ci --command anchor build 102 | 103 | - name: Get yarn cache directory path 104 | id: yarn-cache-dir-path 105 | run: echo "::set-output name=dir::$(yarn config get cacheFolder)" 106 | - name: Yarn Cache 107 | uses: actions/cache@v2 108 | with: 109 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 110 | key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }} 111 | restore-keys: | 112 | ${{ runner.os }}-modules- 113 | - name: Setup Node 114 | uses: actions/setup-node@v3.0.0 115 | - run: yarn install 116 | - name: Generate IDL types 117 | run: nix shell .#ci --command yarn idl:generate:nolint 118 | - run: yarn build 119 | - name: Run e2e tests 120 | run: nix shell .#ci --command yarn test:e2e 121 | -------------------------------------------------------------------------------- /.github/workflows/programs-unit.yml: -------------------------------------------------------------------------------- 1 | name: Unit 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | paths: 7 | - .github/workflows/programs-unit.yml 8 | - programs/** 9 | - Cargo.toml 10 | - Cargo.lock 11 | pull_request: 12 | branches: [master] 13 | paths: 14 | - .github/workflows/programs-unit.yml 15 | - programs/** 16 | - Cargo.toml 17 | - Cargo.lock 18 | 19 | env: 20 | CARGO_TERM_COLOR: always 21 | RUST_TOOLCHAIN: nightly-2021-12-18 22 | 23 | jobs: 24 | lint: 25 | runs-on: ubuntu-latest 26 | steps: 27 | - uses: actions/checkout@v2 28 | - name: Install Rust nightly 29 | uses: actions-rs/toolchain@v1 30 | with: 31 | override: true 32 | profile: minimal 33 | toolchain: ${{ env.RUST_TOOLCHAIN }} 34 | components: rustfmt, clippy 35 | - uses: Swatinem/rust-cache@v1 36 | - name: Run fmt 37 | run: cargo fmt -- --check 38 | - name: Run clippy 39 | run: cargo clippy --all-targets -- --deny=warnings 40 | 41 | unit-tests: 42 | runs-on: ubuntu-latest 43 | steps: 44 | - uses: actions/checkout@v2 45 | - name: Install Rust nightly 46 | uses: actions-rs/toolchain@v1 47 | with: 48 | override: true 49 | profile: minimal 50 | toolchain: ${{ env.RUST_TOOLCHAIN }} 51 | components: rustfmt, clippy 52 | - uses: Swatinem/rust-cache@v1 53 | - name: Run unit tests 54 | run: cargo test --lib 55 | 56 | doc: 57 | runs-on: ubuntu-latest 58 | steps: 59 | - uses: actions/checkout@v2 60 | - name: Install Rust nightly 61 | uses: actions-rs/toolchain@v1 62 | with: 63 | override: true 64 | profile: minimal 65 | toolchain: ${{ env.RUST_TOOLCHAIN }} 66 | components: rustfmt, clippy 67 | - uses: Swatinem/rust-cache@v1 68 | - run: cargo doc 69 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | workflow_dispatch: {} 5 | push: 6 | tags: 7 | - "v*.*.*" 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | SOLANA_VERSION: "1.9.1" 12 | RUST_TOOLCHAIN: nightly-2021-12-18 13 | NPM_AUTH_TOKEN: ${{ secrets.NPM_PUBLISH_TOKEN }} 14 | 15 | jobs: 16 | release-sdk: 17 | runs-on: ubuntu-latest 18 | name: Release SDK on NPM 19 | steps: 20 | - uses: actions/checkout@v2 21 | 22 | - uses: cachix/install-nix-action@v16 23 | with: 24 | install_url: https://nixos-nix-install-tests.cachix.org/serve/i6laym9jw3wg9mw6ncyrk6gjx4l34vvx/install 25 | install_options: "--tarball-url-prefix https://nixos-nix-install-tests.cachix.org/serve" 26 | extra_nix_config: | 27 | experimental-features = nix-command flakes 28 | - name: Setup Cachix 29 | uses: cachix/cachix-action@v10 30 | with: 31 | name: crate 32 | extraPullNames: quarry, saber 33 | authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} 34 | 35 | - name: Get yarn cache directory path 36 | id: yarn-cache-dir-path 37 | run: echo "::set-output name=dir::$(yarn config get cacheFolder)" 38 | - name: Yarn Cache 39 | uses: actions/cache@v2 40 | with: 41 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 42 | key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }} 43 | restore-keys: | 44 | ${{ runner.os }}-modules- 45 | - name: Install Yarn dependencies 46 | run: yarn install 47 | - name: Parse IDLs 48 | run: nix shell .#ci --command yarn idl:generate 49 | - run: yarn build 50 | - run: | 51 | echo 'npmAuthToken: "${NPM_AUTH_TOKEN}"' >> .yarnrc.yml 52 | - name: Publish 53 | run: yarn npm publish 54 | 55 | release-crate: 56 | runs-on: ubuntu-latest 57 | name: Release crate on crates.io 58 | steps: 59 | - uses: actions/checkout@v2 60 | - name: Install Rust nightly 61 | uses: actions-rs/toolchain@v1 62 | with: 63 | override: true 64 | profile: minimal 65 | toolchain: ${{ env.RUST_TOOLCHAIN }} 66 | - uses: Swatinem/rust-cache@v1 67 | 68 | - uses: cachix/install-nix-action@v16 69 | with: 70 | install_url: https://nixos-nix-install-tests.cachix.org/serve/i6laym9jw3wg9mw6ncyrk6gjx4l34vvx/install 71 | install_options: "--tarball-url-prefix https://nixos-nix-install-tests.cachix.org/serve" 72 | extra_nix_config: | 73 | experimental-features = nix-command flakes 74 | - name: Setup Cachix 75 | uses: cachix/cachix-action@v10 76 | with: 77 | name: crate 78 | extraPullNames: quarry, saber 79 | authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} 80 | 81 | - name: Publish crates 82 | run: nix shell .#ci --command cargo ws publish --from-git --yes --skip-published --token ${{ secrets.CARGO_PUBLISH_TOKEN }} 83 | 84 | release-binaries: 85 | runs-on: ubuntu-latest 86 | name: Release verifiable binaries 87 | steps: 88 | - uses: actions/checkout@v2 89 | - uses: cachix/install-nix-action@v16 90 | with: 91 | install_url: https://nixos-nix-install-tests.cachix.org/serve/i6laym9jw3wg9mw6ncyrk6gjx4l34vvx/install 92 | install_options: "--tarball-url-prefix https://nixos-nix-install-tests.cachix.org/serve" 93 | extra_nix_config: | 94 | experimental-features = nix-command flakes 95 | - name: Setup Cachix 96 | uses: cachix/cachix-action@v10 97 | with: 98 | name: crate 99 | extraPullNames: quarry, saber 100 | authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} 101 | 102 | - name: Build programs 103 | run: nix shell .#ci --command anchor build --verifiable --solana-version ${{ env.SOLANA_VERSION }} 104 | - name: Release 105 | uses: softprops/action-gh-release@v1 106 | with: 107 | files: | 108 | target/deploy/* 109 | target/idl/* 110 | target/verifiable/* 111 | 112 | build-and-deploy: 113 | runs-on: ubuntu-latest 114 | steps: 115 | - name: Checkout 116 | uses: actions/checkout@v2 117 | 118 | - uses: cachix/install-nix-action@v16 119 | with: 120 | install_url: https://nixos-nix-install-tests.cachix.org/serve/i6laym9jw3wg9mw6ncyrk6gjx4l34vvx/install 121 | install_options: "--tarball-url-prefix https://nixos-nix-install-tests.cachix.org/serve" 122 | extra_nix_config: | 123 | experimental-features = nix-command flakes 124 | - name: Setup Cachix 125 | uses: cachix/cachix-action@v10 126 | with: 127 | name: crate 128 | extraPullNames: quarry, saber 129 | authToken: ${{ secrets.CACHIX_AUTH_TOKEN }} 130 | 131 | - name: Get yarn cache directory path 132 | id: yarn-cache-dir-path 133 | run: echo "::set-output name=dir::$(yarn config get cacheFolder)" 134 | - name: Yarn Cache 135 | uses: actions/cache@v2 136 | with: 137 | path: ${{ steps.yarn-cache-dir-path.outputs.dir }} 138 | key: ${{ runner.os }}-modules-${{ hashFiles('**/yarn.lock') }} 139 | restore-keys: | 140 | ${{ runner.os }}-modules- 141 | - name: Install Yarn dependencies 142 | run: yarn install 143 | - name: Parse IDLs 144 | run: nix shell .#ci --command yarn idl:generate 145 | - run: yarn docs:generate 146 | - run: cp -R images/ site/ 147 | 148 | - name: Deploy 🚀 149 | uses: JamesIves/github-pages-deploy-action@v4.2.5 150 | with: 151 | branch: gh-pages 152 | folder: site 153 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .anchor/ 2 | node_modules/ 3 | artifacts/ 4 | dist/ 5 | target/ 6 | yarn-error.log 7 | 8 | .yarn/* 9 | !.yarn/patches 10 | !.yarn/releases 11 | !.yarn/plugins 12 | !.yarn/sdks 13 | !.yarn/versions 14 | .pnp.* 15 | 16 | artifacts/ 17 | src/idls/ 18 | 19 | .eslintcache 20 | site/ 21 | Captain.toml 22 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn lint-staged 5 | -------------------------------------------------------------------------------- /.mocharc.js: -------------------------------------------------------------------------------- 1 | require("./.pnp.cjs").setup(); 2 | 3 | module.exports = { 4 | timeout: 30_000, 5 | require: [require.resolve("ts-node/register")], 6 | }; 7 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .yarn/ 2 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "arcanis.vscode-zipfs", 4 | "dbaeumer.vscode-eslint", 5 | "esbenp.prettier-vscode" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "search.exclude": { 3 | "**/.yarn": true, 4 | "**/.pnp.*": true 5 | }, 6 | "eslint.nodePath": ".yarn/sdks", 7 | "typescript.tsdk": ".yarn/sdks/typescript/lib", 8 | "typescript.enablePromptUseWorkspaceTsdk": true, 9 | "prettier.prettierPath": ".yarn/sdks/prettier/index.js" 10 | } 11 | -------------------------------------------------------------------------------- /.yarn/plugins/@yarnpkg/plugin-typescript.cjs: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | //prettier-ignore 3 | module.exports = { 4 | name: "@yarnpkg/plugin-typescript", 5 | factory: function (require) { 6 | var plugin=(()=>{var Ft=Object.create,H=Object.defineProperty,Bt=Object.defineProperties,Kt=Object.getOwnPropertyDescriptor,zt=Object.getOwnPropertyDescriptors,Gt=Object.getOwnPropertyNames,Q=Object.getOwnPropertySymbols,$t=Object.getPrototypeOf,ne=Object.prototype.hasOwnProperty,De=Object.prototype.propertyIsEnumerable;var Re=(e,t,r)=>t in e?H(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,u=(e,t)=>{for(var r in t||(t={}))ne.call(t,r)&&Re(e,r,t[r]);if(Q)for(var r of Q(t))De.call(t,r)&&Re(e,r,t[r]);return e},g=(e,t)=>Bt(e,zt(t)),Lt=e=>H(e,"__esModule",{value:!0});var R=(e,t)=>{var r={};for(var s in e)ne.call(e,s)&&t.indexOf(s)<0&&(r[s]=e[s]);if(e!=null&&Q)for(var s of Q(e))t.indexOf(s)<0&&De.call(e,s)&&(r[s]=e[s]);return r};var I=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Vt=(e,t)=>{for(var r in t)H(e,r,{get:t[r],enumerable:!0})},Qt=(e,t,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Gt(t))!ne.call(e,s)&&s!=="default"&&H(e,s,{get:()=>t[s],enumerable:!(r=Kt(t,s))||r.enumerable});return e},C=e=>Qt(Lt(H(e!=null?Ft($t(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e);var xe=I(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});function _(e){let t=[...e.caches],r=t.shift();return r===void 0?ve():{get(s,n,a={miss:()=>Promise.resolve()}){return r.get(s,n,a).catch(()=>_({caches:t}).get(s,n,a))},set(s,n){return r.set(s,n).catch(()=>_({caches:t}).set(s,n))},delete(s){return r.delete(s).catch(()=>_({caches:t}).delete(s))},clear(){return r.clear().catch(()=>_({caches:t}).clear())}}}function ve(){return{get(e,t,r={miss:()=>Promise.resolve()}){return t().then(n=>Promise.all([n,r.miss(n)])).then(([n])=>n)},set(e,t){return Promise.resolve(t)},delete(e){return Promise.resolve()},clear(){return Promise.resolve()}}}J.createFallbackableCache=_;J.createNullCache=ve});var Ee=I(($s,qe)=>{qe.exports=xe()});var Te=I(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});function Jt(e={serializable:!0}){let t={};return{get(r,s,n={miss:()=>Promise.resolve()}){let a=JSON.stringify(r);if(a in t)return Promise.resolve(e.serializable?JSON.parse(t[a]):t[a]);let o=s(),d=n&&n.miss||(()=>Promise.resolve());return o.then(y=>d(y)).then(()=>o)},set(r,s){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(s):s,Promise.resolve(s)},delete(r){return delete t[JSON.stringify(r)],Promise.resolve()},clear(){return t={},Promise.resolve()}}}ae.createInMemoryCache=Jt});var we=I((Vs,Me)=>{Me.exports=Te()});var Ce=I(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});function Xt(e,t,r){let s={"x-algolia-api-key":r,"x-algolia-application-id":t};return{headers(){return e===oe.WithinHeaders?s:{}},queryParameters(){return e===oe.WithinQueryParameters?s:{}}}}function Yt(e){let t=0,r=()=>(t++,new Promise(s=>{setTimeout(()=>{s(e(r))},Math.min(100*t,1e3))}));return e(r)}function ke(e,t=(r,s)=>Promise.resolve()){return Object.assign(e,{wait(r){return ke(e.then(s=>Promise.all([t(s,r),s])).then(s=>s[1]))}})}function Zt(e){let t=e.length-1;for(t;t>0;t--){let r=Math.floor(Math.random()*(t+1)),s=e[t];e[t]=e[r],e[r]=s}return e}function er(e,t){return Object.keys(t!==void 0?t:{}).forEach(r=>{e[r]=t[r](e)}),e}function tr(e,...t){let r=0;return e.replace(/%s/g,()=>encodeURIComponent(t[r++]))}var rr="4.2.0",sr=e=>()=>e.transporter.requester.destroy(),oe={WithinQueryParameters:0,WithinHeaders:1};M.AuthMode=oe;M.addMethods=er;M.createAuth=Xt;M.createRetryablePromise=Yt;M.createWaitablePromise=ke;M.destroy=sr;M.encode=tr;M.shuffle=Zt;M.version=rr});var F=I((Js,Ue)=>{Ue.exports=Ce()});var Ne=I(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});var nr={Delete:"DELETE",Get:"GET",Post:"POST",Put:"PUT"};ie.MethodEnum=nr});var B=I((Ys,We)=>{We.exports=Ne()});var Ze=I(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});var He=B();function ce(e,t){let r=e||{},s=r.data||{};return Object.keys(r).forEach(n=>{["timeout","headers","queryParameters","data","cacheable"].indexOf(n)===-1&&(s[n]=r[n])}),{data:Object.entries(s).length>0?s:void 0,timeout:r.timeout||t,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var X={Read:1,Write:2,Any:3},U={Up:1,Down:2,Timeouted:3},_e=2*60*1e3;function ue(e,t=U.Up){return g(u({},e),{status:t,lastUpdate:Date.now()})}function Fe(e){return e.status===U.Up||Date.now()-e.lastUpdate>_e}function Be(e){return e.status===U.Timeouted&&Date.now()-e.lastUpdate<=_e}function le(e){return{protocol:e.protocol||"https",url:e.url,accept:e.accept||X.Any}}function ar(e,t){return Promise.all(t.map(r=>e.get(r,()=>Promise.resolve(ue(r))))).then(r=>{let s=r.filter(d=>Fe(d)),n=r.filter(d=>Be(d)),a=[...s,...n],o=a.length>0?a.map(d=>le(d)):t;return{getTimeout(d,y){return(n.length===0&&d===0?1:n.length+3+d)*y},statelessHosts:o}})}var or=({isTimedOut:e,status:t})=>!e&&~~t==0,ir=e=>{let t=e.status;return e.isTimedOut||or(e)||~~(t/100)!=2&&~~(t/100)!=4},cr=({status:e})=>~~(e/100)==2,ur=(e,t)=>ir(e)?t.onRetry(e):cr(e)?t.onSucess(e):t.onFail(e);function Qe(e,t,r,s){let n=[],a=$e(r,s),o=Le(e,s),d=r.method,y=r.method!==He.MethodEnum.Get?{}:u(u({},r.data),s.data),b=u(u(u({"x-algolia-agent":e.userAgent.value},e.queryParameters),y),s.queryParameters),f=0,p=(h,S)=>{let O=h.pop();if(O===void 0)throw Ve(de(n));let P={data:a,headers:o,method:d,url:Ge(O,r.path,b),connectTimeout:S(f,e.timeouts.connect),responseTimeout:S(f,s.timeout)},x=j=>{let T={request:P,response:j,host:O,triesLeft:h.length};return n.push(T),T},v={onSucess:j=>Ke(j),onRetry(j){let T=x(j);return j.isTimedOut&&f++,Promise.all([e.logger.info("Retryable failure",pe(T)),e.hostsCache.set(O,ue(O,j.isTimedOut?U.Timeouted:U.Down))]).then(()=>p(h,S))},onFail(j){throw x(j),ze(j,de(n))}};return e.requester.send(P).then(j=>ur(j,v))};return ar(e.hostsCache,t).then(h=>p([...h.statelessHosts].reverse(),h.getTimeout))}function lr(e){let{hostsCache:t,logger:r,requester:s,requestsCache:n,responsesCache:a,timeouts:o,userAgent:d,hosts:y,queryParameters:b,headers:f}=e,p={hostsCache:t,logger:r,requester:s,requestsCache:n,responsesCache:a,timeouts:o,userAgent:d,headers:f,queryParameters:b,hosts:y.map(h=>le(h)),read(h,S){let O=ce(S,p.timeouts.read),P=()=>Qe(p,p.hosts.filter(j=>(j.accept&X.Read)!=0),h,O);if((O.cacheable!==void 0?O.cacheable:h.cacheable)!==!0)return P();let v={request:h,mappedRequestOptions:O,transporter:{queryParameters:p.queryParameters,headers:p.headers}};return p.responsesCache.get(v,()=>p.requestsCache.get(v,()=>p.requestsCache.set(v,P()).then(j=>Promise.all([p.requestsCache.delete(v),j]),j=>Promise.all([p.requestsCache.delete(v),Promise.reject(j)])).then(([j,T])=>T)),{miss:j=>p.responsesCache.set(v,j)})},write(h,S){return Qe(p,p.hosts.filter(O=>(O.accept&X.Write)!=0),h,ce(S,p.timeouts.write))}};return p}function dr(e){let t={value:`Algolia for JavaScript (${e})`,add(r){let s=`; ${r.segment}${r.version!==void 0?` (${r.version})`:""}`;return t.value.indexOf(s)===-1&&(t.value=`${t.value}${s}`),t}};return t}function Ke(e){try{return JSON.parse(e.content)}catch(t){throw Je(t.message,e)}}function ze({content:e,status:t},r){let s=e;try{s=JSON.parse(e).message}catch(n){}return Xe(s,t,r)}function pr(e,...t){let r=0;return e.replace(/%s/g,()=>encodeURIComponent(t[r++]))}function Ge(e,t,r){let s=Ye(r),n=`${e.protocol}://${e.url}/${t.charAt(0)==="/"?t.substr(1):t}`;return s.length&&(n+=`?${s}`),n}function Ye(e){let t=r=>Object.prototype.toString.call(r)==="[object Object]"||Object.prototype.toString.call(r)==="[object Array]";return Object.keys(e).map(r=>pr("%s=%s",r,t(e[r])?JSON.stringify(e[r]):e[r])).join("&")}function $e(e,t){if(e.method===He.MethodEnum.Get||e.data===void 0&&t.data===void 0)return;let r=Array.isArray(e.data)?e.data:u(u({},e.data),t.data);return JSON.stringify(r)}function Le(e,t){let r=u(u({},e.headers),t.headers),s={};return Object.keys(r).forEach(n=>{let a=r[n];s[n.toLowerCase()]=a}),s}function de(e){return e.map(t=>pe(t))}function pe(e){let t=e.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return g(u({},e),{request:g(u({},e.request),{headers:u(u({},e.request.headers),t)})})}function Xe(e,t,r){return{name:"ApiError",message:e,status:t,transporterStackTrace:r}}function Je(e,t){return{name:"DeserializationError",message:e,response:t}}function Ve(e){return{name:"RetryError",message:"Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.",transporterStackTrace:e}}A.CallEnum=X;A.HostStatusEnum=U;A.createApiError=Xe;A.createDeserializationError=Je;A.createMappedRequestOptions=ce;A.createRetryError=Ve;A.createStatefulHost=ue;A.createStatelessHost=le;A.createTransporter=lr;A.createUserAgent=dr;A.deserializeFailure=ze;A.deserializeSuccess=Ke;A.isStatefulHostTimeouted=Be;A.isStatefulHostUp=Fe;A.serializeData=$e;A.serializeHeaders=Le;A.serializeQueryParameters=Ye;A.serializeUrl=Ge;A.stackFrameWithoutCredentials=pe;A.stackTraceWithoutCredentials=de});var K=I((en,et)=>{et.exports=Ze()});var tt=I(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});var N=F(),mr=K(),z=B(),hr=e=>{let t=e.region||"us",r=N.createAuth(N.AuthMode.WithinHeaders,e.appId,e.apiKey),s=mr.createTransporter(g(u({hosts:[{url:`analytics.${t}.algolia.com`}]},e),{headers:u(g(u({},r.headers()),{"content-type":"application/json"}),e.headers),queryParameters:u(u({},r.queryParameters()),e.queryParameters)})),n=e.appId;return N.addMethods({appId:n,transporter:s},e.methods)},yr=e=>(t,r)=>e.transporter.write({method:z.MethodEnum.Post,path:"2/abtests",data:t},r),gr=e=>(t,r)=>e.transporter.write({method:z.MethodEnum.Delete,path:N.encode("2/abtests/%s",t)},r),fr=e=>(t,r)=>e.transporter.read({method:z.MethodEnum.Get,path:N.encode("2/abtests/%s",t)},r),br=e=>t=>e.transporter.read({method:z.MethodEnum.Get,path:"2/abtests"},t),Pr=e=>(t,r)=>e.transporter.write({method:z.MethodEnum.Post,path:N.encode("2/abtests/%s/stop",t)},r);w.addABTest=yr;w.createAnalyticsClient=hr;w.deleteABTest=gr;w.getABTest=fr;w.getABTests=br;w.stopABTest=Pr});var st=I((rn,rt)=>{rt.exports=tt()});var at=I(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});var me=F(),jr=K(),nt=B(),Or=e=>{let t=e.region||"us",r=me.createAuth(me.AuthMode.WithinHeaders,e.appId,e.apiKey),s=jr.createTransporter(g(u({hosts:[{url:`recommendation.${t}.algolia.com`}]},e),{headers:u(g(u({},r.headers()),{"content-type":"application/json"}),e.headers),queryParameters:u(u({},r.queryParameters()),e.queryParameters)}));return me.addMethods({appId:e.appId,transporter:s},e.methods)},Ir=e=>t=>e.transporter.read({method:nt.MethodEnum.Get,path:"1/strategies/personalization"},t),Ar=e=>(t,r)=>e.transporter.write({method:nt.MethodEnum.Post,path:"1/strategies/personalization",data:t},r);G.createRecommendationClient=Or;G.getPersonalizationStrategy=Ir;G.setPersonalizationStrategy=Ar});var it=I((nn,ot)=>{ot.exports=at()});var jt=I(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0});var l=F(),q=K(),m=B(),Sr=require("crypto");function Y(e){let t=r=>e.request(r).then(s=>{if(e.batch!==void 0&&e.batch(s.hits),!e.shouldStop(s))return s.cursor?t({cursor:s.cursor}):t({page:(r.page||0)+1})});return t({})}var Dr=e=>{let t=e.appId,r=l.createAuth(e.authMode!==void 0?e.authMode:l.AuthMode.WithinHeaders,t,e.apiKey),s=q.createTransporter(g(u({hosts:[{url:`${t}-dsn.algolia.net`,accept:q.CallEnum.Read},{url:`${t}.algolia.net`,accept:q.CallEnum.Write}].concat(l.shuffle([{url:`${t}-1.algolianet.com`},{url:`${t}-2.algolianet.com`},{url:`${t}-3.algolianet.com`}]))},e),{headers:u(g(u({},r.headers()),{"content-type":"application/x-www-form-urlencoded"}),e.headers),queryParameters:u(u({},r.queryParameters()),e.queryParameters)})),n={transporter:s,appId:t,addAlgoliaAgent(a,o){s.userAgent.add({segment:a,version:o})},clearCache(){return Promise.all([s.requestsCache.clear(),s.responsesCache.clear()]).then(()=>{})}};return l.addMethods(n,e.methods)};function ct(){return{name:"MissingObjectIDError",message:"All objects must have an unique objectID (like a primary key) to be valid. Algolia is also able to generate objectIDs automatically but *it's not recommended*. To do it, use the `{'autoGenerateObjectIDIfNotExist': true}` option."}}function ut(){return{name:"ObjectNotFoundError",message:"Object not found."}}function lt(){return{name:"ValidUntilNotFoundError",message:"ValidUntil not found in given secured api key."}}var Rr=e=>(t,r)=>{let d=r||{},{queryParameters:s}=d,n=R(d,["queryParameters"]),a=u({acl:t},s!==void 0?{queryParameters:s}:{}),o=(y,b)=>l.createRetryablePromise(f=>$(e)(y.key,b).catch(p=>{if(p.status!==404)throw p;return f()}));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:"1/keys",data:a},n),o)},vr=e=>(t,r,s)=>{let n=q.createMappedRequestOptions(s);return n.queryParameters["X-Algolia-User-ID"]=t,e.transporter.write({method:m.MethodEnum.Post,path:"1/clusters/mapping",data:{cluster:r}},n)},xr=e=>(t,r,s)=>e.transporter.write({method:m.MethodEnum.Post,path:"1/clusters/mapping/batch",data:{users:t,cluster:r}},s),Z=e=>(t,r,s)=>{let n=(a,o)=>L(e)(t,{methods:{waitTask:D}}).waitTask(a.taskID,o);return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/operation",t),data:{operation:"copy",destination:r}},s),n)},qr=e=>(t,r,s)=>Z(e)(t,r,g(u({},s),{scope:[ee.Rules]})),Er=e=>(t,r,s)=>Z(e)(t,r,g(u({},s),{scope:[ee.Settings]})),Tr=e=>(t,r,s)=>Z(e)(t,r,g(u({},s),{scope:[ee.Synonyms]})),Mr=e=>(t,r)=>{let s=(n,a)=>l.createRetryablePromise(o=>$(e)(t,a).then(o).catch(d=>{if(d.status!==404)throw d}));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Delete,path:l.encode("1/keys/%s",t)},r),s)},wr=()=>(e,t)=>{let r=q.serializeQueryParameters(t),s=Sr.createHmac("sha256",e).update(r).digest("hex");return Buffer.from(s+r).toString("base64")},$=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/keys/%s",t)},r),kr=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/logs"},t),Cr=()=>e=>{let t=Buffer.from(e,"base64").toString("ascii"),r=/validUntil=(\d+)/,s=t.match(r);if(s===null)throw lt();return parseInt(s[1],10)-Math.round(new Date().getTime()/1e3)},Ur=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/clusters/mapping/top"},t),Nr=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/clusters/mapping/%s",t)},r),Wr=e=>t=>{let n=t||{},{retrieveMappings:r}=n,s=R(n,["retrieveMappings"]);return r===!0&&(s.getClusters=!0),e.transporter.read({method:m.MethodEnum.Get,path:"1/clusters/mapping/pending"},s)},L=e=>(t,r={})=>{let s={transporter:e.transporter,appId:e.appId,indexName:t};return l.addMethods(s,r.methods)},Hr=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/keys"},t),_r=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/clusters"},t),Fr=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/indexes"},t),Br=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:"1/clusters/mapping"},t),Kr=e=>(t,r,s)=>{let n=(a,o)=>L(e)(t,{methods:{waitTask:D}}).waitTask(a.taskID,o);return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/operation",t),data:{operation:"move",destination:r}},s),n)},zr=e=>(t,r)=>{let s=(n,a)=>Promise.all(Object.keys(n.taskID).map(o=>L(e)(o,{methods:{waitTask:D}}).waitTask(n.taskID[o],a)));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:"1/indexes/*/batch",data:{requests:t}},r),s)},Gr=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:"1/indexes/*/objects",data:{requests:t}},r),$r=e=>(t,r)=>{let s=t.map(n=>g(u({},n),{params:q.serializeQueryParameters(n.params||{})}));return e.transporter.read({method:m.MethodEnum.Post,path:"1/indexes/*/queries",data:{requests:s},cacheable:!0},r)},Lr=e=>(t,r)=>Promise.all(t.map(s=>{let d=s.params,{facetName:n,facetQuery:a}=d,o=R(d,["facetName","facetQuery"]);return L(e)(s.indexName,{methods:{searchForFacetValues:dt}}).searchForFacetValues(n,a,u(u({},r),o))})),Vr=e=>(t,r)=>{let s=q.createMappedRequestOptions(r);return s.queryParameters["X-Algolia-User-ID"]=t,e.transporter.write({method:m.MethodEnum.Delete,path:"1/clusters/mapping"},s)},Qr=e=>(t,r)=>{let s=(n,a)=>l.createRetryablePromise(o=>$(e)(t,a).catch(d=>{if(d.status!==404)throw d;return o()}));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/keys/%s/restore",t)},r),s)},Jr=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:"1/clusters/mapping/search",data:{query:t}},r),Xr=e=>(t,r)=>{let s=Object.assign({},r),f=r||{},{queryParameters:n}=f,a=R(f,["queryParameters"]),o=n?{queryParameters:n}:{},d=["acl","indexes","referers","restrictSources","queryParameters","description","maxQueriesPerIPPerHour","maxHitsPerQuery"],y=p=>Object.keys(s).filter(h=>d.indexOf(h)!==-1).every(h=>p[h]===s[h]),b=(p,h)=>l.createRetryablePromise(S=>$(e)(t,h).then(O=>y(O)?Promise.resolve():S()));return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Put,path:l.encode("1/keys/%s",t),data:o},a),b)},pt=e=>(t,r)=>{let s=(n,a)=>D(e)(n.taskID,a);return l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/batch",e.indexName),data:{requests:t}},r),s)},Yr=e=>t=>Y(g(u({},t),{shouldStop:r=>r.cursor===void 0,request:r=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/browse",e.indexName),data:r},t)})),Zr=e=>t=>{let r=u({hitsPerPage:1e3},t);return Y(g(u({},r),{shouldStop:s=>s.hits.lengthg(u({},n),{hits:n.hits.map(a=>(delete a._highlightResult,a))}))}}))},es=e=>t=>{let r=u({hitsPerPage:1e3},t);return Y(g(u({},r),{shouldStop:s=>s.hits.lengthg(u({},n),{hits:n.hits.map(a=>(delete a._highlightResult,a))}))}}))},te=e=>(t,r,s)=>{let y=s||{},{batchSize:n}=y,a=R(y,["batchSize"]),o={taskIDs:[],objectIDs:[]},d=(b=0)=>{let f=[],p;for(p=b;p({action:r,body:h})),a).then(h=>(o.objectIDs=o.objectIDs.concat(h.objectIDs),o.taskIDs.push(h.taskID),p++,d(p)))};return l.createWaitablePromise(d(),(b,f)=>Promise.all(b.taskIDs.map(p=>D(e)(p,f))))},ts=e=>t=>l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/clear",e.indexName)},t),(r,s)=>D(e)(r.taskID,s)),rs=e=>t=>{let a=t||{},{forwardToReplicas:r}=a,s=R(a,["forwardToReplicas"]),n=q.createMappedRequestOptions(s);return r&&(n.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/rules/clear",e.indexName)},n),(o,d)=>D(e)(o.taskID,d))},ss=e=>t=>{let a=t||{},{forwardToReplicas:r}=a,s=R(a,["forwardToReplicas"]),n=q.createMappedRequestOptions(s);return r&&(n.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/synonyms/clear",e.indexName)},n),(o,d)=>D(e)(o.taskID,d))},ns=e=>(t,r)=>l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/deleteByQuery",e.indexName),data:t},r),(s,n)=>D(e)(s.taskID,n)),as=e=>t=>l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Delete,path:l.encode("1/indexes/%s",e.indexName)},t),(r,s)=>D(e)(r.taskID,s)),os=e=>(t,r)=>l.createWaitablePromise(yt(e)([t],r).then(s=>({taskID:s.taskIDs[0]})),(s,n)=>D(e)(s.taskID,n)),yt=e=>(t,r)=>{let s=t.map(n=>({objectID:n}));return te(e)(s,k.DeleteObject,r)},is=e=>(t,r)=>{let o=r||{},{forwardToReplicas:s}=o,n=R(o,["forwardToReplicas"]),a=q.createMappedRequestOptions(n);return s&&(a.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Delete,path:l.encode("1/indexes/%s/rules/%s",e.indexName,t)},a),(d,y)=>D(e)(d.taskID,y))},cs=e=>(t,r)=>{let o=r||{},{forwardToReplicas:s}=o,n=R(o,["forwardToReplicas"]),a=q.createMappedRequestOptions(n);return s&&(a.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Delete,path:l.encode("1/indexes/%s/synonyms/%s",e.indexName,t)},a),(d,y)=>D(e)(d.taskID,y))},us=e=>t=>gt(e)(t).then(()=>!0).catch(r=>{if(r.status!==404)throw r;return!1}),ls=e=>(t,r)=>{let y=r||{},{query:s,paginate:n}=y,a=R(y,["query","paginate"]),o=0,d=()=>ft(e)(s||"",g(u({},a),{page:o})).then(b=>{for(let[f,p]of Object.entries(b.hits))if(t(p))return{object:p,position:parseInt(f,10),page:o};if(o++,n===!1||o>=b.nbPages)throw ut();return d()});return d()},ds=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/%s",e.indexName,t)},r),ps=()=>(e,t)=>{for(let[r,s]of Object.entries(e.hits))if(s.objectID===t)return parseInt(r,10);return-1},ms=e=>(t,r)=>{let o=r||{},{attributesToRetrieve:s}=o,n=R(o,["attributesToRetrieve"]),a=t.map(d=>u({indexName:e.indexName,objectID:d},s?{attributesToRetrieve:s}:{}));return e.transporter.read({method:m.MethodEnum.Post,path:"1/indexes/*/objects",data:{requests:a}},n)},hs=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/rules/%s",e.indexName,t)},r),gt=e=>t=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/settings",e.indexName),data:{getVersion:2}},t),ys=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/synonyms/%s",e.indexName,t)},r),bt=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Get,path:l.encode("1/indexes/%s/task/%s",e.indexName,t.toString())},r),gs=e=>(t,r)=>l.createWaitablePromise(Pt(e)([t],r).then(s=>({objectID:s.objectIDs[0],taskID:s.taskIDs[0]})),(s,n)=>D(e)(s.taskID,n)),Pt=e=>(t,r)=>{let o=r||{},{createIfNotExists:s}=o,n=R(o,["createIfNotExists"]),a=s?k.PartialUpdateObject:k.PartialUpdateObjectNoCreate;return te(e)(t,a,n)},fs=e=>(t,r)=>{let O=r||{},{safe:s,autoGenerateObjectIDIfNotExist:n,batchSize:a}=O,o=R(O,["safe","autoGenerateObjectIDIfNotExist","batchSize"]),d=(P,x,v,j)=>l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/operation",P),data:{operation:v,destination:x}},j),(T,V)=>D(e)(T.taskID,V)),y=Math.random().toString(36).substring(7),b=`${e.indexName}_tmp_${y}`,f=he({appId:e.appId,transporter:e.transporter,indexName:b}),p=[],h=d(e.indexName,b,"copy",g(u({},o),{scope:["settings","synonyms","rules"]}));p.push(h);let S=(s?h.wait(o):h).then(()=>{let P=f(t,g(u({},o),{autoGenerateObjectIDIfNotExist:n,batchSize:a}));return p.push(P),s?P.wait(o):P}).then(()=>{let P=d(b,e.indexName,"move",o);return p.push(P),s?P.wait(o):P}).then(()=>Promise.all(p)).then(([P,x,v])=>({objectIDs:x.objectIDs,taskIDs:[P.taskID,...x.taskIDs,v.taskID]}));return l.createWaitablePromise(S,(P,x)=>Promise.all(p.map(v=>v.wait(x))))},bs=e=>(t,r)=>ye(e)(t,g(u({},r),{clearExistingRules:!0})),Ps=e=>(t,r)=>ge(e)(t,g(u({},r),{replaceExistingSynonyms:!0})),js=e=>(t,r)=>l.createWaitablePromise(he(e)([t],r).then(s=>({objectID:s.objectIDs[0],taskID:s.taskIDs[0]})),(s,n)=>D(e)(s.taskID,n)),he=e=>(t,r)=>{let o=r||{},{autoGenerateObjectIDIfNotExist:s}=o,n=R(o,["autoGenerateObjectIDIfNotExist"]),a=s?k.AddObject:k.UpdateObject;if(a===k.UpdateObject){for(let d of t)if(d.objectID===void 0)return l.createWaitablePromise(Promise.reject(ct()))}return te(e)(t,a,n)},Os=e=>(t,r)=>ye(e)([t],r),ye=e=>(t,r)=>{let d=r||{},{forwardToReplicas:s,clearExistingRules:n}=d,a=R(d,["forwardToReplicas","clearExistingRules"]),o=q.createMappedRequestOptions(a);return s&&(o.queryParameters.forwardToReplicas=1),n&&(o.queryParameters.clearExistingRules=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/rules/batch",e.indexName),data:t},o),(y,b)=>D(e)(y.taskID,b))},Is=e=>(t,r)=>ge(e)([t],r),ge=e=>(t,r)=>{let d=r||{},{forwardToReplicas:s,replaceExistingSynonyms:n}=d,a=R(d,["forwardToReplicas","replaceExistingSynonyms"]),o=q.createMappedRequestOptions(a);return s&&(o.queryParameters.forwardToReplicas=1),n&&(o.queryParameters.replaceExistingSynonyms=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/synonyms/batch",e.indexName),data:t},o),(y,b)=>D(e)(y.taskID,b))},ft=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/query",e.indexName),data:{query:t},cacheable:!0},r),dt=e=>(t,r,s)=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/facets/%s/query",e.indexName,t),data:{facetQuery:r},cacheable:!0},s),mt=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/rules/search",e.indexName),data:{query:t}},r),ht=e=>(t,r)=>e.transporter.read({method:m.MethodEnum.Post,path:l.encode("1/indexes/%s/synonyms/search",e.indexName),data:{query:t}},r),As=e=>(t,r)=>{let o=r||{},{forwardToReplicas:s}=o,n=R(o,["forwardToReplicas"]),a=q.createMappedRequestOptions(n);return s&&(a.queryParameters.forwardToReplicas=1),l.createWaitablePromise(e.transporter.write({method:m.MethodEnum.Put,path:l.encode("1/indexes/%s/settings",e.indexName),data:t},a),(d,y)=>D(e)(d.taskID,y))},D=e=>(t,r)=>l.createRetryablePromise(s=>bt(e)(t,r).then(n=>n.status!=="published"?s():void 0)),Ss={AddObject:"addObject",Analytics:"analytics",Browser:"browse",DeleteIndex:"deleteIndex",DeleteObject:"deleteObject",EditSettings:"editSettings",ListIndexes:"listIndexes",Logs:"logs",Recommendation:"recommendation",Search:"search",SeeUnretrievableAttributes:"seeUnretrievableAttributes",Settings:"settings",Usage:"usage"},k={AddObject:"addObject",UpdateObject:"updateObject",PartialUpdateObject:"partialUpdateObject",PartialUpdateObjectNoCreate:"partialUpdateObjectNoCreate",DeleteObject:"deleteObject"},ee={Settings:"settings",Synonyms:"synonyms",Rules:"rules"},Ds={None:"none",StopIfEnoughMatches:"stopIfEnoughMatches"},Rs={Synonym:"synonym",OneWaySynonym:"oneWaySynonym",AltCorrection1:"altCorrection1",AltCorrection2:"altCorrection2",Placeholder:"placeholder"};i.ApiKeyACLEnum=Ss;i.BatchActionEnum=k;i.ScopeEnum=ee;i.StrategyEnum=Ds;i.SynonymEnum=Rs;i.addApiKey=Rr;i.assignUserID=vr;i.assignUserIDs=xr;i.batch=pt;i.browseObjects=Yr;i.browseRules=Zr;i.browseSynonyms=es;i.chunkedBatch=te;i.clearObjects=ts;i.clearRules=rs;i.clearSynonyms=ss;i.copyIndex=Z;i.copyRules=qr;i.copySettings=Er;i.copySynonyms=Tr;i.createBrowsablePromise=Y;i.createMissingObjectIDError=ct;i.createObjectNotFoundError=ut;i.createSearchClient=Dr;i.createValidUntilNotFoundError=lt;i.deleteApiKey=Mr;i.deleteBy=ns;i.deleteIndex=as;i.deleteObject=os;i.deleteObjects=yt;i.deleteRule=is;i.deleteSynonym=cs;i.exists=us;i.findObject=ls;i.generateSecuredApiKey=wr;i.getApiKey=$;i.getLogs=kr;i.getObject=ds;i.getObjectPosition=ps;i.getObjects=ms;i.getRule=hs;i.getSecuredApiKeyRemainingValidity=Cr;i.getSettings=gt;i.getSynonym=ys;i.getTask=bt;i.getTopUserIDs=Ur;i.getUserID=Nr;i.hasPendingMappings=Wr;i.initIndex=L;i.listApiKeys=Hr;i.listClusters=_r;i.listIndices=Fr;i.listUserIDs=Br;i.moveIndex=Kr;i.multipleBatch=zr;i.multipleGetObjects=Gr;i.multipleQueries=$r;i.multipleSearchForFacetValues=Lr;i.partialUpdateObject=gs;i.partialUpdateObjects=Pt;i.removeUserID=Vr;i.replaceAllObjects=fs;i.replaceAllRules=bs;i.replaceAllSynonyms=Ps;i.restoreApiKey=Qr;i.saveObject=js;i.saveObjects=he;i.saveRule=Os;i.saveRules=ye;i.saveSynonym=Is;i.saveSynonyms=ge;i.search=ft;i.searchForFacetValues=dt;i.searchRules=mt;i.searchSynonyms=ht;i.searchUserIDs=Jr;i.setSettings=As;i.updateApiKey=Xr;i.waitTask=D});var It=I((on,Ot)=>{Ot.exports=jt()});var At=I(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});function vs(){return{debug(e,t){return Promise.resolve()},info(e,t){return Promise.resolve()},error(e,t){return Promise.resolve()}}}var xs={Debug:1,Info:2,Error:3};re.LogLevelEnum=xs;re.createNullLogger=vs});var Dt=I((un,St)=>{St.exports=At()});var xt=I(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});var Rt=require("http"),vt=require("https"),qs=require("url");function Es(){let e={keepAlive:!0},t=new Rt.Agent(e),r=new vt.Agent(e);return{send(s){return new Promise(n=>{let a=qs.parse(s.url),o=a.query===null?a.pathname:`${a.pathname}?${a.query}`,d=u({agent:a.protocol==="https:"?r:t,hostname:a.hostname,path:o,method:s.method,headers:s.headers},a.port!==void 0?{port:a.port||""}:{}),y=(a.protocol==="https:"?vt:Rt).request(d,h=>{let S="";h.on("data",O=>S+=O),h.on("end",()=>{clearTimeout(f),clearTimeout(p),n({status:h.statusCode||0,content:S,isTimedOut:!1})})}),b=(h,S)=>setTimeout(()=>{y.abort(),n({status:0,content:S,isTimedOut:!0})},h*1e3),f=b(s.connectTimeout,"Connection timeout"),p;y.on("error",h=>{clearTimeout(f),clearTimeout(p),n({status:0,content:h.message,isTimedOut:!1})}),y.once("response",()=>{clearTimeout(f),p=b(s.responseTimeout,"Socket timeout")}),s.data!==void 0&&y.write(s.data),y.end()})},destroy(){return t.destroy(),r.destroy(),Promise.resolve()}}}fe.createNodeHttpRequester=Es});var Et=I((dn,qt)=>{qt.exports=xt()});var kt=I((pn,Tt)=>{"use strict";var Mt=Ee(),Ts=we(),W=st(),be=F(),Pe=it(),c=It(),Ms=Dt(),ws=Et(),ks=K();function wt(e,t,r){let s={appId:e,apiKey:t,timeouts:{connect:2,read:5,write:30},requester:ws.createNodeHttpRequester(),logger:Ms.createNullLogger(),responsesCache:Mt.createNullCache(),requestsCache:Mt.createNullCache(),hostsCache:Ts.createInMemoryCache(),userAgent:ks.createUserAgent(be.version).add({segment:"Node.js",version:process.versions.node})};return c.createSearchClient(g(u(u({},s),r),{methods:{search:c.multipleQueries,searchForFacetValues:c.multipleSearchForFacetValues,multipleBatch:c.multipleBatch,multipleGetObjects:c.multipleGetObjects,multipleQueries:c.multipleQueries,copyIndex:c.copyIndex,copySettings:c.copySettings,copyRules:c.copyRules,copySynonyms:c.copySynonyms,moveIndex:c.moveIndex,listIndices:c.listIndices,getLogs:c.getLogs,listClusters:c.listClusters,multipleSearchForFacetValues:c.multipleSearchForFacetValues,getApiKey:c.getApiKey,addApiKey:c.addApiKey,listApiKeys:c.listApiKeys,updateApiKey:c.updateApiKey,deleteApiKey:c.deleteApiKey,restoreApiKey:c.restoreApiKey,assignUserID:c.assignUserID,assignUserIDs:c.assignUserIDs,getUserID:c.getUserID,searchUserIDs:c.searchUserIDs,listUserIDs:c.listUserIDs,getTopUserIDs:c.getTopUserIDs,removeUserID:c.removeUserID,hasPendingMappings:c.hasPendingMappings,generateSecuredApiKey:c.generateSecuredApiKey,getSecuredApiKeyRemainingValidity:c.getSecuredApiKeyRemainingValidity,destroy:be.destroy,initIndex:n=>a=>c.initIndex(n)(a,{methods:{batch:c.batch,delete:c.deleteIndex,getObject:c.getObject,getObjects:c.getObjects,saveObject:c.saveObject,saveObjects:c.saveObjects,search:c.search,searchForFacetValues:c.searchForFacetValues,waitTask:c.waitTask,setSettings:c.setSettings,getSettings:c.getSettings,partialUpdateObject:c.partialUpdateObject,partialUpdateObjects:c.partialUpdateObjects,deleteObject:c.deleteObject,deleteObjects:c.deleteObjects,deleteBy:c.deleteBy,clearObjects:c.clearObjects,browseObjects:c.browseObjects,getObjectPosition:c.getObjectPosition,findObject:c.findObject,exists:c.exists,saveSynonym:c.saveSynonym,saveSynonyms:c.saveSynonyms,getSynonym:c.getSynonym,searchSynonyms:c.searchSynonyms,browseSynonyms:c.browseSynonyms,deleteSynonym:c.deleteSynonym,clearSynonyms:c.clearSynonyms,replaceAllObjects:c.replaceAllObjects,replaceAllSynonyms:c.replaceAllSynonyms,searchRules:c.searchRules,getRule:c.getRule,deleteRule:c.deleteRule,saveRule:c.saveRule,saveRules:c.saveRules,replaceAllRules:c.replaceAllRules,browseRules:c.browseRules,clearRules:c.clearRules}}),initAnalytics:()=>n=>W.createAnalyticsClient(g(u(u({},s),n),{methods:{addABTest:W.addABTest,getABTest:W.getABTest,getABTests:W.getABTests,stopABTest:W.stopABTest,deleteABTest:W.deleteABTest}})),initRecommendation:()=>n=>Pe.createRecommendationClient(g(u(u({},s),n),{methods:{getPersonalizationStrategy:Pe.getPersonalizationStrategy,setPersonalizationStrategy:Pe.setPersonalizationStrategy}}))}}))}wt.version=be.version;Tt.exports=wt});var Ut=I((mn,je)=>{var Ct=kt();je.exports=Ct;je.exports.default=Ct});var Ws={};Vt(Ws,{default:()=>Ks});var Oe=C(require("@yarnpkg/core")),E=C(require("@yarnpkg/core")),Ie=C(require("@yarnpkg/plugin-essentials")),Ht=C(require("semver"));var se=C(require("@yarnpkg/core")),Nt=C(Ut()),Cs="e8e1bd300d860104bb8c58453ffa1eb4",Us="OFCNCOG2CU",Wt=async(e,t)=>{var a;let r=se.structUtils.stringifyIdent(e),n=Ns(t).initIndex("npm-search");try{return((a=(await n.getObject(r,{attributesToRetrieve:["types"]})).types)==null?void 0:a.ts)==="definitely-typed"}catch(o){return!1}},Ns=e=>(0,Nt.default)(Us,Cs,{requester:{async send(r){try{let s=await se.httpUtils.request(r.url,r.data||null,{configuration:e,headers:r.headers});return{content:s.body,isTimedOut:!1,status:s.statusCode}}catch(s){return{content:s.response.body,isTimedOut:!1,status:s.response.statusCode}}}}});var _t=e=>e.scope?`${e.scope}__${e.name}`:`${e.name}`,Hs=async(e,t,r,s)=>{if(r.scope==="types")return;let{project:n}=e,{configuration:a}=n,o=a.makeResolver(),d={project:n,resolver:o,report:new E.ThrowReport};if(!await Wt(r,a))return;let b=_t(r),f=E.structUtils.parseRange(r.range).selector;if(!E.semverUtils.validRange(f)){let P=await o.getCandidates(r,new Map,d);f=E.structUtils.parseRange(P[0].reference).selector}let p=Ht.default.coerce(f);if(p===null)return;let h=`${Ie.suggestUtils.Modifier.CARET}${p.major}`,S=E.structUtils.makeDescriptor(E.structUtils.makeIdent("types",b),h),O=E.miscUtils.mapAndFind(n.workspaces,P=>{var T,V;let x=(T=P.manifest.dependencies.get(r.identHash))==null?void 0:T.descriptorHash,v=(V=P.manifest.devDependencies.get(r.identHash))==null?void 0:V.descriptorHash;if(x!==r.descriptorHash&&v!==r.descriptorHash)return E.miscUtils.mapAndFind.skip;let j=[];for(let Ae of Oe.Manifest.allDependencies){let Se=P.manifest[Ae].get(S.identHash);typeof Se!="undefined"&&j.push([Ae,Se])}return j.length===0?E.miscUtils.mapAndFind.skip:j});if(typeof O!="undefined")for(let[P,x]of O)e.manifest[P].set(x.identHash,x);else{try{if((await o.getCandidates(S,new Map,d)).length===0)return}catch{return}e.manifest[Ie.suggestUtils.Target.DEVELOPMENT].set(S.identHash,S)}},_s=async(e,t,r)=>{if(r.scope==="types")return;let s=_t(r),n=E.structUtils.makeIdent("types",s);for(let a of Oe.Manifest.allDependencies)typeof e.manifest[a].get(n.identHash)!="undefined"&&e.manifest[a].delete(n.identHash)},Fs=(e,t)=>{t.publishConfig&&t.publishConfig.typings&&(t.typings=t.publishConfig.typings),t.publishConfig&&t.publishConfig.types&&(t.types=t.publishConfig.types)},Bs={hooks:{afterWorkspaceDependencyAddition:Hs,afterWorkspaceDependencyRemoval:_s,beforeWorkspacePacking:Fs}},Ks=Bs;return Ws;})(); 7 | return plugin; 8 | } 9 | }; 10 | -------------------------------------------------------------------------------- /.yarn/sdks/eslint/bin/eslint.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire, createRequireFromPath} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require eslint/bin/eslint.js 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real eslint/bin/eslint.js your application uses 20 | module.exports = absRequire(`eslint/bin/eslint.js`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/eslint/lib/api.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire, createRequireFromPath} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require eslint 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real eslint your application uses 20 | module.exports = absRequire(`eslint`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/eslint/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "eslint", 3 | "version": "8.14.0-sdk", 4 | "main": "./lib/api.js", 5 | "type": "commonjs" 6 | } 7 | -------------------------------------------------------------------------------- /.yarn/sdks/integrations.yml: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by @yarnpkg/sdks. 2 | # Manual changes might be lost! 3 | 4 | integrations: 5 | - vscode 6 | -------------------------------------------------------------------------------- /.yarn/sdks/prettier/index.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire, createRequireFromPath} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require prettier/index.js 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real prettier/index.js your application uses 20 | module.exports = absRequire(`prettier/index.js`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/prettier/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "prettier", 3 | "version": "2.6.2-sdk", 4 | "main": "./index.js", 5 | "type": "commonjs" 6 | } 7 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/bin/tsc: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire, createRequireFromPath} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require typescript/bin/tsc 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real typescript/bin/tsc your application uses 20 | module.exports = absRequire(`typescript/bin/tsc`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/bin/tsserver: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire, createRequireFromPath} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require typescript/bin/tsserver 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real typescript/bin/tsserver your application uses 20 | module.exports = absRequire(`typescript/bin/tsserver`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/lib/tsc.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire, createRequireFromPath} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require typescript/lib/tsc.js 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real typescript/lib/tsc.js your application uses 20 | module.exports = absRequire(`typescript/lib/tsc.js`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/lib/tsserver.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire, createRequireFromPath} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); 11 | 12 | const moduleWrapper = tsserver => { 13 | if (!process.versions.pnp) { 14 | return tsserver; 15 | } 16 | 17 | const {isAbsolute} = require(`path`); 18 | const pnpApi = require(`pnpapi`); 19 | 20 | const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//); 21 | const isPortal = str => str.startsWith("portal:/"); 22 | const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`); 23 | 24 | const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => { 25 | return `${locator.name}@${locator.reference}`; 26 | })); 27 | 28 | // VSCode sends the zip paths to TS using the "zip://" prefix, that TS 29 | // doesn't understand. This layer makes sure to remove the protocol 30 | // before forwarding it to TS, and to add it back on all returned paths. 31 | 32 | function toEditorPath(str) { 33 | // We add the `zip:` prefix to both `.zip/` paths and virtual paths 34 | if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) { 35 | // We also take the opportunity to turn virtual paths into physical ones; 36 | // this makes it much easier to work with workspaces that list peer 37 | // dependencies, since otherwise Ctrl+Click would bring us to the virtual 38 | // file instances instead of the real ones. 39 | // 40 | // We only do this to modules owned by the the dependency tree roots. 41 | // This avoids breaking the resolution when jumping inside a vendor 42 | // with peer dep (otherwise jumping into react-dom would show resolution 43 | // errors on react). 44 | // 45 | const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str; 46 | if (resolved) { 47 | const locator = pnpApi.findPackageLocator(resolved); 48 | if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) { 49 | str = resolved; 50 | } 51 | } 52 | 53 | str = normalize(str); 54 | 55 | if (str.match(/\.zip\//)) { 56 | switch (hostInfo) { 57 | // Absolute VSCode `Uri.fsPath`s need to start with a slash. 58 | // VSCode only adds it automatically for supported schemes, 59 | // so we have to do it manually for the `zip` scheme. 60 | // The path needs to start with a caret otherwise VSCode doesn't handle the protocol 61 | // 62 | // Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910 63 | // 64 | // Update 2021-10-08: VSCode changed their format in 1.61. 65 | // Before | ^zip:/c:/foo/bar.zip/package.json 66 | // After | ^/zip//c:/foo/bar.zip/package.json 67 | // 68 | // Update 2022-04-06: VSCode changed the format in 1.66. 69 | // Before | ^/zip//c:/foo/bar.zip/package.json 70 | // After | ^/zip/c:/foo/bar.zip/package.json 71 | // 72 | case `vscode <1.61`: { 73 | str = `^zip:${str}`; 74 | } break; 75 | 76 | case `vscode <1.66`: { 77 | str = `^/zip/${str}`; 78 | } break; 79 | 80 | case `vscode`: { 81 | str = `^/zip${str}`; 82 | } break; 83 | 84 | // To make "go to definition" work, 85 | // We have to resolve the actual file system path from virtual path 86 | // and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip) 87 | case `coc-nvim`: { 88 | str = normalize(resolved).replace(/\.zip\//, `.zip::`); 89 | str = resolve(`zipfile:${str}`); 90 | } break; 91 | 92 | // Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server) 93 | // We have to resolve the actual file system path from virtual path, 94 | // everything else is up to neovim 95 | case `neovim`: { 96 | str = normalize(resolved).replace(/\.zip\//, `.zip::`); 97 | str = `zipfile://${str}`; 98 | } break; 99 | 100 | default: { 101 | str = `zip:${str}`; 102 | } break; 103 | } 104 | } 105 | } 106 | 107 | return str; 108 | } 109 | 110 | function fromEditorPath(str) { 111 | switch (hostInfo) { 112 | case `coc-nvim`: { 113 | str = str.replace(/\.zip::/, `.zip/`); 114 | // The path for coc-nvim is in format of //zipfile://.yarn/... 115 | // So in order to convert it back, we use .* to match all the thing 116 | // before `zipfile:` 117 | return process.platform === `win32` 118 | ? str.replace(/^.*zipfile:\//, ``) 119 | : str.replace(/^.*zipfile:/, ``); 120 | } break; 121 | 122 | case `neovim`: { 123 | str = str.replace(/\.zip::/, `.zip/`); 124 | // The path for neovim is in format of zipfile:////.yarn/... 125 | return str.replace(/^zipfile:\/\//, ``); 126 | } break; 127 | 128 | case `vscode`: 129 | default: { 130 | return process.platform === `win32` 131 | ? str.replace(/^\^?(zip:|\/zip)\/+/, ``) 132 | : str.replace(/^\^?(zip:|\/zip)\/+/, `/`); 133 | } break; 134 | } 135 | } 136 | 137 | // Force enable 'allowLocalPluginLoads' 138 | // TypeScript tries to resolve plugins using a path relative to itself 139 | // which doesn't work when using the global cache 140 | // https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238 141 | // VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but 142 | // TypeScript already does local loads and if this code is running the user trusts the workspace 143 | // https://github.com/microsoft/vscode/issues/45856 144 | const ConfiguredProject = tsserver.server.ConfiguredProject; 145 | const {enablePluginsWithOptions: originalEnablePluginsWithOptions} = ConfiguredProject.prototype; 146 | ConfiguredProject.prototype.enablePluginsWithOptions = function() { 147 | this.projectService.allowLocalPluginLoads = true; 148 | return originalEnablePluginsWithOptions.apply(this, arguments); 149 | }; 150 | 151 | // And here is the point where we hijack the VSCode <-> TS communications 152 | // by adding ourselves in the middle. We locate everything that looks 153 | // like an absolute path of ours and normalize it. 154 | 155 | const Session = tsserver.server.Session; 156 | const {onMessage: originalOnMessage, send: originalSend} = Session.prototype; 157 | let hostInfo = `unknown`; 158 | 159 | Object.assign(Session.prototype, { 160 | onMessage(/** @type {string | object} */ message) { 161 | const isStringMessage = typeof message === 'string'; 162 | const parsedMessage = isStringMessage ? JSON.parse(message) : message; 163 | 164 | if ( 165 | parsedMessage != null && 166 | typeof parsedMessage === `object` && 167 | parsedMessage.arguments && 168 | typeof parsedMessage.arguments.hostInfo === `string` 169 | ) { 170 | hostInfo = parsedMessage.arguments.hostInfo; 171 | if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) { 172 | if (/(\/|-)1\.([1-5][0-9]|60)\./.test(process.env.VSCODE_IPC_HOOK)) { 173 | hostInfo += ` <1.61`; 174 | } else if (/(\/|-)1\.(6[1-5])\./.test(process.env.VSCODE_IPC_HOOK)) { 175 | hostInfo += ` <1.66`; 176 | } 177 | } 178 | } 179 | 180 | const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => { 181 | return typeof value === 'string' ? fromEditorPath(value) : value; 182 | }); 183 | 184 | return originalOnMessage.call( 185 | this, 186 | isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON) 187 | ); 188 | }, 189 | 190 | send(/** @type {any} */ msg) { 191 | return originalSend.call(this, JSON.parse(JSON.stringify(msg, (key, value) => { 192 | return typeof value === `string` ? toEditorPath(value) : value; 193 | }))); 194 | } 195 | }); 196 | 197 | return tsserver; 198 | }; 199 | 200 | if (existsSync(absPnpApiPath)) { 201 | if (!process.versions.pnp) { 202 | // Setup the environment to be able to require typescript/lib/tsserver.js 203 | require(absPnpApiPath).setup(); 204 | } 205 | } 206 | 207 | // Defer to the real typescript/lib/tsserver.js your application uses 208 | module.exports = moduleWrapper(absRequire(`typescript/lib/tsserver.js`)); 209 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/lib/tsserverlibrary.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire, createRequireFromPath} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); 11 | 12 | const moduleWrapper = tsserver => { 13 | if (!process.versions.pnp) { 14 | return tsserver; 15 | } 16 | 17 | const {isAbsolute} = require(`path`); 18 | const pnpApi = require(`pnpapi`); 19 | 20 | const isVirtual = str => str.match(/\/(\$\$virtual|__virtual__)\//); 21 | const isPortal = str => str.startsWith("portal:/"); 22 | const normalize = str => str.replace(/\\/g, `/`).replace(/^\/?/, `/`); 23 | 24 | const dependencyTreeRoots = new Set(pnpApi.getDependencyTreeRoots().map(locator => { 25 | return `${locator.name}@${locator.reference}`; 26 | })); 27 | 28 | // VSCode sends the zip paths to TS using the "zip://" prefix, that TS 29 | // doesn't understand. This layer makes sure to remove the protocol 30 | // before forwarding it to TS, and to add it back on all returned paths. 31 | 32 | function toEditorPath(str) { 33 | // We add the `zip:` prefix to both `.zip/` paths and virtual paths 34 | if (isAbsolute(str) && !str.match(/^\^?(zip:|\/zip\/)/) && (str.match(/\.zip\//) || isVirtual(str))) { 35 | // We also take the opportunity to turn virtual paths into physical ones; 36 | // this makes it much easier to work with workspaces that list peer 37 | // dependencies, since otherwise Ctrl+Click would bring us to the virtual 38 | // file instances instead of the real ones. 39 | // 40 | // We only do this to modules owned by the the dependency tree roots. 41 | // This avoids breaking the resolution when jumping inside a vendor 42 | // with peer dep (otherwise jumping into react-dom would show resolution 43 | // errors on react). 44 | // 45 | const resolved = isVirtual(str) ? pnpApi.resolveVirtual(str) : str; 46 | if (resolved) { 47 | const locator = pnpApi.findPackageLocator(resolved); 48 | if (locator && (dependencyTreeRoots.has(`${locator.name}@${locator.reference}`) || isPortal(locator.reference))) { 49 | str = resolved; 50 | } 51 | } 52 | 53 | str = normalize(str); 54 | 55 | if (str.match(/\.zip\//)) { 56 | switch (hostInfo) { 57 | // Absolute VSCode `Uri.fsPath`s need to start with a slash. 58 | // VSCode only adds it automatically for supported schemes, 59 | // so we have to do it manually for the `zip` scheme. 60 | // The path needs to start with a caret otherwise VSCode doesn't handle the protocol 61 | // 62 | // Ref: https://github.com/microsoft/vscode/issues/105014#issuecomment-686760910 63 | // 64 | // Update 2021-10-08: VSCode changed their format in 1.61. 65 | // Before | ^zip:/c:/foo/bar.zip/package.json 66 | // After | ^/zip//c:/foo/bar.zip/package.json 67 | // 68 | // Update 2022-04-06: VSCode changed the format in 1.66. 69 | // Before | ^/zip//c:/foo/bar.zip/package.json 70 | // After | ^/zip/c:/foo/bar.zip/package.json 71 | // 72 | case `vscode <1.61`: { 73 | str = `^zip:${str}`; 74 | } break; 75 | 76 | case `vscode <1.66`: { 77 | str = `^/zip/${str}`; 78 | } break; 79 | 80 | case `vscode`: { 81 | str = `^/zip${str}`; 82 | } break; 83 | 84 | // To make "go to definition" work, 85 | // We have to resolve the actual file system path from virtual path 86 | // and convert scheme to supported by [vim-rzip](https://github.com/lbrayner/vim-rzip) 87 | case `coc-nvim`: { 88 | str = normalize(resolved).replace(/\.zip\//, `.zip::`); 89 | str = resolve(`zipfile:${str}`); 90 | } break; 91 | 92 | // Support neovim native LSP and [typescript-language-server](https://github.com/theia-ide/typescript-language-server) 93 | // We have to resolve the actual file system path from virtual path, 94 | // everything else is up to neovim 95 | case `neovim`: { 96 | str = normalize(resolved).replace(/\.zip\//, `.zip::`); 97 | str = `zipfile://${str}`; 98 | } break; 99 | 100 | default: { 101 | str = `zip:${str}`; 102 | } break; 103 | } 104 | } 105 | } 106 | 107 | return str; 108 | } 109 | 110 | function fromEditorPath(str) { 111 | switch (hostInfo) { 112 | case `coc-nvim`: { 113 | str = str.replace(/\.zip::/, `.zip/`); 114 | // The path for coc-nvim is in format of //zipfile://.yarn/... 115 | // So in order to convert it back, we use .* to match all the thing 116 | // before `zipfile:` 117 | return process.platform === `win32` 118 | ? str.replace(/^.*zipfile:\//, ``) 119 | : str.replace(/^.*zipfile:/, ``); 120 | } break; 121 | 122 | case `neovim`: { 123 | str = str.replace(/\.zip::/, `.zip/`); 124 | // The path for neovim is in format of zipfile:////.yarn/... 125 | return str.replace(/^zipfile:\/\//, ``); 126 | } break; 127 | 128 | case `vscode`: 129 | default: { 130 | return process.platform === `win32` 131 | ? str.replace(/^\^?(zip:|\/zip)\/+/, ``) 132 | : str.replace(/^\^?(zip:|\/zip)\/+/, `/`); 133 | } break; 134 | } 135 | } 136 | 137 | // Force enable 'allowLocalPluginLoads' 138 | // TypeScript tries to resolve plugins using a path relative to itself 139 | // which doesn't work when using the global cache 140 | // https://github.com/microsoft/TypeScript/blob/1b57a0395e0bff191581c9606aab92832001de62/src/server/project.ts#L2238 141 | // VSCode doesn't want to enable 'allowLocalPluginLoads' due to security concerns but 142 | // TypeScript already does local loads and if this code is running the user trusts the workspace 143 | // https://github.com/microsoft/vscode/issues/45856 144 | const ConfiguredProject = tsserver.server.ConfiguredProject; 145 | const {enablePluginsWithOptions: originalEnablePluginsWithOptions} = ConfiguredProject.prototype; 146 | ConfiguredProject.prototype.enablePluginsWithOptions = function() { 147 | this.projectService.allowLocalPluginLoads = true; 148 | return originalEnablePluginsWithOptions.apply(this, arguments); 149 | }; 150 | 151 | // And here is the point where we hijack the VSCode <-> TS communications 152 | // by adding ourselves in the middle. We locate everything that looks 153 | // like an absolute path of ours and normalize it. 154 | 155 | const Session = tsserver.server.Session; 156 | const {onMessage: originalOnMessage, send: originalSend} = Session.prototype; 157 | let hostInfo = `unknown`; 158 | 159 | Object.assign(Session.prototype, { 160 | onMessage(/** @type {string | object} */ message) { 161 | const isStringMessage = typeof message === 'string'; 162 | const parsedMessage = isStringMessage ? JSON.parse(message) : message; 163 | 164 | if ( 165 | parsedMessage != null && 166 | typeof parsedMessage === `object` && 167 | parsedMessage.arguments && 168 | typeof parsedMessage.arguments.hostInfo === `string` 169 | ) { 170 | hostInfo = parsedMessage.arguments.hostInfo; 171 | if (hostInfo === `vscode` && process.env.VSCODE_IPC_HOOK) { 172 | if (/(\/|-)1\.([1-5][0-9]|60)\./.test(process.env.VSCODE_IPC_HOOK)) { 173 | hostInfo += ` <1.61`; 174 | } else if (/(\/|-)1\.(6[1-5])\./.test(process.env.VSCODE_IPC_HOOK)) { 175 | hostInfo += ` <1.66`; 176 | } 177 | } 178 | } 179 | 180 | const processedMessageJSON = JSON.stringify(parsedMessage, (key, value) => { 181 | return typeof value === 'string' ? fromEditorPath(value) : value; 182 | }); 183 | 184 | return originalOnMessage.call( 185 | this, 186 | isStringMessage ? processedMessageJSON : JSON.parse(processedMessageJSON) 187 | ); 188 | }, 189 | 190 | send(/** @type {any} */ msg) { 191 | return originalSend.call(this, JSON.parse(JSON.stringify(msg, (key, value) => { 192 | return typeof value === `string` ? toEditorPath(value) : value; 193 | }))); 194 | } 195 | }); 196 | 197 | return tsserver; 198 | }; 199 | 200 | if (existsSync(absPnpApiPath)) { 201 | if (!process.versions.pnp) { 202 | // Setup the environment to be able to require typescript/lib/tsserverlibrary.js 203 | require(absPnpApiPath).setup(); 204 | } 205 | } 206 | 207 | // Defer to the real typescript/lib/tsserverlibrary.js your application uses 208 | module.exports = moduleWrapper(absRequire(`typescript/lib/tsserverlibrary.js`)); 209 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/lib/typescript.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const {existsSync} = require(`fs`); 4 | const {createRequire, createRequireFromPath} = require(`module`); 5 | const {resolve} = require(`path`); 6 | 7 | const relPnpApiPath = "../../../../.pnp.cjs"; 8 | 9 | const absPnpApiPath = resolve(__dirname, relPnpApiPath); 10 | const absRequire = (createRequire || createRequireFromPath)(absPnpApiPath); 11 | 12 | if (existsSync(absPnpApiPath)) { 13 | if (!process.versions.pnp) { 14 | // Setup the environment to be able to require typescript/lib/typescript.js 15 | require(absPnpApiPath).setup(); 16 | } 17 | } 18 | 19 | // Defer to the real typescript/lib/typescript.js your application uses 20 | module.exports = absRequire(`typescript/lib/typescript.js`); 21 | -------------------------------------------------------------------------------- /.yarn/sdks/typescript/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "typescript", 3 | "version": "4.6.3-sdk", 4 | "main": "./lib/typescript.js", 5 | "type": "commonjs" 6 | } 7 | -------------------------------------------------------------------------------- /.yarnrc.yml: -------------------------------------------------------------------------------- 1 | enableGlobalCache: true 2 | 3 | nodeLinker: pnp 4 | 5 | plugins: 6 | - path: .yarn/plugins/@yarnpkg/plugin-interactive-tools.cjs 7 | spec: "@yarnpkg/plugin-interactive-tools" 8 | - path: .yarn/plugins/@yarnpkg/plugin-typescript.cjs 9 | spec: "@yarnpkg/plugin-typescript" 10 | 11 | yarnPath: .yarn/releases/yarn-3.2.0.cjs 12 | -------------------------------------------------------------------------------- /Anchor.toml: -------------------------------------------------------------------------------- 1 | anchor_version = "0.24.2" 2 | solana_version = "1.9.16" 3 | 4 | [features] 5 | seeds = true 6 | 7 | [registry] 8 | url = "https://anchor.projectserum.com" 9 | 10 | [provider] 11 | cluster = "localnet" 12 | wallet = "tests/fixture-key.json" 13 | 14 | [scripts] 15 | test = "yarn mocha" 16 | 17 | [programs.mainnet] 18 | crate_token = "CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs" 19 | crate_redeem_in_kind = "1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE" 20 | 21 | [programs.devnet] 22 | crate_token = "CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs" 23 | crate_redeem_in_kind = "1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE" 24 | 25 | [programs.testnet] 26 | crate_token = "CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs" 27 | crate_redeem_in_kind = "1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE" 28 | 29 | [programs.localnet] 30 | crate_token = "CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs" 31 | crate_redeem_in_kind = "1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE" 32 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = ["programs/*"] 3 | 4 | [profile.release] 5 | lto = "fat" 6 | codegen-units = 1 7 | 8 | [profile.release.build-override] 9 | opt-level = 3 10 | incremental = false 11 | codegen-units = 1 12 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 📦 Crate Protocol 2 | 3 | [![License](https://img.shields.io/badge/license-AGPL%203.0-blue)](https://github.com/CrateProtocol/crate/blob/master/LICENSE) 4 | [![Build Status](https://img.shields.io/github/workflow/status/CrateProtocol/crate/E2E/master)](https://github.com/CrateProtocol/crate/actions/workflows/programs-e2e.yml?query=branch%3Amaster) 5 | [![Contributors](https://img.shields.io/github/contributors/CrateProtocol/crate)](https://github.com/CrateProtocol/crate/graphs/contributors) 6 | 7 | ![Crate Protocol](/images/banner.png) 8 | 9 | Crate Protocol allows anyone to create, manage, and trade a tokenized basket of assets, which we refer to as a **Crate**. A Crate is always fully collateralized by its underlying assets. The protocol will evolve to support advanced features, including automatic rebalancing based on set parameters. 10 | 11 | We're in active development. For the latest updates, please join our community: 12 | 13 | - Twitter: https://twitter.com/CrateProtocol 14 | - Discord: https://chat.crate.so 15 | 16 | ## Note 17 | 18 | - **Crate is in active development, so all APIs are subject to change.** 19 | - **This code is unaudited. Use at your own risk.** 20 | 21 | ## Packages 22 | 23 | | Package | Description | Version | Docs | 24 | | :------------------------- | :------------------------------------------------ | :-------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------- | 25 | | `crate-redeem-in-kind` | In-kind distributions for redeeming Crate assets. | [![Crates.io](https://img.shields.io/crates/v/crate-redeem-in-kind)](https://crates.io/crates/crate-redeem-in-kind) | [![Docs.rs](https://docs.rs/crate-redeem-in-kind/badge.svg)](https://docs.rs/crate-redeem-in-kind) | 26 | | `crate-token` | Fractional ownership of a basket of assets. | [![Crates.io](https://img.shields.io/crates/v/crate-token)](https://crates.io/crates/crate-token) | [![Docs.rs](https://docs.rs/crate-token/badge.svg)](https://docs.rs/crate-token) | 27 | | `@crateprotocol/crate-sdk` | TypeScript SDK for Crate | [![npm](https://img.shields.io/npm/v/@crateprotocol/crate-sdk.svg)](https://www.npmjs.com/package/@crateprotocol/crate-sdk) | [![Docs](https://img.shields.io/badge/docs-typedoc-blue)](https://docs.crate.so/ts/) | 28 | 29 | ## Addresses 30 | 31 | Program addresses are the same on devnet, testnet, and mainnet-beta. 32 | 33 | - CrateRedeemInKind: [`1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE`](https://explorer.solana.com/address/1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE) 34 | - CrateToken: [`CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs`](https://explorer.solana.com/address/CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs) 35 | 36 | ## Contribution 37 | 38 | Thank you for your interest in contributing to Crate Protocol! All contributions are welcome no matter how big or small. This includes (but is not limited to) filing issues, adding documentation, fixing bugs, creating examples, and implementing features. 39 | 40 | When contributing, please make sure your code adheres to some basic coding guidlines: 41 | 42 | - Code must be formatted with the configured formatters (e.g. rustfmt and prettier). 43 | - Comment lines should be no longer than 80 characters and written with proper grammar and punctuation. 44 | - Commit messages should be prefixed with the package(s) they modify. Changes affecting multiple packages should list all packages. In rare cases, changes may omit the package name prefix. 45 | 46 | ## License 47 | 48 | Crate Protocol is licensed under the AGPL-3.0 license. 49 | 50 | Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Crate Protocol by you, as defined in the AGPL-3.0 license, shall be licensed as above, without any additional terms or conditions. 51 | -------------------------------------------------------------------------------- /ci.nix: -------------------------------------------------------------------------------- 1 | { pkgs }: 2 | pkgs.buildEnv { 3 | name = "ci"; 4 | paths = with pkgs; 5 | (pkgs.lib.optionals pkgs.stdenv.isLinux [ udev ]) ++ [ 6 | anchor-0_24_2 7 | cargo-workspaces 8 | 9 | nodejs 10 | yarn 11 | python3 12 | 13 | pkgconfig 14 | openssl 15 | jq 16 | gnused 17 | 18 | libiconv 19 | ] ++ (pkgs.lib.optionals pkgs.stdenv.isDarwin [ 20 | pkgs.darwin.apple_sdk.frameworks.AppKit 21 | pkgs.darwin.apple_sdk.frameworks.IOKit 22 | pkgs.darwin.apple_sdk.frameworks.Foundation 23 | ]); 24 | } 25 | -------------------------------------------------------------------------------- /flake.lock: -------------------------------------------------------------------------------- 1 | { 2 | "nodes": { 3 | "flake-utils": { 4 | "locked": { 5 | "lastModified": 1649676176, 6 | "narHash": "sha256-OWKJratjt2RW151VUlJPRALb7OU2S5s+f0vLj4o1bHM=", 7 | "owner": "numtide", 8 | "repo": "flake-utils", 9 | "rev": "a4b154ebbdc88c8498a5c7b01589addc9e9cb678", 10 | "type": "github" 11 | }, 12 | "original": { 13 | "owner": "numtide", 14 | "repo": "flake-utils", 15 | "type": "github" 16 | } 17 | }, 18 | "flake-utils_2": { 19 | "locked": { 20 | "lastModified": 1649676176, 21 | "narHash": "sha256-OWKJratjt2RW151VUlJPRALb7OU2S5s+f0vLj4o1bHM=", 22 | "owner": "numtide", 23 | "repo": "flake-utils", 24 | "rev": "a4b154ebbdc88c8498a5c7b01589addc9e9cb678", 25 | "type": "github" 26 | }, 27 | "original": { 28 | "owner": "numtide", 29 | "repo": "flake-utils", 30 | "type": "github" 31 | } 32 | }, 33 | "flake-utils_3": { 34 | "locked": { 35 | "lastModified": 1637014545, 36 | "narHash": "sha256-26IZAc5yzlD9FlDT54io1oqG/bBoyka+FJk5guaX4x4=", 37 | "owner": "numtide", 38 | "repo": "flake-utils", 39 | "rev": "bba5dcc8e0b20ab664967ad83d24d64cb64ec4f4", 40 | "type": "github" 41 | }, 42 | "original": { 43 | "owner": "numtide", 44 | "repo": "flake-utils", 45 | "type": "github" 46 | } 47 | }, 48 | "nixpkgs": { 49 | "locked": { 50 | "lastModified": 1650676489, 51 | "narHash": "sha256-8v0qMwq36v/mUGywsJTcfpm9HHMr4v2urYHns1LwPkg=", 52 | "owner": "NixOS", 53 | "repo": "nixpkgs", 54 | "rev": "875b41570c41386017d787caefedc008ddb6e31b", 55 | "type": "github" 56 | }, 57 | "original": { 58 | "owner": "NixOS", 59 | "ref": "nixpkgs-unstable", 60 | "repo": "nixpkgs", 61 | "type": "github" 62 | } 63 | }, 64 | "nixpkgs_2": { 65 | "locked": { 66 | "lastModified": 1649961138, 67 | "narHash": "sha256-8ZCPrazs+qd2V8Elw84lIWuk0kKfVQ8Ei/19gahURhM=", 68 | "owner": "NixOS", 69 | "repo": "nixpkgs", 70 | "rev": "d08394e7cd5c7431a1e8f53b7f581e74ee909548", 71 | "type": "github" 72 | }, 73 | "original": { 74 | "owner": "NixOS", 75 | "ref": "nixpkgs-unstable", 76 | "repo": "nixpkgs", 77 | "type": "github" 78 | } 79 | }, 80 | "root": { 81 | "inputs": { 82 | "flake-utils": "flake-utils", 83 | "nixpkgs": "nixpkgs", 84 | "saber-overlay": "saber-overlay" 85 | } 86 | }, 87 | "rust-overlay": { 88 | "inputs": { 89 | "flake-utils": "flake-utils_3", 90 | "nixpkgs": [ 91 | "saber-overlay", 92 | "nixpkgs" 93 | ] 94 | }, 95 | "locked": { 96 | "lastModified": 1649903781, 97 | "narHash": "sha256-m+3EZo0a4iS8IwHQhkM/riPuFpu76505xKqmN9j5O+E=", 98 | "owner": "oxalica", 99 | "repo": "rust-overlay", 100 | "rev": "e45696bedc4a13a5970376b8fc09660fdd0e6f6c", 101 | "type": "github" 102 | }, 103 | "original": { 104 | "owner": "oxalica", 105 | "repo": "rust-overlay", 106 | "type": "github" 107 | } 108 | }, 109 | "saber-overlay": { 110 | "inputs": { 111 | "flake-utils": "flake-utils_2", 112 | "nixpkgs": "nixpkgs_2", 113 | "rust-overlay": "rust-overlay" 114 | }, 115 | "locked": { 116 | "lastModified": 1649978970, 117 | "narHash": "sha256-hj+Yp3iacTNU/5+EhzcQ3xASiaifHP5AW3752vLMAn0=", 118 | "owner": "saber-hq", 119 | "repo": "saber-overlay", 120 | "rev": "5ec6426c8cc205d0577660fac5469f47f2dccabf", 121 | "type": "github" 122 | }, 123 | "original": { 124 | "owner": "saber-hq", 125 | "repo": "saber-overlay", 126 | "type": "github" 127 | } 128 | } 129 | }, 130 | "root": "root", 131 | "version": 7 132 | } 133 | -------------------------------------------------------------------------------- /flake.nix: -------------------------------------------------------------------------------- 1 | { 2 | description = "Crate Protocol development environment."; 3 | 4 | inputs = { 5 | nixpkgs.url = "github:NixOS/nixpkgs/nixpkgs-unstable"; 6 | saber-overlay.url = "github:saber-hq/saber-overlay"; 7 | flake-utils.url = "github:numtide/flake-utils"; 8 | }; 9 | 10 | outputs = { self, nixpkgs, saber-overlay, flake-utils }: 11 | flake-utils.lib.eachSystem [ 12 | "aarch64-darwin" 13 | "x86_64-linux" 14 | "x86_64-darwin" 15 | ] 16 | (system: 17 | let 18 | pkgs = import nixpkgs { inherit system; } 19 | // saber-overlay.packages.${system}; 20 | in 21 | { 22 | devShell = import ./shell.nix { inherit pkgs; }; 23 | packages.ci = import ./ci.nix { inherit pkgs; }; 24 | }); 25 | } 26 | -------------------------------------------------------------------------------- /images/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CrateProtocol/crate/9ec178c0e15ce0275bd8e2cae2b65c6ff03fd1f8/images/banner.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@crateprotocol/crate-sdk", 3 | "version": "0.6.0", 4 | "description": "Fractional ownership of shared assets", 5 | "main": "dist/cjs/index.js", 6 | "module": "dist/esm/index.js", 7 | "repository": "https://github.com/CrateProtocol/crate.git", 8 | "author": "Jen Zhang ", 9 | "bugs": { 10 | "url": "https://github.com/CrateProtocol/crate/issues", 11 | "email": "team@crate.so" 12 | }, 13 | "publishConfig": { 14 | "access": "public" 15 | }, 16 | "homepage": "https://crate.so", 17 | "license": "AGPL-3.0", 18 | "devDependencies": { 19 | "@project-serum/anchor": "^0.24.2", 20 | "@rushstack/eslint-patch": "^1.1.3", 21 | "@saberhq/anchor-contrib": "^1.12.65", 22 | "@saberhq/chai-solana": "^1.12.65", 23 | "@saberhq/eslint-config": "^1.12.65", 24 | "@saberhq/solana-contrib": "^1.12.65", 25 | "@saberhq/token-utils": "^1.12.65", 26 | "@saberhq/tsconfig": "^1.12.65", 27 | "@solana/web3.js": "^1.39.1", 28 | "@types/bn.js": "^5.1.0", 29 | "@types/mocha": "^9.1.1", 30 | "@types/node": "^16.11.27", 31 | "@types/prettier": "^2.6.0", 32 | "@yarnpkg/doctor": "^4.0.0-rc.2", 33 | "bn.js": "^5.2.0", 34 | "chai": "^4.3.4", 35 | "eslint": "^8.14.0", 36 | "eslint-import-resolver-node": "^0.3.6", 37 | "eslint-plugin-import": "^2.26.0", 38 | "husky": "^7.0.4", 39 | "jsbi": "^4.3.0", 40 | "lerna": "^4.0.0", 41 | "lint-staged": "^12.4.0", 42 | "mocha": "^9.2.2", 43 | "prettier": "^2.6.2", 44 | "ts-node": "^10.7.0", 45 | "typedoc": "^0.22.15", 46 | "typescript": "^4.6.3" 47 | }, 48 | "scripts": { 49 | "build": "rm -fr dist/ && tsc -P tsconfig.build.json && tsc -P tsconfig.esm.json", 50 | "docs:generate": "typedoc --excludePrivate --includeVersion --out site/ts/ src/index.ts", 51 | "typecheck": "tsc", 52 | "idl:generate": "./scripts/parse-idls.sh && ./scripts/generate-idl-types.sh", 53 | "idl:generate:nolint": "./scripts/parse-idls.sh && RUN_ESLINT=none ./scripts/generate-idl-types.sh", 54 | "lint": "eslint . --cache", 55 | "test:e2e": "anchor test --skip-build tests/*.ts", 56 | "prepare": "husky install" 57 | }, 58 | "peerDependencies": { 59 | "@project-serum/anchor": ">=0.24.2", 60 | "@saberhq/anchor-contrib": "^1.12", 61 | "@saberhq/solana-contrib": "^1.12", 62 | "@saberhq/token-utils": "^1.12", 63 | "@solana/web3.js": "^1.37" 64 | }, 65 | "packageManager": "yarn@3.2.0", 66 | "dependencies": { 67 | "superstruct": "^0.15.4", 68 | "tiny-invariant": "^1.2.0", 69 | "tslib": "^2.4.0" 70 | }, 71 | "resolutions": { 72 | "chai": "=4.3.4" 73 | }, 74 | "lint-staged": { 75 | "*.ts": "eslint --cache --fix", 76 | "*.{md,json,js,yml,yaml}": "prettier --write" 77 | }, 78 | "files": [ 79 | "dist/", 80 | "src/" 81 | ] 82 | } 83 | -------------------------------------------------------------------------------- /programs/crate-redeem-in-kind/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crate-redeem-in-kind" 3 | version = "0.6.0" 4 | description = "In-kind distributions for redeeming Crate assets." 5 | edition = "2021" 6 | homepage = "https://crate.so" 7 | repository = "https://github.com/CrateProtocol/crate" 8 | authors = ["Jen Zhang "] 9 | license = "AGPL-3.0" 10 | keywords = ["solana", "crate"] 11 | 12 | [lib] 13 | crate-type = ["cdylib", "lib"] 14 | name = "crate_redeem_in_kind" 15 | 16 | [features] 17 | no-entrypoint = [] 18 | no-idl = [] 19 | cpi = ["no-entrypoint"] 20 | default = [] 21 | 22 | [dependencies] 23 | anchor-lang = "^0.24" 24 | anchor-spl = "^0.24" 25 | crate-token = { path = "../crate-token", version = "0.6.0", features = ["cpi"] } 26 | static-pubkey = "^1.0.2" 27 | vipers = "^2" 28 | num-traits = "0.2" 29 | -------------------------------------------------------------------------------- /programs/crate-redeem-in-kind/README.md: -------------------------------------------------------------------------------- 1 | # `crate-redeem-in-kind` 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/crate-redeem-in-kind)](https://crates.io/crates/crate-redeem-in-kind) 4 | 5 | Program which performs in-kind distributions when redeeming Crate assets. 6 | 7 | To use this, set your `withdraw_authority` to `2amCDqmgpQ2qkryLArCcYeX8DzyNqvjuy7yKq6hsonqF`, which is a singleton PDA that allows this program to perform withdrawals on behalf of your Crate. 8 | 9 | Program Address: [`1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE`](https://explorer.solana.com/address/1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE) 10 | -------------------------------------------------------------------------------- /programs/crate-redeem-in-kind/Xargo.toml: -------------------------------------------------------------------------------- 1 | [target.bpfel-unknown-unknown.dependencies.std] 2 | features = [] 3 | -------------------------------------------------------------------------------- /programs/crate-redeem-in-kind/src/account_validators.rs: -------------------------------------------------------------------------------- 1 | //! Validate accounts 2 | 3 | use anchor_lang::prelude::*; 4 | use vipers::assert_keys_eq; 5 | 6 | use crate::Redeem; 7 | use vipers::validate::Validate; 8 | 9 | impl<'info> Validate<'info> for Redeem<'info> { 10 | fn validate(&self) -> Result<()> { 11 | assert_keys_eq!( 12 | self.withdraw_authority, 13 | crate::WITHDRAW_AUTHORITY_ADDRESS, 14 | "withdraw_authority" 15 | ); 16 | 17 | assert_keys_eq!(self.crate_token.mint, self.crate_mint, "crate_token.mint"); 18 | assert_keys_eq!(self.crate_source.mint, self.crate_mint, "crate_source.mint"); 19 | assert_keys_eq!(self.crate_source.owner, self.owner, "crate_source.owner"); 20 | Ok(()) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /programs/crate-redeem-in-kind/src/events.rs: -------------------------------------------------------------------------------- 1 | //! Crate events 2 | 3 | use anchor_lang::prelude::*; 4 | 5 | /// Emitted when crate tokens are redeemed. 6 | #[event] 7 | pub struct RedeemEvent { 8 | #[index] 9 | pub crate_key: Pubkey, 10 | pub source: Pubkey, 11 | pub amount: u64, 12 | } 13 | -------------------------------------------------------------------------------- /programs/crate-redeem-in-kind/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! In-kind distributions for redeeming Crate assets. 2 | #![deny(rustdoc::all)] 3 | #![allow(rustdoc::missing_doc_code_examples)] 4 | 5 | mod account_validators; 6 | 7 | pub mod events; 8 | 9 | use anchor_lang::prelude::*; 10 | use anchor_lang::solana_program; 11 | use anchor_lang::solana_program::account_info::next_account_infos; 12 | use anchor_spl::token::{self, Mint, Token, TokenAccount}; 13 | use num_traits::cast::ToPrimitive; 14 | use static_pubkey::static_pubkey; 15 | use vipers::validate::Validate; 16 | use vipers::{invariant, unwrap_int}; 17 | 18 | use events::*; 19 | 20 | declare_id!("1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE"); 21 | 22 | /// Address of the withdraw authority to use for this Crate. 23 | pub static WITHDRAW_AUTHORITY_ADDRESS: Pubkey = 24 | static_pubkey!("2amCDqmgpQ2qkryLArCcYeX8DzyNqvjuy7yKq6hsonqF"); 25 | 26 | /// Bump seed of the above address. 27 | pub const WITHDRAW_AUTHORITY_ADDRESS_BUMP: u8 = 255; 28 | 29 | /// Signer seeds of the [WITHDRAW_AUTHORITY_ADDRESS]. 30 | pub static WITHDRAW_AUTHORITY_SIGNER_SEEDS: &[&[&[u8]]] = 31 | &[&[b"CrateRedeemInKind", &[WITHDRAW_AUTHORITY_ADDRESS_BUMP]]]; 32 | 33 | /// [crate_redeem_in_kind] program. 34 | #[program] 35 | pub mod crate_redeem_in_kind { 36 | use std::collections::BTreeMap; 37 | 38 | use super::*; 39 | 40 | /// Redeems Crate tokens for their underlying assets, in-kind. 41 | /// This redemption limits the number of assets that can be redeemed, 42 | /// but it ensures that all assets are redeemed equally. 43 | #[access_control(ctx.accounts.validate())] 44 | pub fn redeem<'info>( 45 | ctx: Context<'_, '_, '_, 'info, Redeem<'info>>, 46 | amount: u64, 47 | ) -> Result<()> { 48 | let burn = token::Burn { 49 | mint: ctx.accounts.crate_mint.to_account_info(), 50 | from: ctx.accounts.crate_source.to_account_info(), 51 | authority: ctx.accounts.owner.to_account_info(), 52 | }; 53 | 54 | token::burn( 55 | CpiContext::new(ctx.accounts.token_program.to_account_info(), burn), 56 | amount, 57 | )?; 58 | 59 | // calculate the fractional slice of each account 60 | let num_remaining_accounts = ctx.remaining_accounts.len(); 61 | if num_remaining_accounts == 0 { 62 | return Ok(()); 63 | } 64 | invariant!( 65 | num_remaining_accounts % 4 == 0, 66 | "must have even number of tokens" 67 | ); 68 | let num_tokens = unwrap_int!(num_remaining_accounts.checked_div(4)); 69 | // TODO: add check to make sure every single token in the crate was redeemed 70 | 71 | let remaining_accounts_iter = &mut ctx.remaining_accounts.iter(); 72 | 73 | for _i in 0..num_tokens { 74 | // none of these accounts need to be validated further, since 75 | // [crate_token::cpi::withdraw] already handles it. 76 | let bumps = &mut BTreeMap::new(); 77 | let asset: RedeemAsset = Accounts::try_accounts( 78 | &crate::ID, 79 | &mut next_account_infos(remaining_accounts_iter, 4)?, 80 | &[], 81 | bumps, 82 | )?; 83 | 84 | let share: u64 = unwrap_int!((asset.crate_underlying.amount as u128) 85 | .checked_mul(amount.into()) 86 | .and_then(|num| num.checked_div(ctx.accounts.crate_mint.supply.into())) 87 | .and_then(|num| num.to_u64())); 88 | 89 | crate_token::cpi::withdraw( 90 | CpiContext::new_with_signer( 91 | ctx.accounts.crate_token_program.to_account_info(), 92 | crate_token::cpi::accounts::Withdraw { 93 | crate_token: ctx.accounts.crate_token.to_account_info(), 94 | crate_underlying: asset.crate_underlying.to_account_info(), 95 | withdraw_authority: ctx.accounts.withdraw_authority.to_account_info(), 96 | withdraw_destination: asset.withdraw_destination.to_account_info(), 97 | author_fee_destination: asset.author_fee_destination.to_account_info(), 98 | protocol_fee_destination: asset.protocol_fee_destination.to_account_info(), 99 | token_program: ctx.accounts.token_program.to_account_info(), 100 | }, 101 | WITHDRAW_AUTHORITY_SIGNER_SEEDS, 102 | ), 103 | share, 104 | )?; 105 | } 106 | 107 | emit!(RedeemEvent { 108 | crate_key: ctx.accounts.crate_token.key(), 109 | source: ctx.accounts.crate_source.key(), 110 | amount 111 | }); 112 | 113 | Ok(()) 114 | } 115 | } 116 | 117 | // -------------------------------- 118 | // Context Structs 119 | // -------------------------------- 120 | 121 | /// Accounts for [crate_redeem_in_kind::redeem]. 122 | #[derive(Accounts)] 123 | pub struct Redeem<'info> { 124 | /// The withdraw authority PDA. 125 | /// CHECK: Arbitrary. 126 | pub withdraw_authority: UncheckedAccount<'info>, 127 | 128 | /// Information about the crate. 129 | #[account(has_one = withdraw_authority)] 130 | pub crate_token: Account<'info, crate_token::CrateToken>, 131 | 132 | /// [Mint] of the [crate_token::CrateToken]. 133 | #[account(mut)] 134 | pub crate_mint: Account<'info, Mint>, 135 | 136 | /// Source of the crate tokens. 137 | #[account(mut)] 138 | pub crate_source: Account<'info, TokenAccount>, 139 | 140 | /// Owner of the crate source. 141 | pub owner: Signer<'info>, 142 | 143 | /// [Token] program. 144 | pub token_program: Program<'info, Token>, 145 | 146 | /// [crate_token] program. 147 | pub crate_token_program: Program<'info, crate_token::program::CrateToken>, 148 | } 149 | 150 | /// Asset redeemed in [crate_redeem_in_kind::redeem]. 151 | #[derive(Accounts)] 152 | pub struct RedeemAsset<'info> { 153 | /// Crate account of the tokens 154 | #[account(mut)] 155 | pub crate_underlying: Account<'info, TokenAccount>, 156 | 157 | /// Destination of the tokens to redeem 158 | #[account(mut)] 159 | pub withdraw_destination: Account<'info, TokenAccount>, 160 | 161 | /// Author fee token destination 162 | #[account(mut)] 163 | pub author_fee_destination: Account<'info, TokenAccount>, 164 | 165 | /// Protocol fee token destination 166 | #[account(mut)] 167 | pub protocol_fee_destination: Account<'info, TokenAccount>, 168 | } 169 | 170 | #[cfg(test)] 171 | mod tests { 172 | use super::*; 173 | #[test] 174 | fn test_withdraw_authority_address() { 175 | let (key, bump) = Pubkey::find_program_address(&[b"CrateRedeemInKind"], &crate::ID); 176 | assert_eq!(key, WITHDRAW_AUTHORITY_ADDRESS); 177 | assert_eq!(bump, WITHDRAW_AUTHORITY_ADDRESS_BUMP); 178 | } 179 | } 180 | -------------------------------------------------------------------------------- /programs/crate-token/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "crate-token" 3 | version = "0.6.0" 4 | description = "Fractional ownership of a basket of fungible assets." 5 | edition = "2021" 6 | homepage = "https://crate.so" 7 | repository = "https://github.com/CrateProtocol/crate" 8 | authors = ["Jen Zhang "] 9 | license = "AGPL-3.0" 10 | keywords = ["solana", "crate"] 11 | 12 | [lib] 13 | crate-type = ["cdylib", "lib"] 14 | name = "crate_token" 15 | 16 | [features] 17 | no-entrypoint = [] 18 | no-idl = [] 19 | cpi = ["no-entrypoint"] 20 | default = [] 21 | 22 | [dependencies] 23 | anchor-lang = "^0.24" 24 | anchor-spl = "^0.24" 25 | static-pubkey = "^1.0.2" 26 | vipers = "^2" 27 | num-traits = "0.2" 28 | -------------------------------------------------------------------------------- /programs/crate-token/README.md: -------------------------------------------------------------------------------- 1 | # `crate-token` 2 | 3 | [![Crates.io](https://img.shields.io/crates/v/crate-token)](https://crates.io/crates/crate-token) 4 | 5 | Program which allows users to create a token that is redeemable for its underlying assets. 6 | 7 | This can be used for many use cases, including but not limited to: 8 | 9 | - ETFs 10 | - Composable Stablecoins 11 | - Rewards distributions 12 | 13 | Program Address: [`CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs`](https://explorer.solana.com/address/CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs) 14 | 15 | ## Protocol fees 16 | 17 | Protocol fees are taken from the `issue_fee` and the `withdraw_fee`-- 20% of this fee goes to the Crate DAO, while the other 80% goes to the Crate's "author". These fees are set by the `fee_setter` and default to zero. 18 | 19 | There are no fees if the Crate's consumer does not take any fees. We want Crate to be a common building block for any ETF-like protocol on the Solana blockchain. 20 | -------------------------------------------------------------------------------- /programs/crate-token/Xargo.toml: -------------------------------------------------------------------------------- 1 | [target.bpfel-unknown-unknown.dependencies.std] 2 | features = [] 3 | -------------------------------------------------------------------------------- /programs/crate-token/src/account_validators.rs: -------------------------------------------------------------------------------- 1 | //! Validate accounts 2 | 3 | use anchor_lang::prelude::*; 4 | use vipers::{assert_keys_eq, invariant}; 5 | 6 | use crate::{Issue, NewCrate, SetFeeTo, SetFeeToSetter, SetFees, Withdraw}; 7 | use anchor_lang::Key; 8 | use vipers::validate::Validate; 9 | 10 | impl<'info> Validate<'info> for NewCrate<'info> { 11 | fn validate(&self) -> Result<()> { 12 | assert_keys_eq!( 13 | self.crate_mint.mint_authority.unwrap(), 14 | self.crate_token, 15 | "crate_mint.mint_authority" 16 | ); 17 | 18 | let freeze_authority = self.crate_mint.freeze_authority.unwrap(); 19 | invariant!( 20 | freeze_authority == self.crate_token.key() 21 | || freeze_authority == self.issue_authority.key(), 22 | InvalidFreezeAuthority 23 | ); 24 | 25 | invariant!(self.crate_mint.supply == 0, "supply must be zero"); 26 | Ok(()) 27 | } 28 | } 29 | 30 | impl<'info> Validate<'info> for SetFees<'info> { 31 | fn validate(&self) -> Result<()> { 32 | assert_keys_eq!( 33 | self.crate_token.fee_setter_authority, 34 | self.fee_setter, 35 | "crate_token.fee_setter_authority" 36 | ); 37 | Ok(()) 38 | } 39 | } 40 | 41 | impl<'info> Validate<'info> for SetFeeTo<'info> { 42 | fn validate(&self) -> Result<()> { 43 | assert_keys_eq!( 44 | self.crate_token.fee_to_setter, 45 | self.fee_to_setter, 46 | "crate_token.fee_to_setter" 47 | ); 48 | Ok(()) 49 | } 50 | } 51 | 52 | impl<'info> Validate<'info> for SetFeeToSetter<'info> { 53 | fn validate(&self) -> Result<()> { 54 | assert_keys_eq!( 55 | self.crate_token.fee_to_setter, 56 | self.fee_to_setter, 57 | "crate_token.fee_to_setter" 58 | ); 59 | Ok(()) 60 | } 61 | } 62 | 63 | impl<'info> Validate<'info> for Issue<'info> { 64 | fn validate(&self) -> Result<()> { 65 | assert_keys_eq!( 66 | self.crate_token.mint, 67 | self.crate_mint.key(), 68 | "crate_token.mint" 69 | ); 70 | assert_keys_eq!( 71 | self.crate_token.issue_authority, 72 | self.issue_authority, 73 | "crate_token.issue_authority" 74 | ); 75 | 76 | assert_keys_eq!( 77 | self.mint_destination.mint, 78 | self.crate_token.mint, 79 | "mint_destination.mint" 80 | ); 81 | 82 | // only validate fee destinations if there are fees 83 | if self.crate_token.issue_fee_bps != 0 { 84 | assert_keys_eq!( 85 | self.author_fee_destination.mint, 86 | self.crate_token.mint, 87 | "author_fee_destination.mint" 88 | ); 89 | assert_keys_eq!( 90 | self.author_fee_destination.owner, 91 | self.crate_token.author_fee_to, 92 | "author_fee_destination.owner" 93 | ); 94 | assert_keys_eq!( 95 | self.protocol_fee_destination.mint, 96 | self.crate_token.mint, 97 | "protocol_fee_destination.mint" 98 | ); 99 | assert_keys_eq!( 100 | self.protocol_fee_destination.owner, 101 | crate::FEE_TO_ADDRESS, 102 | "fee to mismatch" 103 | ); 104 | } 105 | 106 | Ok(()) 107 | } 108 | } 109 | 110 | impl<'info> Validate<'info> for Withdraw<'info> { 111 | fn validate(&self) -> Result<()> { 112 | assert_keys_eq!( 113 | self.crate_underlying.owner, 114 | self.crate_token, 115 | "crate_underlying.owner" 116 | ); 117 | assert_keys_eq!( 118 | self.withdraw_authority, 119 | self.crate_token.withdraw_authority, 120 | "withdraw_authority" 121 | ); 122 | 123 | assert_keys_eq!( 124 | self.withdraw_destination.mint, 125 | self.crate_underlying.mint, 126 | "withdraw_destination.mint" 127 | ); 128 | 129 | // only validate fee destinations if there are fees 130 | if self.crate_token.withdraw_fee_bps != 0 { 131 | assert_keys_eq!( 132 | self.author_fee_destination.mint, 133 | self.crate_underlying.mint, 134 | "author_fee_destination.mint" 135 | ); 136 | assert_keys_eq!( 137 | self.author_fee_destination.owner, 138 | self.crate_token.author_fee_to, 139 | "author_fee_destination.owner" 140 | ); 141 | assert_keys_eq!( 142 | self.protocol_fee_destination.mint, 143 | self.crate_underlying.mint, 144 | "protocol_fee_destination.mint" 145 | ); 146 | assert_keys_eq!( 147 | self.protocol_fee_destination.owner, 148 | crate::FEE_TO_ADDRESS, 149 | "fee to mismatch" 150 | ); 151 | } 152 | 153 | Ok(()) 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /programs/crate-token/src/events.rs: -------------------------------------------------------------------------------- 1 | //! Crate events 2 | #![deny(missing_docs)] 3 | 4 | use anchor_lang::prelude::*; 5 | 6 | /// Emitted when a crate is created. 7 | #[event] 8 | pub struct NewCrateEvent { 9 | /// Key of the created crate. 10 | #[index] 11 | pub crate_key: Pubkey, 12 | /// Issue authority. 13 | #[index] 14 | pub issue_authority: Pubkey, 15 | /// Withdraw authority. 16 | #[index] 17 | pub withdraw_authority: Pubkey, 18 | } 19 | 20 | /// Emitted when crate tokens are issued. 21 | #[event] 22 | pub struct IssueEvent { 23 | /// Key of the created crate. 24 | #[index] 25 | pub crate_key: Pubkey, 26 | /// Destination token account. 27 | pub destination: Pubkey, 28 | /// Amount of tokens issued. 29 | pub amount: u64, 30 | /// Author fee. 31 | pub author_fee: u64, 32 | /// Protocol fee. 33 | pub protocol_fee: u64, 34 | } 35 | 36 | /// Emitted when crate tokens are withdrawn. 37 | #[event] 38 | pub struct WithdrawEvent { 39 | /// Key of the crate withdrawn from. 40 | #[index] 41 | pub crate_key: Pubkey, 42 | /// Mint of the withdrawn token. 43 | pub token: Pubkey, 44 | /// Destination of tokens. 45 | pub destination: Pubkey, 46 | /// Amount of tokens withdrawn. 47 | pub amount: u64, 48 | /// Author fee. 49 | pub author_fee: u64, 50 | /// Protocol fee. 51 | pub protocol_fee: u64, 52 | } 53 | -------------------------------------------------------------------------------- /programs/crate-token/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Crate Token. 2 | #![deny(rustdoc::all)] 3 | #![allow(rustdoc::missing_doc_code_examples)] 4 | 5 | mod account_validators; 6 | mod macros; 7 | 8 | pub mod events; 9 | pub mod state; 10 | 11 | use anchor_lang::prelude::*; 12 | use anchor_lang::solana_program; 13 | use anchor_spl::token::{self, Mint, Token, TokenAccount}; 14 | use static_pubkey::static_pubkey; 15 | use vipers::prelude::*; 16 | 17 | use events::*; 18 | pub use state::*; 19 | 20 | declare_id!("CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs"); 21 | 22 | /// Address where fees are sent to. 23 | pub static FEE_TO_ADDRESS: Pubkey = static_pubkey!("AAqAKWdsUPepSgXf7Msbp1pQ7yCPgYkBvXmNfTFBGAqp"); 24 | 25 | /// Issuance fee as a portion of the crate's fee, in bps. 26 | pub static ISSUE_FEE_BPS: u16 = 2_000; 27 | 28 | /// Withdraw fee as a portion of the crate's fee, in bps. 29 | pub static WITHDRAW_FEE_BPS: u16 = 2_000; 30 | 31 | /// Maximum fee for anything. 32 | pub const MAX_FEE_BPS: u16 = 10_000; 33 | 34 | /// [crate_token] program. 35 | #[program] 36 | pub mod crate_token { 37 | use super::*; 38 | 39 | /// Provisions a new Crate. 40 | #[access_control(ctx.accounts.validate())] 41 | pub fn new_crate(ctx: Context, _bump: u8) -> Result<()> { 42 | let info = &mut ctx.accounts.crate_token; 43 | info.mint = ctx.accounts.crate_mint.key(); 44 | info.bump = unwrap_bump!(ctx, "crate_token"); 45 | 46 | info.fee_to_setter = ctx.accounts.fee_to_setter.key(); 47 | info.fee_setter_authority = ctx.accounts.fee_setter_authority.key(); 48 | info.issue_authority = ctx.accounts.issue_authority.key(); 49 | info.withdraw_authority = ctx.accounts.withdraw_authority.key(); 50 | info.author_fee_to = ctx.accounts.author_fee_to.key(); 51 | 52 | info.issue_fee_bps = 0; 53 | info.withdraw_fee_bps = 0; 54 | 55 | emit!(NewCrateEvent { 56 | issue_authority: ctx.accounts.issue_authority.key(), 57 | withdraw_authority: ctx.accounts.withdraw_authority.key(), 58 | crate_key: ctx.accounts.crate_token.key(), 59 | }); 60 | 61 | Ok(()) 62 | } 63 | 64 | /// Set the issue fee. 65 | /// Only the `fee_setter_authority` can call this. 66 | #[access_control(ctx.accounts.validate())] 67 | pub fn set_issue_fee(ctx: Context, issue_fee_bps: u16) -> Result<()> { 68 | invariant!(issue_fee_bps <= MAX_FEE_BPS, MaxFeeExceeded); 69 | let crate_token = &mut ctx.accounts.crate_token; 70 | crate_token.issue_fee_bps = issue_fee_bps; 71 | Ok(()) 72 | } 73 | 74 | /// Set the withdraw fee. 75 | /// Only the `fee_setter_authority` can call this. 76 | #[access_control(ctx.accounts.validate())] 77 | pub fn set_withdraw_fee(ctx: Context, withdraw_fee_bps: u16) -> Result<()> { 78 | invariant!(withdraw_fee_bps <= MAX_FEE_BPS, MaxFeeExceeded); 79 | let crate_token = &mut ctx.accounts.crate_token; 80 | crate_token.withdraw_fee_bps = withdraw_fee_bps; 81 | Ok(()) 82 | } 83 | 84 | /// Set the next recipient of the fees. 85 | /// Only the `fee_to_setter` can call this. 86 | #[access_control(ctx.accounts.validate())] 87 | pub fn set_fee_to(ctx: Context) -> Result<()> { 88 | let crate_token = &mut ctx.accounts.crate_token; 89 | crate_token.author_fee_to = ctx.accounts.author_fee_to.key(); 90 | Ok(()) 91 | } 92 | 93 | /// Sets who can change who sets the fees. 94 | /// Only the `fee_to_setter` can call this. 95 | #[access_control(ctx.accounts.validate())] 96 | pub fn set_fee_to_setter(ctx: Context) -> Result<()> { 97 | let crate_token = &mut ctx.accounts.crate_token; 98 | crate_token.fee_to_setter = ctx.accounts.next_fee_to_setter.key(); 99 | Ok(()) 100 | } 101 | 102 | /// Issues Crate tokens. 103 | /// Only the `issue_authority` can call this. 104 | #[access_control(ctx.accounts.validate())] 105 | pub fn issue(ctx: Context, amount: u64) -> Result<()> { 106 | // Do nothing if there is a zero amount. 107 | if amount == 0 { 108 | return Ok(()); 109 | } 110 | 111 | let seeds: &[&[u8]] = gen_crate_signer_seeds!(ctx.accounts.crate_token); 112 | let crate_token = &ctx.accounts.crate_token; 113 | let state::Fees { 114 | amount, 115 | author_fee, 116 | protocol_fee, 117 | } = crate_token.apply_issue_fee(amount)?; 118 | 119 | token::mint_to( 120 | CpiContext::new_with_signer( 121 | ctx.accounts.token_program.to_account_info(), 122 | token::MintTo { 123 | mint: ctx.accounts.crate_mint.to_account_info(), 124 | to: ctx.accounts.mint_destination.to_account_info(), 125 | authority: ctx.accounts.crate_token.to_account_info(), 126 | }, 127 | &[seeds], 128 | ), 129 | amount, 130 | )?; 131 | 132 | if author_fee > 0 { 133 | token::mint_to( 134 | CpiContext::new_with_signer( 135 | ctx.accounts.token_program.to_account_info(), 136 | token::MintTo { 137 | mint: ctx.accounts.crate_mint.to_account_info(), 138 | to: ctx.accounts.author_fee_destination.to_account_info(), 139 | authority: ctx.accounts.crate_token.to_account_info(), 140 | }, 141 | &[seeds], 142 | ), 143 | author_fee, 144 | )?; 145 | } 146 | 147 | if protocol_fee > 0 { 148 | token::mint_to( 149 | CpiContext::new_with_signer( 150 | ctx.accounts.token_program.to_account_info(), 151 | token::MintTo { 152 | mint: ctx.accounts.crate_mint.to_account_info(), 153 | to: ctx.accounts.protocol_fee_destination.to_account_info(), 154 | authority: ctx.accounts.crate_token.to_account_info(), 155 | }, 156 | &[seeds], 157 | ), 158 | protocol_fee, 159 | )?; 160 | } 161 | 162 | emit!(IssueEvent { 163 | crate_key: ctx.accounts.crate_token.key(), 164 | destination: ctx.accounts.mint_destination.key(), 165 | amount, 166 | author_fee, 167 | protocol_fee 168 | }); 169 | 170 | Ok(()) 171 | } 172 | 173 | /// Withdraws Crate tokens. 174 | /// Only the `withdraw_authority` can call this. 175 | #[access_control(ctx.accounts.validate())] 176 | pub fn withdraw(ctx: Context, amount: u64) -> Result<()> { 177 | // Do nothing if there is a zero amount. 178 | if amount == 0 { 179 | return Ok(()); 180 | } 181 | 182 | let token_program = ctx.accounts.token_program.to_account_info(); 183 | let seeds = gen_crate_signer_seeds!(ctx.accounts.crate_token); 184 | let signer_seeds: &[&[&[u8]]] = &[seeds]; 185 | let crate_token = &ctx.accounts.crate_token; 186 | let state::Fees { 187 | amount, 188 | author_fee, 189 | protocol_fee, 190 | } = crate_token.apply_withdraw_fee(amount)?; 191 | 192 | // share 193 | token::transfer( 194 | CpiContext::new_with_signer( 195 | token_program.clone(), 196 | token::Transfer { 197 | from: ctx.accounts.crate_underlying.to_account_info(), 198 | to: ctx.accounts.withdraw_destination.to_account_info(), 199 | authority: ctx.accounts.crate_token.to_account_info(), 200 | }, 201 | signer_seeds, 202 | ), 203 | amount, 204 | )?; 205 | 206 | if author_fee > 0 { 207 | token::transfer( 208 | CpiContext::new_with_signer( 209 | token_program.clone(), 210 | token::Transfer { 211 | from: ctx.accounts.crate_underlying.to_account_info(), 212 | to: ctx.accounts.author_fee_destination.to_account_info(), 213 | authority: ctx.accounts.crate_token.to_account_info(), 214 | }, 215 | signer_seeds, 216 | ), 217 | author_fee, 218 | )?; 219 | } 220 | 221 | if protocol_fee > 0 { 222 | token::transfer( 223 | CpiContext::new_with_signer( 224 | token_program.clone(), 225 | token::Transfer { 226 | from: ctx.accounts.crate_underlying.to_account_info(), 227 | to: ctx.accounts.protocol_fee_destination.to_account_info(), 228 | authority: ctx.accounts.crate_token.to_account_info(), 229 | }, 230 | signer_seeds, 231 | ), 232 | protocol_fee, 233 | )?; 234 | } 235 | 236 | emit!(WithdrawEvent { 237 | crate_key: ctx.accounts.crate_token.key(), 238 | token: ctx.accounts.crate_underlying.mint, 239 | destination: ctx.accounts.withdraw_destination.key(), 240 | amount, 241 | author_fee, 242 | protocol_fee, 243 | }); 244 | 245 | Ok(()) 246 | } 247 | } 248 | 249 | // -------------------------------- 250 | // Context Structs 251 | // -------------------------------- 252 | 253 | /// Accounts for [crate_token::new_crate]. 254 | #[derive(Accounts)] 255 | pub struct NewCrate<'info> { 256 | /// Information about the crate. 257 | #[account( 258 | init, 259 | seeds = [ 260 | b"CrateToken".as_ref(), 261 | crate_mint.key().to_bytes().as_ref() 262 | ], 263 | bump, 264 | space = 8 + CrateToken::LEN, 265 | payer = payer 266 | )] 267 | pub crate_token: Account<'info, CrateToken>, 268 | 269 | /// [Mint] of the [CrateToken]. 270 | pub crate_mint: Account<'info, Mint>, 271 | 272 | /// The authority that can change who fees go to. 273 | /// CHECK: Arbitrary input. 274 | pub fee_to_setter: UncheckedAccount<'info>, 275 | 276 | /// The authority that can set fees. 277 | /// CHECK: Arbitrary input. 278 | pub fee_setter_authority: UncheckedAccount<'info>, 279 | 280 | /// The authority that can issue new [CrateToken] tokens. 281 | /// CHECK: Arbitrary input. 282 | pub issue_authority: UncheckedAccount<'info>, 283 | 284 | /// The authority that can redeem the [CrateToken] token underlying. 285 | /// CHECK: Arbitrary input. 286 | pub withdraw_authority: UncheckedAccount<'info>, 287 | 288 | /// Owner of the author fee accounts. 289 | /// CHECK: Arbitrary input. 290 | pub author_fee_to: UncheckedAccount<'info>, 291 | 292 | /// Payer of the crate initialization. 293 | #[account(mut)] 294 | pub payer: Signer<'info>, 295 | 296 | /// System program. 297 | pub system_program: Program<'info, System>, 298 | } 299 | 300 | /// Accounts for [crate_token::set_issue_fee] and [crate_token::set_withdraw_fee]. 301 | #[derive(Accounts)] 302 | #[instruction(bump: u8)] 303 | pub struct SetFees<'info> { 304 | /// Information about the crate. 305 | #[account(mut)] 306 | pub crate_token: Account<'info, CrateToken>, 307 | 308 | /// Account that can set the fees. 309 | pub fee_setter: Signer<'info>, 310 | } 311 | 312 | /// Accounts for [crate_token::set_fee_to]. 313 | #[derive(Accounts)] 314 | #[instruction(bump: u8)] 315 | pub struct SetFeeTo<'info> { 316 | /// Information about the crate. 317 | #[account(mut)] 318 | pub crate_token: Account<'info, CrateToken>, 319 | /// Account that can set the fee recipient. 320 | pub fee_to_setter: Signer<'info>, 321 | /// Who the fees go to. 322 | /// CHECK: Arbitrary input. 323 | pub author_fee_to: UncheckedAccount<'info>, 324 | } 325 | 326 | /// Accounts for [crate_token::set_fee_to_setter]. 327 | #[derive(Accounts)] 328 | #[instruction(bump: u8)] 329 | pub struct SetFeeToSetter<'info> { 330 | /// Information about the crate. 331 | #[account(mut)] 332 | pub crate_token: Account<'info, CrateToken>, 333 | /// Account that can set the fee recipient. 334 | pub fee_to_setter: Signer<'info>, 335 | /// Who will be able to change the fees next. 336 | /// CHECK: Arbitrary input. 337 | pub next_fee_to_setter: UncheckedAccount<'info>, 338 | } 339 | 340 | /// Accounts for [crate_token::issue]. 341 | #[derive(Accounts)] 342 | pub struct Issue<'info> { 343 | /// Information about the crate. 344 | pub crate_token: Account<'info, CrateToken>, 345 | 346 | /// [Mint] of the [CrateToken]. 347 | #[account(mut)] 348 | pub crate_mint: Account<'info, Mint>, 349 | 350 | /// Authority of the account issuing Crate tokens. 351 | pub issue_authority: Signer<'info>, 352 | 353 | /// Destination of the minted tokens. 354 | #[account(mut)] 355 | pub mint_destination: Account<'info, TokenAccount>, 356 | 357 | /// Destination of the author fee tokens. 358 | #[account(mut)] 359 | pub author_fee_destination: Account<'info, TokenAccount>, 360 | 361 | /// Destination of the protocol fee tokens. 362 | #[account(mut)] 363 | pub protocol_fee_destination: Account<'info, TokenAccount>, 364 | 365 | /// [Token] program. 366 | pub token_program: Program<'info, Token>, 367 | } 368 | 369 | /// Accounts for [crate_token::withdraw]. 370 | #[derive(Accounts)] 371 | pub struct Withdraw<'info> { 372 | /// Information about the crate. 373 | pub crate_token: Account<'info, CrateToken>, 374 | 375 | /// Crate-owned account of the tokens 376 | #[account(mut)] 377 | pub crate_underlying: Account<'info, TokenAccount>, 378 | 379 | /// Authority that can withdraw. 380 | pub withdraw_authority: Signer<'info>, 381 | 382 | /// Destination of the withdrawn tokens. 383 | #[account(mut)] 384 | pub withdraw_destination: Account<'info, TokenAccount>, 385 | 386 | /// Destination of the author fee tokens. 387 | #[account(mut)] 388 | pub author_fee_destination: Account<'info, TokenAccount>, 389 | 390 | /// Destination of the protocol fee tokens. 391 | #[account(mut)] 392 | pub protocol_fee_destination: Account<'info, TokenAccount>, 393 | 394 | /// [Token] program. 395 | pub token_program: Program<'info, Token>, 396 | } 397 | 398 | #[error_code] 399 | /// Error codes. 400 | pub enum ErrorCode { 401 | #[msg("Maximum fee exceeded.")] 402 | MaxFeeExceeded, 403 | #[msg("Freeze authority must either be the issuer or the Crate itself.")] 404 | InvalidFreezeAuthority, 405 | } 406 | 407 | #[cfg(test)] 408 | mod tests { 409 | use super::*; 410 | #[test] 411 | fn test_fee_to_address() { 412 | let (key, bump) = Pubkey::find_program_address(&[b"CrateFees"], &crate::ID); 413 | assert_eq!(key, FEE_TO_ADDRESS); 414 | assert_eq!(bump, 254); 415 | } 416 | } 417 | -------------------------------------------------------------------------------- /programs/crate-token/src/macros.rs: -------------------------------------------------------------------------------- 1 | /// Generates the signer seeds for a [crate::state::CrateToken]. 2 | #[macro_export] 3 | macro_rules! gen_crate_signer_seeds { 4 | ($ctoken:expr) => { 5 | &[ 6 | b"CrateToken".as_ref(), 7 | $ctoken.mint.as_ref(), 8 | &[$ctoken.bump], 9 | ] 10 | }; 11 | } 12 | -------------------------------------------------------------------------------- /programs/crate-token/src/state.rs: -------------------------------------------------------------------------------- 1 | use anchor_lang::{prelude::*, solana_program::pubkey::PUBKEY_BYTES}; 2 | use num_traits::ToPrimitive; 3 | use vipers::unwrap_int; 4 | 5 | /// Contains the info of a crate token. Immutable. 6 | /// The account associated with this struct is also the mint/freeze authority. 7 | #[account] 8 | #[derive(Copy, Debug, Default, PartialEq, Eq)] 9 | pub struct CrateToken { 10 | /// [anchor_spl::token::Mint] of the [CrateToken]. 11 | pub mint: Pubkey, 12 | /// Bump. 13 | pub bump: u8, 14 | 15 | /// Authority that can modify the [CrateToken]'s fees. 16 | pub fee_setter_authority: Pubkey, 17 | /// Authority that can modify who can change the fees. 18 | pub fee_to_setter: Pubkey, 19 | /// Authority that is allowed to issue new shares of the Crate. 20 | /// This is usually a program that will handle users depositing 21 | /// tokens into the crate + giving them shares of the crate. 22 | pub issue_authority: Pubkey, 23 | /// Authority that is allowed to withdraw any token from the Crate. 24 | /// Withdrawals may be subject to fees. 25 | pub withdraw_authority: Pubkey, 26 | 27 | /// Account which is the recipient of issue/withdraw ("author") fees. 28 | /// If fees do not exist, this is unused. 29 | pub author_fee_to: Pubkey, 30 | 31 | /// The issuance fee in bps. 32 | /// [crate::ISSUE_FEE_BPS] of this fee goes to the Crate DAO. 33 | pub issue_fee_bps: u16, 34 | /// The issuance fee in bps. 35 | /// [crate::WITHDRAW_FEE_BPS] of this fee goes to the Crate DAO. 36 | pub withdraw_fee_bps: u16, 37 | } 38 | 39 | impl CrateToken { 40 | pub const LEN: usize = PUBKEY_BYTES + 1 + PUBKEY_BYTES * 5 + 2 + 2; 41 | } 42 | 43 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] 44 | pub struct Fees { 45 | pub amount: u64, 46 | /// Fee to the Crate's author. 47 | pub author_fee: u64, 48 | /// Fee to the Crate protocol. 49 | pub protocol_fee: u64, 50 | } 51 | 52 | fn apply_bps(amount: u64, bps: u16) -> Result<(u64, u64)> { 53 | let bps = unwrap_int!((amount) 54 | .checked_mul(bps.into()) 55 | .and_then(|v| v.checked_div(10_000)) 56 | .and_then(|v| v.to_u64())); 57 | Ok((unwrap_int!(amount.checked_sub(bps)), bps)) 58 | } 59 | 60 | impl CrateToken { 61 | /// Applies the issuance fee. 62 | pub fn apply_issue_fee(&self, amount: u64) -> Result { 63 | let (amount, issue_fee) = apply_bps(amount, self.issue_fee_bps)?; 64 | let (author_fee, protocol_fee) = apply_bps(issue_fee, crate::ISSUE_FEE_BPS)?; 65 | Ok(Fees { 66 | amount, 67 | author_fee, 68 | protocol_fee, 69 | }) 70 | } 71 | 72 | /// Applies the withdraw fee. 73 | pub fn apply_withdraw_fee(&self, amount: u64) -> Result { 74 | let (amount, withdraw_fee) = apply_bps(amount, self.withdraw_fee_bps)?; 75 | let (author_fee, protocol_fee) = apply_bps(withdraw_fee, crate::WITHDRAW_FEE_BPS)?; 76 | Ok(Fees { 77 | amount, 78 | author_fee, 79 | protocol_fee, 80 | }) 81 | } 82 | } 83 | 84 | #[cfg(test)] 85 | mod tests { 86 | use super::*; 87 | 88 | #[test] 89 | fn test_crate_token_len() { 90 | use crate::CrateToken; 91 | assert_eq!( 92 | CrateToken::LEN, 93 | CrateToken::default().try_to_vec().unwrap().len() 94 | ); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /scripts/generate-idl-types.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | shopt -s extglob 4 | 5 | cd $(dirname $0)/.. 6 | 7 | generate_declaration_file() { 8 | PROGRAM_SO=$1 9 | OUT_DIR=$2 10 | 11 | prog="$(basename $PROGRAM_SO .json)" 12 | OUT_PATH="$OUT_DIR/$prog.ts" 13 | if [ ! $(which gsed) ]; then 14 | PREFIX=$(echo $prog | sed -E 's/(^|_)([a-z])/\U\2/g') 15 | else 16 | PREFIX=$(echo $prog | gsed -E 's/(^|_)([a-z])/\U\2/g') 17 | fi 18 | typename="${PREFIX}IDL" 19 | rawName="${PREFIX}JSON" 20 | 21 | # types 22 | echo "export type $typename =" >>$OUT_PATH 23 | cat $PROGRAM_SO >>$OUT_PATH 24 | echo ";" >>$OUT_PATH 25 | 26 | # raw json 27 | echo "export const $rawName: $typename =" >>$OUT_PATH 28 | cat $PROGRAM_SO >>$OUT_PATH 29 | echo ";" >>$OUT_PATH 30 | 31 | # error type 32 | echo "import { generateErrorMap } from '@saberhq/anchor-contrib';" >>$OUT_PATH 33 | echo "export const ${PREFIX}Errors = generateErrorMap($rawName);" >>$OUT_PATH 34 | } 35 | 36 | generate_sdk_idls() { 37 | SDK_DIR=${1:-"./packages/sdk/src/idls"} 38 | IDL_JSONS=$2 39 | 40 | echo "Generating IDLs for the following programs:" 41 | echo $IDL_JSONS 42 | echo "" 43 | 44 | rm -rf $SDK_DIR 45 | mkdir -p $SDK_DIR 46 | if [ $(ls -l artifacts/idl/ | wc -l) -ne 0 ]; then 47 | for f in $IDL_JSONS; do 48 | generate_declaration_file $f $SDK_DIR 49 | done 50 | if [[ $RUN_ESLINT != "none" ]]; then 51 | yarn eslint --fix $SDK_DIR 52 | fi 53 | else 54 | echo "Warning: no IDLs found. Make sure you ran ./scripts/idl.sh first." 55 | fi 56 | } 57 | 58 | generate_sdk_idls ./src/idls 'artifacts/idl/*.json' 59 | -------------------------------------------------------------------------------- /scripts/parse-idls.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # This script generates the IDL JSONs without buildling the full packages. 4 | 5 | rm -fr artifacts/idl/ 6 | mkdir -p artifacts/idl/ 7 | 8 | for PROGRAM in $(find programs/ -maxdepth 3 -name lib.rs); do 9 | PROGRAM_NAME=$(dirname $PROGRAM | xargs dirname | xargs basename | tr '-' '_') 10 | echo "Parsing IDL for $PROGRAM_NAME" 11 | anchor idl parse --file $PROGRAM >artifacts/idl/$PROGRAM_NAME.json || { 12 | echo "Could not parse IDL" 13 | exit 1 14 | } 15 | done 16 | -------------------------------------------------------------------------------- /shell.nix: -------------------------------------------------------------------------------- 1 | { pkgs }: 2 | pkgs.stdenvNoCC.mkDerivation { 3 | name = "devshell"; 4 | nativeBuiltInputs = (pkgs.lib.optionals pkgs.stdenv.isDarwin [ 5 | pkgs.darwin.apple_sdk.frameworks.AppKit 6 | pkgs.darwin.apple_sdk.frameworks.IOKit 7 | pkgs.darwin.apple_sdk.frameworks.Foundation 8 | ]); 9 | buildInputs = with pkgs; 10 | (pkgs.lib.optionals pkgs.stdenv.isLinux ([ 11 | # solana 12 | udev 13 | ])) ++ [ 14 | rustup 15 | cargo-deps 16 | gh 17 | 18 | # sdk 19 | nodejs 20 | yarn 21 | python3 22 | 23 | pkgconfig 24 | openssl 25 | jq 26 | gnused 27 | 28 | libiconv 29 | 30 | cargo-workspaces 31 | anchor-0_24_2 32 | spl-token-cli 33 | ] ++ (pkgs.lib.optionals pkgs.stdenv.isDarwin [ 34 | pkgs.darwin.apple_sdk.frameworks.AppKit 35 | pkgs.darwin.apple_sdk.frameworks.IOKit 36 | pkgs.darwin.apple_sdk.frameworks.Foundation 37 | ]); 38 | shellHook = '' 39 | export PATH=$PATH:$HOME/.cargo/bin 40 | ''; 41 | } 42 | -------------------------------------------------------------------------------- /src/constants.ts: -------------------------------------------------------------------------------- 1 | import { buildCoderMap } from "@saberhq/anchor-contrib"; 2 | import { PublicKey } from "@solana/web3.js"; 3 | 4 | import type { 5 | CrateRedeemInKindProgram, 6 | CrateRedeemInKindTypes, 7 | } from "./programs/crateRedeemInKind"; 8 | import { CrateRedeemInKindJSON } from "./programs/crateRedeemInKind"; 9 | import type { CrateTokenProgram, CrateTokenTypes } from "./programs/crateToken"; 10 | import { CrateTokenJSON } from "./programs/crateToken"; 11 | 12 | export const CRATE_IDLS = { 13 | CrateToken: CrateTokenJSON, 14 | CrateRedeemInKind: CrateRedeemInKindJSON, 15 | }; 16 | 17 | export const CRATE_ADDRESSES = { 18 | CrateToken: new PublicKey("CRATwLpu6YZEeiVq9ajjxs61wPQ9f29s1UoQR9siJCRs"), 19 | CrateRedeemInKind: new PublicKey( 20 | "1NKyU3qShZC3oJgvCCftAHDi5TFxcJwfyUz2FeZsiwE" 21 | ), 22 | }; 23 | 24 | export interface CratePrograms { 25 | CrateToken: CrateTokenProgram; 26 | CrateRedeemInKind: CrateRedeemInKindProgram; 27 | } 28 | 29 | export type CrateAddresses = { [K in keyof typeof CRATE_ADDRESSES]: PublicKey }; 30 | 31 | export const CRATE_FEE_OWNER = new PublicKey( 32 | "AAqAKWdsUPepSgXf7Msbp1pQ7yCPgYkBvXmNfTFBGAqp" 33 | ); 34 | 35 | export const CRATE_REDEEM_IN_KIND_WITHDRAW_AUTHORITY = new PublicKey( 36 | "2amCDqmgpQ2qkryLArCcYeX8DzyNqvjuy7yKq6hsonqF" 37 | ); 38 | 39 | /** 40 | * Coders for Crate accounts and programs. 41 | */ 42 | export const CRATE_CODERS = buildCoderMap<{ 43 | CrateToken: CrateTokenTypes; 44 | CrateRedeemInKind: CrateRedeemInKindTypes; 45 | }>(CRATE_IDLS, CRATE_ADDRESSES); 46 | -------------------------------------------------------------------------------- /src/crateToken.ts: -------------------------------------------------------------------------------- 1 | import { newProgramMap } from "@saberhq/anchor-contrib"; 2 | import type { AugmentedProvider, Provider } from "@saberhq/solana-contrib"; 3 | import { 4 | SolanaAugmentedProvider, 5 | TransactionEnvelope, 6 | } from "@saberhq/solana-contrib"; 7 | import type { Token, TokenAmount } from "@saberhq/token-utils"; 8 | import { 9 | createInitMintInstructions, 10 | getOrCreateATA, 11 | getOrCreateATAs, 12 | TOKEN_PROGRAM_ID, 13 | } from "@saberhq/token-utils"; 14 | import type { 15 | AccountMeta, 16 | Signer, 17 | TransactionInstruction, 18 | } from "@solana/web3.js"; 19 | import { Keypair, PublicKey, SystemProgram } from "@solana/web3.js"; 20 | import invariant from "tiny-invariant"; 21 | 22 | import type { CrateAddresses, CratePrograms } from "./constants"; 23 | import { 24 | CRATE_ADDRESSES, 25 | CRATE_FEE_OWNER, 26 | CRATE_IDLS, 27 | CRATE_REDEEM_IN_KIND_WITHDRAW_AUTHORITY, 28 | } from "./constants"; 29 | import { generateCrateAddress } from "./pda"; 30 | import type { CrateTokenData } from "./programs/crateToken"; 31 | 32 | /** 33 | * Javascript SDK for interacting with the Crate protocol. 34 | */ 35 | export class CrateSDK { 36 | constructor( 37 | readonly provider: AugmentedProvider, 38 | readonly programs: CratePrograms 39 | ) {} 40 | 41 | /** 42 | * Initialize from a Provider 43 | * @param provider 44 | * @param crateTokenProgramId 45 | * @returns 46 | */ 47 | static init( 48 | provider: Provider, 49 | addresses: CrateAddresses = CRATE_ADDRESSES 50 | ): CrateSDK { 51 | return new CrateSDK( 52 | new SolanaAugmentedProvider(provider), 53 | newProgramMap(provider, CRATE_IDLS, addresses) 54 | ); 55 | } 56 | 57 | /** 58 | * Creates a new instance of the SDK with the given keypair. 59 | */ 60 | withSigner(signer: Signer): CrateSDK { 61 | return CrateSDK.init(this.provider.withSigner(signer)); 62 | } 63 | 64 | /** 65 | * Creates a new Crate. 66 | * @returns 67 | */ 68 | async newCrate({ 69 | mintKP = Keypair.generate(), 70 | decimals = 6, 71 | payer = this.provider.wallet.publicKey, 72 | 73 | feeToSetter = this.provider.wallet.publicKey, 74 | feeSetterAuthority = this.provider.wallet.publicKey, 75 | issueAuthority = this.provider.wallet.publicKey, 76 | withdrawAuthority = CRATE_REDEEM_IN_KIND_WITHDRAW_AUTHORITY, 77 | authorFeeTo = PublicKey.default, 78 | }: { 79 | mintKP?: Keypair; 80 | decimals?: number; 81 | payer?: PublicKey; 82 | 83 | feeToSetter?: PublicKey; 84 | feeSetterAuthority?: PublicKey; 85 | issueAuthority?: PublicKey; 86 | withdrawAuthority?: PublicKey; 87 | /** 88 | * Who to send the author fees to. 89 | */ 90 | authorFeeTo?: PublicKey; 91 | } = {}): Promise<{ tx: TransactionEnvelope; crateKey: PublicKey }> { 92 | const [crateKey, bump] = await generateCrateAddress(mintKP.publicKey); 93 | 94 | const initMintTX = await createInitMintInstructions({ 95 | provider: this.provider, 96 | mintKP, 97 | decimals, 98 | mintAuthority: crateKey, 99 | freezeAuthority: crateKey, 100 | }); 101 | const newCrateTX = new TransactionEnvelope(this.provider, [ 102 | this.programs.CrateToken.instruction.newCrate(bump, { 103 | accounts: { 104 | crateToken: crateKey, 105 | crateMint: mintKP.publicKey, 106 | feeToSetter, 107 | feeSetterAuthority, 108 | issueAuthority, 109 | withdrawAuthority, 110 | authorFeeTo, 111 | payer, 112 | systemProgram: SystemProgram.programId, 113 | }, 114 | }), 115 | ]); 116 | 117 | return { tx: initMintTX.combine(newCrateTX), crateKey }; 118 | } 119 | 120 | setIssueFee(crateKey: PublicKey, feeBPS: number): TransactionEnvelope { 121 | return new TransactionEnvelope(this.provider, [ 122 | this.programs.CrateToken.instruction.setIssueFee(feeBPS, { 123 | accounts: { 124 | crateToken: crateKey, 125 | feeSetter: this.provider.wallet.publicKey, 126 | }, 127 | }), 128 | ]); 129 | } 130 | 131 | setWithdrawFee(crateKey: PublicKey, feeBPS: number): TransactionEnvelope { 132 | return new TransactionEnvelope(this.provider, [ 133 | this.programs.CrateToken.instruction.setWithdrawFee(feeBPS, { 134 | accounts: { 135 | crateToken: crateKey, 136 | feeSetter: this.provider.wallet.publicKey, 137 | }, 138 | }), 139 | ]); 140 | } 141 | 142 | async fetchCrateTokenData(key: PublicKey): Promise { 143 | return (await this.programs.CrateToken.account.crateToken.fetchNullable( 144 | key 145 | )) as CrateTokenData; 146 | } 147 | 148 | /** 149 | * Issues Crate tokens as the issuer. 150 | * @returns 151 | */ 152 | async issue({ 153 | amount, 154 | issueAuthority = this.provider.wallet.publicKey, 155 | mintDestination, 156 | }: { 157 | amount: TokenAmount; 158 | issueAuthority?: PublicKey; 159 | mintDestination: PublicKey; 160 | }): Promise { 161 | const [crateKey] = await generateCrateAddress(amount.token.mintAccount); 162 | 163 | const crateTokenData = await this.fetchCrateTokenData(crateKey); 164 | if (!crateTokenData) { 165 | throw new Error("Crate does not exist."); 166 | } 167 | 168 | const ixs = []; 169 | const feeDestinations = { 170 | authorFeeDestination: mintDestination, 171 | protocolFeeDestination: mintDestination, 172 | }; 173 | if (crateTokenData.issueFeeBps !== 0) { 174 | const [authorFeeATA, protocolFeeATA] = await Promise.all([ 175 | getOrCreateATA({ 176 | provider: this.provider, 177 | mint: crateTokenData.mint, 178 | owner: crateTokenData.authorFeeTo, 179 | }), 180 | getOrCreateATA({ 181 | provider: this.provider, 182 | mint: crateTokenData.mint, 183 | owner: CRATE_FEE_OWNER, 184 | }), 185 | ]); 186 | 187 | feeDestinations.authorFeeDestination = authorFeeATA.address; 188 | feeDestinations.protocolFeeDestination = protocolFeeATA.address; 189 | ixs.push( 190 | ...[ 191 | ...(authorFeeATA.instruction ? [authorFeeATA.instruction] : []), 192 | ...(protocolFeeATA.instruction ? [protocolFeeATA.instruction] : []), 193 | ] 194 | ); 195 | } 196 | 197 | return new TransactionEnvelope(this.provider, [ 198 | this.programs.CrateToken.instruction.issue(amount.toU64(), { 199 | accounts: { 200 | crateToken: crateKey, 201 | crateMint: amount.token.mintAccount, 202 | issueAuthority, 203 | mintDestination, 204 | tokenProgram: TOKEN_PROGRAM_ID, 205 | ...feeDestinations, 206 | }, 207 | }), 208 | ]); 209 | } 210 | 211 | /** 212 | * Redeems Crate tokens for the underlying tokens. 213 | */ 214 | async redeem({ 215 | amount, 216 | owner = this.provider.wallet.publicKey, 217 | underlyingTokens, 218 | }: { 219 | amount: TokenAmount; 220 | owner?: PublicKey; 221 | /** 222 | * Underlying tokens list. Ensure this is complete. 223 | */ 224 | underlyingTokens: Token[]; 225 | }): Promise { 226 | const [crateKey] = await generateCrateAddress(amount.token.mintAccount); 227 | const crateTokenData = 228 | (await this.programs.CrateToken.account.crateToken.fetchNullable( 229 | crateKey 230 | )) as CrateTokenData; 231 | if (!crateTokenData) { 232 | throw new Error("Crate not found."); 233 | } 234 | 235 | if ( 236 | !crateTokenData.withdrawAuthority.equals( 237 | CRATE_REDEEM_IN_KIND_WITHDRAW_AUTHORITY 238 | ) 239 | ) { 240 | throw new Error("Expected REDEEM_IN_KIND withdraw authority."); 241 | } 242 | 243 | const underlyingMints = underlyingTokens.reduce( 244 | (acc, tok) => ({ ...acc, [tok.address]: tok.mintAccount }), 245 | {} 246 | ); 247 | const ownerATAs = await getOrCreateATAs({ 248 | provider: this.provider, 249 | mints: { 250 | crate: amount.token.mintAccount, 251 | ...underlyingMints, 252 | }, 253 | owner, 254 | }); 255 | 256 | const crateATAs = await getOrCreateATAs({ 257 | provider: this.provider, 258 | mints: underlyingMints, 259 | owner: crateKey, 260 | }); 261 | 262 | const additionalInstructions: TransactionInstruction[] = []; 263 | const remainingAccountKeys = await (async (): Promise => { 264 | if (crateTokenData.withdrawFeeBps !== 0) { 265 | const authorFeeATAs = await getOrCreateATAs({ 266 | provider: this.provider, 267 | mints: underlyingMints, 268 | owner: crateTokenData.authorFeeTo, 269 | }); 270 | additionalInstructions.push(...authorFeeATAs.instructions); 271 | 272 | const protocolFeeATAs = await getOrCreateATAs({ 273 | provider: this.provider, 274 | mints: underlyingMints, 275 | owner: CRATE_FEE_OWNER, 276 | }); 277 | additionalInstructions.push(...protocolFeeATAs.instructions); 278 | 279 | return underlyingTokens.flatMap((token) => { 280 | const crateATA = (crateATAs.accounts as Record)[ 281 | token.address 282 | ]; 283 | const ownerATA = (ownerATAs.accounts as Record)[ 284 | token.address 285 | ]; 286 | const authorFeeATA = ( 287 | authorFeeATAs.accounts as Record 288 | )[token.address]; 289 | const protocolFeeATA = ( 290 | protocolFeeATAs.accounts as Record 291 | )[token.address]; 292 | invariant( 293 | ownerATA && crateATA && authorFeeATA && protocolFeeATA, 294 | "missing ATA" 295 | ); 296 | return [crateATA, ownerATA, authorFeeATA, protocolFeeATA]; 297 | }); 298 | } else { 299 | return underlyingTokens.flatMap((token) => { 300 | const crateATA = (crateATAs.accounts as Record)[ 301 | token.address 302 | ]; 303 | const ownerATA = (ownerATAs.accounts as Record)[ 304 | token.address 305 | ]; 306 | invariant(ownerATA && crateATA, "missing ATA"); 307 | // use owner ATAs for the fees, since there are no fees 308 | return [crateATA, ownerATA, ownerATA, ownerATA]; 309 | }); 310 | } 311 | })(); 312 | const remainingAccounts = remainingAccountKeys.map( 313 | (acc): AccountMeta => ({ 314 | pubkey: acc, 315 | isSigner: false, 316 | isWritable: true, 317 | }) 318 | ); 319 | 320 | const env = new TransactionEnvelope(this.provider, [ 321 | ...additionalInstructions, 322 | this.programs.CrateRedeemInKind.instruction.redeem(amount.toU64(), { 323 | accounts: { 324 | withdrawAuthority: CRATE_REDEEM_IN_KIND_WITHDRAW_AUTHORITY, 325 | crateToken: crateKey, 326 | crateMint: amount.token.mintAccount, 327 | crateSource: ownerATAs.accounts.crate, 328 | owner, 329 | tokenProgram: TOKEN_PROGRAM_ID, 330 | crateTokenProgram: CRATE_ADDRESSES.CrateToken, 331 | }, 332 | remainingAccounts, 333 | }), 334 | ]); 335 | env.instructions.unshift(...ownerATAs.instructions); 336 | return env; 337 | } 338 | } 339 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./constants"; 2 | export * from "./crateToken"; 3 | export * from "./pda"; 4 | export * from "./programs"; 5 | -------------------------------------------------------------------------------- /src/pda.ts: -------------------------------------------------------------------------------- 1 | import { utils } from "@project-serum/anchor"; 2 | import { PublicKey } from "@solana/web3.js"; 3 | 4 | import { CRATE_ADDRESSES } from "./constants"; 5 | 6 | export const generateCrateAddress = ( 7 | mint: PublicKey, 8 | programID: PublicKey = CRATE_ADDRESSES.CrateToken 9 | ): Promise<[PublicKey, number]> => { 10 | return PublicKey.findProgramAddress( 11 | [utils.bytes.utf8.encode("CrateToken"), mint.toBuffer()], 12 | programID 13 | ); 14 | }; 15 | -------------------------------------------------------------------------------- /src/programs/crateRedeemInKind.ts: -------------------------------------------------------------------------------- 1 | import type { AnchorTypes } from "@saberhq/anchor-contrib"; 2 | 3 | import type { CrateRedeemInKindIDL } from "../idls/crate_redeem_in_kind"; 4 | 5 | export * from "../idls/crate_redeem_in_kind"; 6 | 7 | export type CrateRedeemInKindTypes = AnchorTypes; 8 | 9 | export type CrateRedeemInKindProgram = CrateRedeemInKindTypes["Program"]; 10 | -------------------------------------------------------------------------------- /src/programs/crateToken.ts: -------------------------------------------------------------------------------- 1 | import type { AnchorTypes } from "@saberhq/anchor-contrib"; 2 | 3 | import type { CrateTokenIDL } from "../idls/crate_token"; 4 | 5 | export * from "../idls/crate_token"; 6 | 7 | export type CrateTokenTypes = AnchorTypes< 8 | CrateTokenIDL, 9 | { 10 | crateToken: CrateTokenData; 11 | } 12 | >; 13 | 14 | export type CrateTokenData = CrateTokenTypes["Accounts"]["CrateToken"]; 15 | 16 | export type CrateTokenProgram = CrateTokenTypes["Program"]; 17 | -------------------------------------------------------------------------------- /src/programs/index.ts: -------------------------------------------------------------------------------- 1 | export * from "./crateRedeemInKind"; 2 | export * from "./crateToken"; 3 | -------------------------------------------------------------------------------- /tests/crate-token.ts: -------------------------------------------------------------------------------- 1 | import { expectTX } from "@saberhq/chai-solana"; 2 | import { 3 | PendingTransaction, 4 | TransactionEnvelope, 5 | } from "@saberhq/solana-contrib"; 6 | import { 7 | createMintAndVault, 8 | getMintInfo, 9 | getOrCreateATA, 10 | getOrCreateATAs, 11 | getTokenAccount, 12 | SPLToken, 13 | Token, 14 | TOKEN_PROGRAM_ID, 15 | TokenAmount, 16 | u64, 17 | } from "@saberhq/token-utils"; 18 | import type { PublicKey } from "@solana/web3.js"; 19 | import { Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js"; 20 | import { expect } from "chai"; 21 | import invariant from "tiny-invariant"; 22 | 23 | import type { CrateSDK } from "../src"; 24 | import { CRATE_FEE_OWNER } from "../src/constants"; 25 | import { makeSDK } from "./workspace"; 26 | 27 | describe("crate-token", () => { 28 | const sdk = makeSDK(); 29 | const provider = sdk.provider; 30 | 31 | let crateToken: Token; 32 | 33 | let crateKey: PublicKey; 34 | let otherSDK: CrateSDK; 35 | let otherAccount: PublicKey; 36 | 37 | const makeUser = async (): Promise<{ 38 | kp: Keypair; 39 | sdk: CrateSDK; 40 | tokenAccount: PublicKey; 41 | }> => { 42 | const kp = Keypair.generate(); 43 | const newSDK = sdk.withSigner(kp); 44 | await expectTX( 45 | new PendingTransaction( 46 | newSDK.provider.connection, 47 | await newSDK.provider.connection.requestAirdrop( 48 | newSDK.provider.wallet.publicKey, 49 | LAMPORTS_PER_SOL 50 | ) 51 | ) 52 | ).to.be.fulfilled; 53 | 54 | const ata = await getOrCreateATA({ 55 | provider: newSDK.provider, 56 | mint: crateToken.mintAccount, 57 | owner: kp.publicKey, 58 | }); 59 | invariant(ata.instruction, "instruction"); 60 | await expectTX(new TransactionEnvelope(newSDK.provider, [ata.instruction])) 61 | .to.be.fulfilled; 62 | return { kp, sdk: newSDK, tokenAccount: ata.address }; 63 | }; 64 | 65 | beforeEach(async () => { 66 | const mintKP = Keypair.generate(); 67 | crateToken = Token.fromMint(mintKP.publicKey, 6); 68 | 69 | const { crateKey: theCrateKey, tx: createTX } = await sdk.newCrate({ 70 | mintKP, 71 | decimals: crateToken.decimals, 72 | }); 73 | crateKey = theCrateKey; 74 | await expectTX(createTX, "Create Crate Token").to.be.fulfilled; 75 | 76 | await expectTX( 77 | sdk.setWithdrawFee(theCrateKey, 1), 78 | "Set withdraw fee to 0.01%" 79 | ).to.be.fulfilled; 80 | 81 | const other = await makeUser(); 82 | otherSDK = other.sdk; 83 | otherAccount = other.tokenAccount; 84 | }); 85 | 86 | it("can issue and redeem", async () => { 87 | const amount = TokenAmount.parse(crateToken, "1000"); 88 | await expectTX( 89 | await sdk.issue({ 90 | amount, 91 | mintDestination: otherAccount, 92 | }), 93 | "Issue tokens to Other" 94 | ).to.be.fulfilled; 95 | 96 | await expectTX( 97 | await otherSDK.redeem({ 98 | amount, 99 | underlyingTokens: [], 100 | }), 101 | "Redeem" 102 | ).to.be.fulfilled; 103 | }); 104 | 105 | it("stakeholder fractions are correct", async () => { 106 | const userB = await makeUser(); 107 | 108 | // create mints 109 | const [mintA, vaultA] = await createMintAndVault( 110 | provider, 111 | new u64("100000000") 112 | ); 113 | const [mintB, vaultB] = await createMintAndVault( 114 | provider, 115 | new u64("100000000") 116 | ); 117 | 118 | await expectTX( 119 | await sdk.issue({ 120 | amount: TokenAmount.parse(crateToken, "500"), 121 | mintDestination: otherAccount, 122 | }), 123 | "Issue tokens to Other" 124 | ).to.be.fulfilled; 125 | await expectTX( 126 | await sdk.issue({ 127 | amount: TokenAmount.parse(crateToken, "1000"), 128 | mintDestination: userB.tokenAccount, 129 | }), 130 | "Issue tokens to user2" 131 | ).to.be.fulfilled; 132 | 133 | expect( 134 | (await getTokenAccount(provider, otherAccount)).amount 135 | ).to.bignumber.equal("500000000"); 136 | expect( 137 | (await getTokenAccount(provider, userB.tokenAccount)).amount 138 | ).to.bignumber.equal("1000000000"); 139 | expect( 140 | (await getMintInfo(provider, crateToken.mintAccount)).supply 141 | ).to.bignumber.equal("1500000000"); 142 | 143 | // fees 144 | const { instructions: feeIXs } = await getOrCreateATAs({ 145 | provider, 146 | mints: { 147 | mintA, 148 | mintB, 149 | }, 150 | owner: CRATE_FEE_OWNER, 151 | }); 152 | await expectTX(new TransactionEnvelope(provider, feeIXs.slice()), "fees").to 153 | .be.fulfilled; 154 | 155 | // send tokens to the crate 156 | const { 157 | instructions, 158 | accounts: { mintA: crateTokenA, mintB: crateTokenB }, 159 | } = await getOrCreateATAs({ 160 | provider, 161 | mints: { 162 | mintA, 163 | mintB, 164 | }, 165 | owner: crateKey, 166 | }); 167 | await expectTX( 168 | new TransactionEnvelope(provider, [ 169 | ...instructions, 170 | SPLToken.createTransferInstruction( 171 | TOKEN_PROGRAM_ID, 172 | vaultA, 173 | crateTokenA, 174 | sdk.provider.wallet.publicKey, 175 | [], 176 | 9_000000 177 | ), 178 | SPLToken.createTransferInstruction( 179 | TOKEN_PROGRAM_ID, 180 | vaultB, 181 | crateTokenB, 182 | sdk.provider.wallet.publicKey, 183 | [], 184 | 18_000000 185 | ), 186 | ]) 187 | ).to.be.fulfilled; 188 | 189 | const { 190 | accounts: { mintA: userAtokA, mintB: userAtokB }, 191 | instructions: instructionsUserA, 192 | } = await getOrCreateATAs({ 193 | provider, 194 | mints: { 195 | mintA, 196 | mintB, 197 | }, 198 | owner: otherSDK.provider.wallet.publicKey, 199 | }); 200 | const { 201 | accounts: { mintA: userBtokA, mintB: userBtokB }, 202 | instructions: instructionsUserB, 203 | } = await getOrCreateATAs({ 204 | provider, 205 | mints: { 206 | mintA, 207 | mintB, 208 | }, 209 | owner: userB.sdk.provider.wallet.publicKey, 210 | }); 211 | 212 | await expectTX( 213 | new TransactionEnvelope(provider, [ 214 | ...instructionsUserA, 215 | ...instructionsUserB, 216 | ]), 217 | "ATAs" 218 | ).to.be.fulfilled; 219 | 220 | const underlyingTokens = [ 221 | Token.fromMint(mintA, 6), 222 | Token.fromMint(mintB, 6), 223 | ]; 224 | 225 | expect( 226 | (await getMintInfo(provider, crateToken.mintAccount)).supply 227 | ).to.bignumber.equal("1500000000"); 228 | 229 | await expectTX( 230 | await otherSDK.redeem({ 231 | amount: TokenAmount.parse(crateToken, "500"), 232 | underlyingTokens, 233 | }), 234 | "Redeem A" 235 | ).to.be.fulfilled; 236 | 237 | const withFees = (amt: string): string => 238 | new u64(amt).sub(new u64(amt).div(new u64("10000"))).toString(); 239 | 240 | expect( 241 | (await getTokenAccount(provider, userAtokA)).amount 242 | ).to.bignumber.equal(withFees("3000000")); 243 | expect( 244 | (await getTokenAccount(provider, userAtokB)).amount 245 | ).to.bignumber.equal(withFees("6000000")); 246 | expect( 247 | (await getTokenAccount(provider, crateTokenA)).amount 248 | ).to.bignumber.equal("6000000"); 249 | expect( 250 | (await getTokenAccount(provider, crateTokenB)).amount 251 | ).to.bignumber.equal("12000000"); 252 | expect( 253 | (await getMintInfo(provider, crateToken.mintAccount)).supply 254 | ).to.bignumber.equal("1000000000"); 255 | 256 | expect( 257 | (await getTokenAccount(provider, otherAccount)).amount 258 | ).to.bignumber.equal("0"); 259 | expect( 260 | (await getTokenAccount(provider, userB.tokenAccount)).amount 261 | ).to.bignumber.equal("1000000000"); 262 | 263 | await expectTX( 264 | await userB.sdk.redeem({ 265 | amount: TokenAmount.parse(crateToken, "1000"), 266 | underlyingTokens, 267 | }), 268 | "Redeem B" 269 | ).to.be.fulfilled; 270 | 271 | expect( 272 | (await getTokenAccount(provider, userBtokA)).amount 273 | ).to.bignumber.equal(withFees("6000000")); 274 | expect( 275 | (await getTokenAccount(provider, userBtokB)).amount 276 | ).to.bignumber.equal(withFees("12000000")); 277 | expect( 278 | (await getTokenAccount(provider, crateTokenA)).amount 279 | ).to.bignumber.equal("0"); 280 | expect( 281 | (await getTokenAccount(provider, crateTokenB)).amount 282 | ).to.bignumber.equal("0"); 283 | 284 | expect( 285 | (await getTokenAccount(provider, otherAccount)).amount 286 | ).to.bignumber.equal("0"); 287 | expect( 288 | (await getTokenAccount(provider, userB.tokenAccount)).amount 289 | ).to.bignumber.equal("0"); 290 | expect( 291 | (await getMintInfo(provider, crateToken.mintAccount)).supply 292 | ).to.bignumber.equal("0"); 293 | }); 294 | }); 295 | -------------------------------------------------------------------------------- /tests/fixture-key.json: -------------------------------------------------------------------------------- 1 | [ 2 | 148, 243, 45, 212, 135, 246, 72, 26, 73, 140, 56, 126, 177, 224, 224, 170, 3 | 236, 120, 106, 35, 82, 69, 249, 235, 237, 125, 11, 106, 191, 236, 0, 39, 4, 4 | 105, 253, 195, 52, 130, 7, 89, 145, 103, 113, 215, 175, 175, 188, 81, 200, 89, 5 | 116, 202, 162, 197, 253, 236, 129, 122, 206, 63, 253, 182, 227, 207 6 | ] 7 | -------------------------------------------------------------------------------- /tests/workspace.ts: -------------------------------------------------------------------------------- 1 | import * as anchor from "@project-serum/anchor"; 2 | import { AnchorProvider } from "@project-serum/anchor"; 3 | import { chaiSolana } from "@saberhq/chai-solana"; 4 | import { SolanaProvider } from "@saberhq/solana-contrib"; 5 | import chai from "chai"; 6 | 7 | import { CrateSDK } from "../src"; 8 | 9 | chai.use(chaiSolana); 10 | 11 | const anchorProvider = AnchorProvider.env(); 12 | anchor.setProvider(anchorProvider); 13 | 14 | const provider = SolanaProvider.load({ 15 | connection: anchorProvider.connection, 16 | wallet: anchorProvider.wallet, 17 | opts: anchorProvider.opts, 18 | }); 19 | 20 | export const makeSDK = (): CrateSDK => { 21 | return CrateSDK.init(provider); 22 | }; 23 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "noEmit": false, 5 | "module": "CommonJS", 6 | "outDir": "dist/cjs/", 7 | "types": [] 8 | }, 9 | "include": ["src/"], 10 | "exclude": ["**/*.test.ts"] 11 | } 12 | -------------------------------------------------------------------------------- /tsconfig.esm.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.build.json", 3 | "compilerOptions": { 4 | "module": "ESNext", 5 | "outDir": "dist/esm/" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "@saberhq/tsconfig/tsconfig.lib.json", 3 | "compilerOptions": { 4 | "module": "CommonJS", 5 | "noEmit": true, 6 | "types": ["mocha", "node"] 7 | }, 8 | "include": ["src/", "tests/"] 9 | } 10 | --------------------------------------------------------------------------------