mirror of
https://github.com/logos-blockchain/lssa.git
synced 2026-02-18 04:13:07 +00:00
Merge branch 'main' into feat/nixify
# Conflicts: # wallet-ffi/wallet_ffi.h
This commit is contained in:
commit
042854653c
50
.deny.toml
Normal file
50
.deny.toml
Normal file
@ -0,0 +1,50 @@
|
||||
# Config file reference can be found at https://embarkstudios.github.io/cargo-deny/checks/cfg.html.
|
||||
|
||||
[graph]
|
||||
all-features = true
|
||||
exclude-dev = true
|
||||
no-default-features = true
|
||||
|
||||
[advisories]
|
||||
ignore = [
|
||||
{ id = "RUSTSEC-2023-0071", reason = "Marvin Attack: potential key recovery through timing sidechannels" },
|
||||
{ id = "RUSTSEC-2024-0388", reason = "`derivative` is unmaintained; consider using an alternative. Use `cargo tree -p derivative -i > tmp.txt` to check the dependency tree." },
|
||||
{ id = "RUSTSEC-2024-0436", reason = "`paste` has a security vulnerability; consider using an alternative. Use `cargo tree -p paste -i > tmp.txt` to check the dependency tree." },
|
||||
{ id = "RUSTSEC-2025-0055", reason = "`tracing-subscriber` v0.2.25 pulled in by ark-relations v0.4.0 - will be addressed before mainnet" },
|
||||
{ id = "RUSTSEC-2025-0141", reason = "`bincode` is unmaintained but continuing to use it." },
|
||||
]
|
||||
yanked = "deny"
|
||||
unused-ignored-advisory = "deny"
|
||||
|
||||
[bans]
|
||||
allow-wildcard-paths = false
|
||||
multiple-versions = "allow"
|
||||
|
||||
[licenses]
|
||||
allow = [
|
||||
"Apache-2.0 WITH LLVM-exception",
|
||||
"Apache-2.0",
|
||||
"BSD-2-Clause",
|
||||
"BSD-3-Clause",
|
||||
"BSL-1.0",
|
||||
"CC0-1.0",
|
||||
"CDLA-Permissive-2.0",
|
||||
"ISC",
|
||||
"MIT",
|
||||
"MPL-2.0",
|
||||
"Unicode-3.0",
|
||||
"Zlib",
|
||||
]
|
||||
private = { ignore = false }
|
||||
unused-allowed-license = "deny"
|
||||
|
||||
[sources]
|
||||
allow-git = [
|
||||
"https://github.com/EspressoSystems/jellyfish.git",
|
||||
"https://github.com/logos-blockchain/logos-blockchain.git",
|
||||
]
|
||||
unknown-git = "deny"
|
||||
unknown-registry = "deny"
|
||||
|
||||
[sources.allow-org]
|
||||
github = ["logos-co"]
|
||||
19
.github/actions/install-logos-blockchain-circuits/action.yaml
vendored
Normal file
19
.github/actions/install-logos-blockchain-circuits/action.yaml
vendored
Normal file
@ -0,0 +1,19 @@
|
||||
name: Setup Logos Blockchain Circuits
|
||||
|
||||
description: Set up Logos Blockchain Circom Circuits, Rapidsnark prover and Rapidsnark verifier using the setup-logos-blockchain-circuits.sh script.
|
||||
|
||||
inputs:
|
||||
github-token:
|
||||
description: GitHub token for downloading releases
|
||||
required: true
|
||||
|
||||
runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Setup logos-blockchain-circuits
|
||||
shell: bash
|
||||
working-directory: ${{ github.workspace }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ inputs.github-token }}
|
||||
run: |
|
||||
curl -sSL https://raw.githubusercontent.com/logos-blockchain/logos-blockchain/main/scripts/setup-logos-blockchain-circuits.sh | bash
|
||||
25
.github/workflows/ci.yml
vendored
25
.github/workflows/ci.yml
vendored
@ -56,6 +56,19 @@ jobs:
|
||||
- name: Check for unused dependencies
|
||||
run: cargo machete
|
||||
|
||||
deny:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ github.head_ref }}
|
||||
|
||||
- name: Install cargo-deny
|
||||
run: cargo install --locked cargo-deny
|
||||
|
||||
- name: Check licenses and advisories
|
||||
run: cargo deny check
|
||||
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
@ -70,6 +83,10 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/install-risc0
|
||||
|
||||
- uses: ./.github/actions/install-logos-blockchain-circuits
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install active toolchain
|
||||
run: rustup install
|
||||
|
||||
@ -95,6 +112,10 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/install-risc0
|
||||
|
||||
- uses: ./.github/actions/install-logos-blockchain-circuits
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install active toolchain
|
||||
run: rustup install
|
||||
|
||||
@ -119,6 +140,10 @@ jobs:
|
||||
|
||||
- uses: ./.github/actions/install-risc0
|
||||
|
||||
- uses: ./.github/actions/install-logos-blockchain-circuits
|
||||
with:
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Install active toolchain
|
||||
run: rustup install
|
||||
|
||||
|
||||
177
Cargo.lock
generated
177
Cargo.lock
generated
@ -821,17 +821,6 @@ version = "1.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
||||
|
||||
[[package]]
|
||||
name = "atty"
|
||||
version = "0.2.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
|
||||
dependencies = [
|
||||
"hermit-abi 0.1.19",
|
||||
"libc",
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "autocfg"
|
||||
version = "1.5.0"
|
||||
@ -1183,21 +1172,21 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "cbindgen"
|
||||
version = "0.26.0"
|
||||
version = "0.29.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "da6bc11b07529f16944307272d5bd9b22530bc7d05751717c9d416586cedab49"
|
||||
checksum = "befbfd072a8e81c02f8c507aefce431fe5e7d051f83d48a23ffc9b9fe5a11799"
|
||||
dependencies = [
|
||||
"clap 3.2.25",
|
||||
"heck 0.4.1",
|
||||
"indexmap 1.9.3",
|
||||
"clap",
|
||||
"heck",
|
||||
"indexmap 2.12.1",
|
||||
"log",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"syn 1.0.109",
|
||||
"syn 2.0.111",
|
||||
"tempfile",
|
||||
"toml 0.5.11",
|
||||
"toml 0.9.9+spec-1.0.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1296,21 +1285,6 @@ dependencies = [
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "3.2.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ea181bf566f71cb9a5d17a59e1871af638180a18fb0035c92ae62b705207123"
|
||||
dependencies = [
|
||||
"atty",
|
||||
"bitflags 1.3.2",
|
||||
"clap_lex 0.2.4",
|
||||
"indexmap 1.9.3",
|
||||
"strsim 0.10.0",
|
||||
"termcolor",
|
||||
"textwrap",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.5.53"
|
||||
@ -1329,8 +1303,8 @@ checksum = "d76b5d13eaa18c901fd2f7fca939fefe3a0727a953561fefdf3b2922b8569d00"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"clap_lex 0.7.6",
|
||||
"strsim 0.11.1",
|
||||
"clap_lex",
|
||||
"strsim",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -1339,21 +1313,12 @@ version = "4.5.49"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2a0b5487afeab2deb2ff4e03a807ad1a03ac532ff5a2cee5d86884440c7f7671"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.111",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "0.2.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5"
|
||||
dependencies = [
|
||||
"os_str_bytes",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "0.7.6"
|
||||
@ -1632,7 +1597,7 @@ dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim 0.11.1",
|
||||
"strsim",
|
||||
"syn 2.0.111",
|
||||
]
|
||||
|
||||
@ -1646,7 +1611,7 @@ dependencies = [
|
||||
"ident_case",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"strsim 0.11.1",
|
||||
"strsim",
|
||||
"syn 2.0.111",
|
||||
]
|
||||
|
||||
@ -1872,7 +1837,7 @@ version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e92f10a49176cbffacaedabfaa11d51db1ea0f80a83c26e1873b43cd1742c24"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"proc-macro2-diagnostics",
|
||||
]
|
||||
@ -2487,27 +2452,12 @@ dependencies = [
|
||||
"hashbrown 0.15.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.1.19"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.2"
|
||||
@ -2871,7 +2821,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-trait",
|
||||
"clap 4.5.53",
|
||||
"clap",
|
||||
"env_logger",
|
||||
"indexer_service_protocol",
|
||||
"indexer_service_rpc",
|
||||
@ -2969,10 +2919,13 @@ dependencies = [
|
||||
"nssa_core",
|
||||
"sequencer_core",
|
||||
"sequencer_runner",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"token_core",
|
||||
"tokio",
|
||||
"url",
|
||||
"wallet",
|
||||
"wallet-ffi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -2997,7 +2950,7 @@ version = "0.4.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"
|
||||
dependencies = [
|
||||
"hermit-abi 0.5.2",
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@ -3208,7 +3161,7 @@ version = "0.26.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2da3f8ab5ce1bb124b6d082e62dffe997578ceaf0aeb9f3174a214589dc00f07"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"heck",
|
||||
"proc-macro-crate",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
@ -4212,6 +4165,7 @@ dependencies = [
|
||||
"test-case",
|
||||
"test_program_methods",
|
||||
"thiserror 2.0.17",
|
||||
"token_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -4407,12 +4361,6 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
|
||||
|
||||
[[package]]
|
||||
name = "os_str_bytes"
|
||||
version = "6.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e2355d85b9a3786f481747ced0e0ff2ba35213a1f9bd406ed906554d7af805a1"
|
||||
|
||||
[[package]]
|
||||
name = "overwatch"
|
||||
version = "0.1.0"
|
||||
@ -4653,7 +4601,7 @@ dependencies = [
|
||||
name = "program_deployment"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clap 4.5.53",
|
||||
"clap",
|
||||
"nssa",
|
||||
"nssa_core",
|
||||
"tokio",
|
||||
@ -4674,6 +4622,8 @@ dependencies = [
|
||||
"nssa_core",
|
||||
"risc0-zkvm",
|
||||
"serde",
|
||||
"token_core",
|
||||
"token_program",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@ -5672,7 +5622,7 @@ dependencies = [
|
||||
"actix",
|
||||
"actix-web",
|
||||
"anyhow",
|
||||
"clap 4.5.53",
|
||||
"clap",
|
||||
"common",
|
||||
"env_logger",
|
||||
"log",
|
||||
@ -5764,6 +5714,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_spanned"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_urlencoded"
|
||||
version = "0.7.1"
|
||||
@ -5990,12 +5949,6 @@ dependencies = [
|
||||
"thiserror 2.0.17",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
@ -6017,7 +5970,7 @@ version = "0.27.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
|
||||
dependencies = [
|
||||
"heck 0.5.0",
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.111",
|
||||
@ -6162,12 +6115,6 @@ dependencies = [
|
||||
"risc0-zkvm",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "textwrap"
|
||||
version = "0.16.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c13547615a44dc9c452a8a534638acdf07120d4b6847c8178705da06306a3057"
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.69"
|
||||
@ -6273,6 +6220,23 @@ version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
||||
|
||||
[[package]]
|
||||
name = "token_core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"borsh",
|
||||
"nssa_core",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "token_program"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"nssa_core",
|
||||
"token_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.48.0"
|
||||
@ -6358,15 +6322,6 @@ dependencies = [
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.5.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.8.23"
|
||||
@ -6374,11 +6329,26 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_spanned",
|
||||
"serde_spanned 0.6.9",
|
||||
"toml_datetime 0.6.11",
|
||||
"toml_edit 0.22.27",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml"
|
||||
version = "0.9.9+spec-1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eb5238e643fc34a1d5d7e753e1532a91912d74b63b92b3ea51fde8d1b7bc79dd"
|
||||
dependencies = [
|
||||
"indexmap 2.12.1",
|
||||
"serde_core",
|
||||
"serde_spanned 1.0.4",
|
||||
"toml_datetime 0.7.4+spec-1.0.0",
|
||||
"toml_parser",
|
||||
"toml_writer",
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.6.11"
|
||||
@ -6405,7 +6375,7 @@ checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
|
||||
dependencies = [
|
||||
"indexmap 2.12.1",
|
||||
"serde",
|
||||
"serde_spanned",
|
||||
"serde_spanned 0.6.9",
|
||||
"toml_datetime 0.6.11",
|
||||
"toml_write",
|
||||
"winnow",
|
||||
@ -6438,6 +6408,12 @@ version = "0.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
|
||||
|
||||
[[package]]
|
||||
name = "toml_writer"
|
||||
version = "1.0.6+spec-1.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607"
|
||||
|
||||
[[package]]
|
||||
name = "tower"
|
||||
version = "0.4.13"
|
||||
@ -6710,7 +6686,7 @@ dependencies = [
|
||||
"base64",
|
||||
"borsh",
|
||||
"bytemuck",
|
||||
"clap 4.5.53",
|
||||
"clap",
|
||||
"common",
|
||||
"env_logger",
|
||||
"futures",
|
||||
@ -6727,6 +6703,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"token_core",
|
||||
"tokio",
|
||||
"url",
|
||||
]
|
||||
@ -6738,6 +6715,8 @@ dependencies = [
|
||||
"cbindgen",
|
||||
"common",
|
||||
"nssa",
|
||||
"nssa_core",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"wallet",
|
||||
]
|
||||
|
||||
@ -1,3 +1,6 @@
|
||||
[workspace.package]
|
||||
license = "MIT or Apache-2.0"
|
||||
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
members = [
|
||||
@ -16,6 +19,8 @@ members = [
|
||||
"indexer_service",
|
||||
"indexer_service/protocol",
|
||||
"indexer_service/rpc",
|
||||
"programs/token/core",
|
||||
"programs/token",
|
||||
"program_methods",
|
||||
"program_methods/guest",
|
||||
"test_program_methods",
|
||||
@ -42,6 +47,8 @@ indexer_service_protocol = { path = "indexer_service/protocol" }
|
||||
indexer_service_rpc = { path = "indexer_service/rpc" }
|
||||
wallet = { path = "wallet" }
|
||||
wallet-ffi = { path = "wallet-ffi" }
|
||||
token_core = { path = "programs/token/core" }
|
||||
token_program = { path = "programs/token" }
|
||||
test_program_methods = { path = "test_program_methods" }
|
||||
bedrock_client = { path = "bedrock_client" }
|
||||
indexer_core = { path = "indexer_core" }
|
||||
|
||||
109
LEZ testnet v0.1 tutorials/amm.md
Normal file
109
LEZ testnet v0.1 tutorials/amm.md
Normal file
@ -0,0 +1,109 @@
|
||||
# Automated Market Maker (AMM)
|
||||
|
||||
This tutorial covers the AMM program in LEZ. The AMM manages liquidity pools and enables swaps between custom tokens. By the end, you will have practiced:
|
||||
1. Creating a liquidity pool for a token pair.
|
||||
2. Swapping tokens.
|
||||
3. Withdrawing liquidity from the pool.
|
||||
4. Adding liquidity to the pool.
|
||||
|
||||
## 1. Creating a liquidity pool for a token pair
|
||||
|
||||
We start by creating a pool for the tokens created earlier. In return for providing liquidity, you receive liquidity provider (LP) tokens. LP tokens represent your share of the pool and are required to withdraw liquidity later.
|
||||
|
||||
> [!NOTE]
|
||||
> The AMM does not currently charge swap fees or distribute rewards to liquidity providers. LP tokens therefore represent only a proportional share of the pool reserves. Fee support will be added in future versions.
|
||||
|
||||
### a. Create an LP holding account
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf
|
||||
```
|
||||
|
||||
### b. Initialize the pool
|
||||
|
||||
Deposit tokens A and B and specify the account that will receive LP tokens:
|
||||
|
||||
```bash
|
||||
wallet amm new \
|
||||
--user-holding-a Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw \
|
||||
--user-holding-b Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
--user-holding-lp Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf \
|
||||
--balance-a 100 \
|
||||
--balance-b 200
|
||||
```
|
||||
|
||||
> [!Important]
|
||||
> The LP holding account is owned by the token program, so LP tokens are managed using the same token infrastructure as regular tokens.
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf
|
||||
|
||||
# Output:
|
||||
Holding account owned by token program
|
||||
{"account_type":"Token holding","definition_id":"7BeDS3e28MA5Err7gBswmR1fUKdHXqmUpTefNPu3pJ9i","balance":100}
|
||||
```
|
||||
|
||||
> [!Tip]
|
||||
> If you inspect the `user-holding-a` and `user-holding-b` accounts, you will see that 100 and 200 tokens were deducted. Those tokens now reside in the pool and are available for swaps by any user.
|
||||
|
||||
## 2. Swapping
|
||||
|
||||
Use `wallet amm swap` to perform a token swap:
|
||||
|
||||
```bash
|
||||
wallet amm swap \
|
||||
--user-holding-a Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw \
|
||||
--user-holding-b Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
# The amount of tokens to swap
|
||||
--amount-in 5 \
|
||||
# The minimum number of tokens expected in return
|
||||
--min-amount-out 8 \
|
||||
# The definition ID of the token being provided to the swap
|
||||
# In this case, we are swapping from TOKENA to TOKENB, and so this is the definition ID of TOKENA
|
||||
--token-definition 4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7
|
||||
```
|
||||
|
||||
Once executed, 5 tokens are deducted from the Token A holding account and the corresponding amount (computed by the pool’s pricing function) is credited to the Token B holding account.
|
||||
|
||||
## 3. Withdrawing liquidity from the pool
|
||||
|
||||
Liquidity providers can withdraw assets by redeeming (burning) LP tokens. The amount received is proportional to the share of LP tokens redeemed relative to the total LP supply.
|
||||
|
||||
Use `wallet amm remove-liquidity`:
|
||||
|
||||
```bash
|
||||
wallet amm remove-liquidity \
|
||||
--user-holding-a Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw \
|
||||
--user-holding-b Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
--user-holding-lp Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf \
|
||||
--balance-lp 20 \
|
||||
--min-amount-a 1 \
|
||||
--min-amount-b 1
|
||||
```
|
||||
|
||||
> [!Important]
|
||||
> This burns `balance-lp` LP tokens from the user’s LP holding account. In return, the AMM transfers tokens A and B from the pool vaults to the user’s holding accounts, based on current reserves.
|
||||
> The `min-amount-a` and `min-amount-b` parameters set the minimum acceptable outputs. If the computed amounts fall below either threshold, the instruction fails to protect against unfavorable pool changes.
|
||||
|
||||
## 4. Adding liquidity to the pool
|
||||
|
||||
To add liquidity, deposit tokens A and B in the ratio implied by current pool reserves. In return, the AMM mints new LP tokens that represent your proportional share.
|
||||
|
||||
Use `wallet amm add-liquidity`:
|
||||
|
||||
```bash
|
||||
wallet amm add-liquidity \
|
||||
--user-holding-a Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw \
|
||||
--user-holding-b Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
--user-holding-lp Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf \
|
||||
--min-amount-lp 1 \
|
||||
--max-amount-a 10 \
|
||||
--max-amount-b 10
|
||||
```
|
||||
|
||||
> [!Important]
|
||||
> `max-amount-a` and `max-amount-b` cap how many tokens A and B can be taken from the user’s accounts. The AMM computes the required amounts based on the pool’s reserve ratio.
|
||||
> `min-amount-lp` sets the minimum LP tokens to mint. If the computed LP amount falls below this threshold, the instruction fails.
|
||||
159
LEZ testnet v0.1 tutorials/custom-tokens.md
Normal file
159
LEZ testnet v0.1 tutorials/custom-tokens.md
Normal file
@ -0,0 +1,159 @@
|
||||
This tutorial focuses on custom tokens using the Token program. As of now, you have used the authenticated-transfers program for native tokens. The Token program is for creating and managing custom tokens. By the end, you will have practiced:
|
||||
1. Creating new tokens.
|
||||
2. Transferring custom tokens.
|
||||
|
||||
> [!Important]
|
||||
> The Token program is a single program that creates and manages all tokens, so you do not deploy a new program for each token.
|
||||
> Token program accounts fall into two types:
|
||||
> - Token definition accounts: store token metadata such as name and total supply. This account is the token’s identifier.
|
||||
> - Token holding accounts: store balances and the definition ID they belong to.
|
||||
|
||||
The CLI provides commands to execute the Token program. Run `wallet token` to see the options:
|
||||
|
||||
```bash
|
||||
Commands:
|
||||
new Produce a new token
|
||||
send Send tokens from one account to another with variable privacy
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
```
|
||||
|
||||
## 1. Creating new tokens
|
||||
|
||||
Use `wallet token new` to execute the `New` function of the Token program. The command expects:
|
||||
- A token name.
|
||||
- A total supply.
|
||||
- Two uninitialized accounts:
|
||||
- One for the token definition account.
|
||||
- One for the token holding account that receives the initial supply.
|
||||
|
||||
### a. Public definition account and public supply account
|
||||
|
||||
1. Create two new public accounts:
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7
|
||||
```
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw
|
||||
```
|
||||
|
||||
2. Create the token (Token A):
|
||||
|
||||
```bash
|
||||
wallet token new \
|
||||
--name TOKENA \
|
||||
--total-supply 1337 \
|
||||
--definition-account-id Public/4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7 \
|
||||
--supply-account-id Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw
|
||||
```
|
||||
|
||||
3. Inspect the initialized accounts:
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7
|
||||
|
||||
# Output:
|
||||
Definition account owned by token program
|
||||
{"account_type":"Token definition","name":"TOKENA","total_supply":1337}
|
||||
```
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw
|
||||
|
||||
# Output:
|
||||
Holding account owned by token program
|
||||
{"account_type":"Token holding","definition_id":"4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7","balance":1337}
|
||||
```
|
||||
|
||||
### b. Public definition account and private supply account
|
||||
|
||||
1. Create fresh accounts for this example:
|
||||
|
||||
> [!Important]
|
||||
> You cannot reuse the accounts from the previous example. Create new ones here.
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii
|
||||
```
|
||||
|
||||
```bash
|
||||
wallet account new private
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Private/HMRHZdPw4pbyPVZHNGrV6K5AA95wACFsHTRST84fr3CF
|
||||
With npk 6a2dfe433cf28e525aa0196d719be3c16146f7ee358ca39595323f94fde38f93
|
||||
With ipk 03d59abf4bee974cc12ddb44641c19f0b5441fef39191f047c988c29a77252a577
|
||||
```
|
||||
|
||||
2. Create the token (Token B):
|
||||
|
||||
```bash
|
||||
wallet token new \
|
||||
--name TOKENB \
|
||||
--total-supply 7331 \
|
||||
--definition-account-id Public/GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii \
|
||||
--supply-account-id Private/HMRHZdPw4pbyPVZHNGrV6K5AA95wACFsHTRST84fr3CF
|
||||
```
|
||||
|
||||
3. Inspect the accounts:
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii
|
||||
|
||||
# Output:
|
||||
Definition account owned by token program
|
||||
{"account_type":"Token definition","name":"TOKENB","total_supply":7331}
|
||||
```
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Private/HMRHZdPw4pbyPVZHNGrV6K5AA95wACFsHTRST84fr3CF
|
||||
|
||||
# Output:
|
||||
Holding account owned by token program
|
||||
{"account_type":"Token holding","definition_id":"GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii","balance":7331}
|
||||
```
|
||||
|
||||
> [!Important]
|
||||
> As a private account, the supply account is visible only in your local wallet storage.
|
||||
|
||||
## 2. Custom token transfers
|
||||
|
||||
The Token program can move balances between token holding accounts. If the recipient account is uninitialized, the token program will automatically claim it. Use `wallet token send` to execute a transfer.
|
||||
|
||||
### a. Create a recipient account
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6
|
||||
```
|
||||
|
||||
### b. Send 1000 TOKENB to the recipient
|
||||
|
||||
```bash
|
||||
wallet token send \
|
||||
--from Private/HMRHZdPw4pbyPVZHNGrV6K5AA95wACFsHTRST84fr3CF \
|
||||
--to Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
--amount 1000
|
||||
```
|
||||
|
||||
### c. Inspect the recipient account
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6
|
||||
|
||||
# Output:
|
||||
Holding account owned by token program
|
||||
{"account_type":"Token holding","definition_id":"GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii","balance":1000}
|
||||
```
|
||||
250
LEZ testnet v0.1 tutorials/token-transfer.md
Normal file
250
LEZ testnet v0.1 tutorials/token-transfer.md
Normal file
@ -0,0 +1,250 @@
|
||||
This tutorial walks through native token transfers between public and private accounts using the Authenticated-Transfers program. You will create and initialize accounts, fund them with the Pinata program, and run transfers across different privacy combinations. By the end, you will have practiced:
|
||||
1. Public account creation and initialization.
|
||||
2. Account funding through the Pinata program.
|
||||
3. Native token transfers between public accounts.
|
||||
4. Private account creation.
|
||||
5. Native token transfer from a public account to a private account.
|
||||
6. Native token transfer from a public account to a private account owned by someone else.
|
||||
|
||||
---
|
||||
|
||||
The CLI provides commands to manage accounts. Run `wallet account` to see the options available:
|
||||
```bash
|
||||
Commands:
|
||||
get Get account data
|
||||
new Produce new public or private account
|
||||
sync-private Sync private accounts
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
```
|
||||
|
||||
## 1. Public account creation and initialization
|
||||
> [!Important]
|
||||
> Public accounts live on-chain and are identified by a 32-byte Account ID. Running `wallet account new public` generates a fresh keypair for the signature scheme used in LEZ.
|
||||
> The account ID is derived from the public key, and the private key signs transactions and authorizes program executions.
|
||||
> The CLI can create both public and private accounts.
|
||||
|
||||
### a. New public account creation
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
```
|
||||
> [!Tip]
|
||||
> Save this account ID. You will use it in later commands.
|
||||
|
||||
### b. Account initialization
|
||||
|
||||
To query the account’s current status, run:
|
||||
|
||||
```bash
|
||||
# Replace the id with yours
|
||||
wallet account get --account-id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
|
||||
# Output:
|
||||
Account is Uninitialized
|
||||
```
|
||||
|
||||
In this example, we initialize the account for the authenticated-transfer program, which manages native token transfers and enforces authenticated debits.
|
||||
|
||||
1. Initialize the account:
|
||||
```bash
|
||||
# This command submits a public transaction executing the `init` function of the
|
||||
# authenticated-transfer program. The wallet polls the sequencer until the
|
||||
# transaction is included in a block, which may take several seconds.
|
||||
wallet auth-transfer init --account-id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
```
|
||||
|
||||
2. Check the updated account status:
|
||||
```bash
|
||||
wallet account get --account-id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated-transfer program
|
||||
{"balance":0}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> New accounts start uninitialized, meaning no program owns them yet. Any program may claim an uninitialized account; once claimed, that program owns it.
|
||||
> Owned accounts can only be modified through executions of the owning program. The only exception is native-token credits: any program may credit native tokens to any account.
|
||||
> Debiting native tokens must always be performed by the owning program.
|
||||
|
||||
## 2. Account funding through the Piñata program
|
||||
Now that the account is initialized under the authenticated-tansfer program, fund it using the testnet Piñata program.
|
||||
|
||||
```bash
|
||||
# Replace with your id
|
||||
wallet pinata claim --to Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
```
|
||||
|
||||
After the claim succeeds, the account is funded:
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated-transfer program
|
||||
{"balance":150}
|
||||
```
|
||||
|
||||
## 3. Native token transfers between public accounts
|
||||
LEZ includes a program for managing native tokens. Run `wallet auth-transfer` to see the available commands:
|
||||
```bash
|
||||
Commands:
|
||||
init Initialize account under the authenticated-transfer program
|
||||
send Send native tokens from one account to another with variable privacy
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
```
|
||||
|
||||
We already used `init`. Now use `send` to execute a transfer.
|
||||
|
||||
### a. Create a recipient account
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The new account is uninitialized. The authenticated-transfer program will claim any uninitialized account used in a transfer, so manual initialization isn’t required.
|
||||
|
||||
### b. Send 37 tokens to the new account
|
||||
```bash
|
||||
wallet auth-transfer send \
|
||||
--from Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ \
|
||||
--to Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS \
|
||||
--amount 37
|
||||
```
|
||||
|
||||
### c. Check both accounts
|
||||
```bash
|
||||
# Sender account (use your sender ID)
|
||||
wallet account get --account-id Public/HrA8TVjBS8UVf9akV7LRhyh6k4c7F6PS7PvqgtPmKAT8
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated-transfer program
|
||||
{"balance":113}
|
||||
```
|
||||
|
||||
```bash
|
||||
# Recipient account
|
||||
wallet account get --account-id Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated-transfer program
|
||||
{"balance":37}
|
||||
```
|
||||
|
||||
## 4. Private account creation
|
||||
|
||||
> [!Important]
|
||||
> Private accounts are structurally identical to public accounts, but their values are stored off-chain. On-chain, only a 32-byte commitment is recorded.
|
||||
> Transactions include encrypted private values so the owner can recover them, and the decryption keys are never shared.
|
||||
> Private accounts use two keypairs: nullifier keys for privacy-preserving executions and viewing keys for encrypting and decrypting values.
|
||||
> The private account ID is derived from the nullifier public key.
|
||||
> Private accounts can be initialized by anyone, but once initialized they can only be modified by the owner’s keys.
|
||||
> Updates include a new commitment and a nullifier for the old state, which prevents linkage between versions.
|
||||
|
||||
### a. Create a private account
|
||||
|
||||
```bash
|
||||
wallet account new private
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Private/HacPU3hakLYzWtSqUPw6TUr8fqoMieVWovsUR6sJf7cL
|
||||
With npk e6366f79d026c8bd64ae6b3d601f0506832ec682ab54897f205fffe64ec0d951
|
||||
With ipk 02ddc96d0eb56e00ce14994cfdaec5ae1f76244180a919545983156e3519940a17
|
||||
```
|
||||
|
||||
> [!Tip]
|
||||
> Focus on the account ID for now. The `npk` and `ipk` values are stored locally and used to build privacy-preserving transactions. The private account ID is derived from `npk`.
|
||||
|
||||
Just like public accounts, new private accounts start out uninitialized:
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Private/HacPU3hakLYzWtSqUPw6TUr8fqoMieVWovsUR6sJf7cL
|
||||
|
||||
# Output:
|
||||
Account is Uninitialized
|
||||
```
|
||||
|
||||
> [!Important]
|
||||
> Private accounts are never visible to the network. They exist only in your local wallet storage.
|
||||
|
||||
## 5. Native token transfer from a public account to a private account
|
||||
|
||||
> [!Important]
|
||||
> Sending tokens to an uninitialized private account causes the authenticated-transfer program to claim it, just like with public accounts. Program logic is the same regardless of account type.
|
||||
|
||||
### a. Send 17 tokens to the private account
|
||||
|
||||
> [!Note]
|
||||
> The syntax matches public-to-public transfers, but the recipient is a private ID. This runs locally, generates a proof, and submits it to the sequencer. It may take 30 seconds to 4 minutes.
|
||||
|
||||
```bash
|
||||
wallet auth-transfer send \
|
||||
--from Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS \
|
||||
--to Private/HacPU3hakLYzWtSqUPw6TUr8fqoMieVWovsUR6sJf7cL \
|
||||
--amount 17
|
||||
```
|
||||
|
||||
### b. Check both accounts
|
||||
|
||||
```bash
|
||||
# Public sender account
|
||||
wallet account get --account-id Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated-transfer program
|
||||
{"balance":20}
|
||||
```
|
||||
|
||||
```bash
|
||||
# Private recipient account
|
||||
wallet account get --account-id Private/HacPU3hakLYzWtSqUPw6TUr8fqoMieVWovsUR6sJf7cL
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated-transfer program
|
||||
{"balance":17}
|
||||
```
|
||||
|
||||
> [!Note]
|
||||
> The last command does not query the network. It works offline because private account data is stored locally. Other users cannot read your private balances.
|
||||
|
||||
> [!Caution]
|
||||
> Private accounts can only be modified by their owner’s keys. The exception is initialization: any user can initialize an uninitialized private account. This enables transfers to a private account owned by someone else, as long as that account is uninitialized.
|
||||
|
||||
## 6. Native token transfer from a public account to a private account owned by someone else
|
||||
|
||||
> [!Important]
|
||||
> We’ll simulate transferring to someone else by creating a new private account we own and treating it as if it belonged to another user.
|
||||
|
||||
### a. Create a new uninitialized private account
|
||||
|
||||
```bash
|
||||
wallet account new private
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Private/AukXPRBmrYVqoqEW2HTs7N3hvTn3qdNFDcxDHVr5hMm5
|
||||
With npk 0c95ebc4b3830f53da77bb0b80a276a776cdcf6410932acc718dcdb3f788a00e
|
||||
With ipk 039fd12a3674a880d3e917804129141e4170d419d1f9e28a3dcf979c1f2369cb72
|
||||
```
|
||||
|
||||
> [!Tip]
|
||||
> Ignore the private account ID here and use the `npk` and `ipk` values to send to a foreign private account.
|
||||
|
||||
```bash
|
||||
wallet auth-transfer send \
|
||||
--from Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS \
|
||||
--to-npk 0c95ebc4b3830f53da77bb0b80a276a776cdcf6410932acc718dcdb3f788a00e \
|
||||
--to-ipk 039fd12a3674a880d3e917804129141e4170d419d1f9e28a3dcf979c1f2369cb72 \
|
||||
--amount 3
|
||||
```
|
||||
|
||||
> [!Warning]
|
||||
> This command creates a privacy-preserving transaction, which may take a few minutes. The updated values are encrypted and included in the transaction.
|
||||
> Once accepted, the recipient must run `wallet account sync-private` to scan the chain for their encrypted updates and refresh local state.
|
||||
|
||||
> [!Note]
|
||||
> You have seen transfers between two public accounts and from a public sender to a private recipient. Transfers from a private sender, whether to a public account or to another private account, follow the same pattern.
|
||||
26
LEZ testnet v0.1 tutorials/wallet-setup.md
Normal file
26
LEZ testnet v0.1 tutorials/wallet-setup.md
Normal file
@ -0,0 +1,26 @@
|
||||
This repository includes a CLI for interacting with the Logos Blockchain. To install it, run the following command from the root of the repository:
|
||||
|
||||
```bash
|
||||
cargo install --path wallet --force
|
||||
```
|
||||
|
||||
To check that everythin is working, run `wallet help`.
|
||||
|
||||
## Available Wallet Commands
|
||||
|
||||
| Command | Description |
|
||||
|------------------------|-------------------------------------------------------------|
|
||||
| `wallet auth-transfer` | Authenticated transfer (init, send) |
|
||||
| `wallet chain-info` | Chain info queries (current-block-id, block, transaction) |
|
||||
| `wallet account` | Account management (get, list, new, sync-private) |
|
||||
| `wallet pinata` | Piñata faucet (claim) |
|
||||
| `wallet token` | Token operations (new, send) |
|
||||
| `wallet amm` | AMM operations (new, swap, add-liquidity, remove-liquidity) |
|
||||
| `wallet check-health` | Health checks that the wallet is connected to the node |
|
||||
| `wallet config` | Config Setup (get, set) |
|
||||
| `wallet restore-keys ` | Keys restore from a given password at given `depth` |
|
||||
| `wallet deploy-program`| Program deployment |
|
||||
| `wallet help` | Help |
|
||||
|
||||
Some completion scripts exists, see the [completions](./completions/README.md) folder.
|
||||
|
||||
740
README.md
740
README.md
@ -1,70 +1,75 @@
|
||||
# Nescience
|
||||
# Logos Execution Zone (LEZ)
|
||||
|
||||
Logos Execution Zone (LEZ) is a programmable blockchain that cleanly separates public and private state while keeping them fully interoperable. Developers can build apps that operate across transparent and privacy-preserving accounts without changing their logic. Privacy is enforced by the protocol itself through zero-knowledge proofs (ZKPs), so it is always available and automatic.
|
||||
|
||||
Nescience State Separation Architecture (NSSA) is a programmable blockchain system that introduces a clean separation between public and private states, while keeping them fully interoperable. It lets developers build apps that can operate across both transparent and privacy-preserving accounts. Privacy is handled automatically by the protocol through zero-knowledge proofs (ZKPs). The result is a programmable blockchain where privacy comes built-in.
|
||||
|
||||
## Background
|
||||
|
||||
Typically, public blockchains maintain a fully transparent state, where the mapping from account IDs to account values is entirely visible. In NSSA, we introduce a parallel *private state*, a new layer of accounts that coexists with the public one. The public and private states can be viewed as a partition of the account ID space: accounts with public IDs are openly visible, while private accounts are accessible only to holders of the corresponding viewing keys. Consistency across both states is enforced through zero-knowledge proofs (ZKPs).
|
||||
These features are provided by the Logos Execution Environment (LEE). Traditional public blockchains expose a fully transparent state: the mapping from account IDs to account values is entirely visible. LEE introduces a parallel *private state* that coexists with the public one. Together, public and private accounts form a partition of the account ID space: public IDs are visible on-chain, while private accounts are accessible only to holders of the corresponding viewing keys. Consistency across both states is enforced by ZKPs.
|
||||
|
||||
Public accounts are stored on-chain as a visible map from IDs to account states, and their values are updated in place. Private accounts are never stored on-chain in raw form. Each update produces a new commitment that binds the current value while keeping it hidden. Previous commitments remain on-chain, but a nullifier set marks old versions as spent, ensuring that only the most recent private state can be used in execution.
|
||||
|
||||
Public accounts are represented on-chain as a visible map from IDs to account states and are modified in-place when their values change. Private accounts, by contrast, are never stored in raw form on-chain. Each update creates a new commitment, which cryptographically binds the current value of the account while preserving privacy. Commitments of previous valid versions remain on-chain, but a nullifier set is maintained to mark old versions as spent, ensuring that only the most up-to-date version of each private account can be used in any execution.
|
||||
|
||||
### Programmability and selective privacy
|
||||
|
||||
Our goal is to enable full programmability within this hybrid model, matching the flexibility and composability of public blockchains. Developers write and deploy programs in NSSA just as they would on any other blockchain. Privacy, along with the ability to execute programs involving any combination of public and private accounts, is handled entirely at the protocol level and available out of the box for all programs. From the program’s perspective, all accounts are indistinguishable. This abstraction allows developers to focus purely on business logic, while the system transparently enforces privacy and consistency guarantees.
|
||||
LEZ aims to deliver full programmability in a hybrid public/private model, with the same flexibility and composability as public blockchains. Developers write and deploy programs in LEZ just as they would elsewhere. The protocol automatically supports executions that involve any combination of public and private accounts. From the program’s perspective, all accounts look the same, and privacy is enforced transparently. This lets developers focus on business logic while the system guarantees privacy and correctness.
|
||||
|
||||
To the best of our knowledge, this approach is unique to Nescience. Other programmable blockchains with a focus on privacy typically adopt a developer-driven model for private execution, meaning that dApp logic must explicitly handle private inputs correctly. In contrast, Nescience handles privacy at the protocol level, so developers do not need to modify their programs—private and public accounts are treated uniformly, and privacy-preserving execution is available out of the box.
|
||||
To our knowledge, this design is unique to LEZ. Other privacy-focused programmable blockchains often require developers to explicitly handle private inputs inside their app logic. In LEZ, privacy is protocol-level: programs do not change, accounts are treated uniformly, and private execution works out of the box.
|
||||
|
||||
### Example: creating and transferring tokens across states
|
||||
---
|
||||
|
||||
## Example: Creating and transferring tokens across states
|
||||
|
||||
1. Token creation (public execution)
|
||||
- Alice submits a transaction that executes the token program `New` function on-chain.
|
||||
- A new public token definition account is created.
|
||||
- The minted tokens are recorded on-chain in Alice’s public account.
|
||||
|
||||
1. Token creation (public execution):
|
||||
- Alice submits a transaction to execute the token program `New` function on-chain.
|
||||
- A new public token account is created, representing the token.
|
||||
- The minted tokens are recorded on-chain and fully visible on Alice's public account.
|
||||
2. Transfer from public to private (local / privacy-preserving execution)
|
||||
- Alice executes the token program `Transfer` function locally, specifying a Bob’s private account as recipient.
|
||||
- Alice runs the token program `Transfer` function locally, sending to Bob’s private account.
|
||||
- A ZKP of correct execution is generated.
|
||||
- The proof is submitted to the blockchain, and validator nodes verify it.
|
||||
- Alice's public account balance is modified accordingly.
|
||||
- Bob’s private account and balance remain hidden, while the transfer is provably valid.
|
||||
- The proof is submitted to the blockchain and verified by validators.
|
||||
- Alice’s public balance is updated on-chain.
|
||||
- Bob’s private balance remains hidden, while the transfer is provably correct.
|
||||
|
||||
3. Transferring private to public (local / privacy-preserving execution)
|
||||
- Bob executes the token program `Transfer` function locally, specifying a Charlie’s public account as recipient.
|
||||
- Bob executes the token program `Transfer` function locally, sending to Charlie’s public account.
|
||||
- A ZKP of correct execution is generated.
|
||||
- Bob’s private account and balance still remain hidden.
|
||||
- Charlie's public account is modified with the new tokens added.
|
||||
4. Transferring public to public (public execution):
|
||||
- Alice submits a transaction to execute the token program `Transfer` function on-chain, specifying Charlie's public account as recipient.
|
||||
- The execution is handled on-chain without ZKPs involved.
|
||||
- Alice's and Charlie's accounts are modified according to the transaction.
|
||||
- Bob’s private balance stays hidden.
|
||||
- Charlie’s public account is updated on-chain.
|
||||
|
||||
4. Transfer from public to public (public execution)
|
||||
- Alice submits an on-chain transaction to run `Transfer`, sending to Charlie’s public account.
|
||||
- Execution is handled fully on-chain without ZKPs.
|
||||
- Alice’s and Charlie’s public balances are updated.
|
||||
|
||||
|
||||
#### Key points:
|
||||
- The same token program is used in all executions.
|
||||
- The difference lies in execution mode: public executions update visible accounts on-chain, while private executions rely on ZKPs.
|
||||
- Validators only need to verify proofs for privacy-preserving transactions, keeping processing efficient.
|
||||
### Key points:
|
||||
- The same token program is used in every execution.
|
||||
- The only difference is execution mode: public execution updates visible state on-chain, while private execution relies on ZKPs.
|
||||
- Validators verify proofs only for privacy-preserving transactions, keeping processing efficient.
|
||||
|
||||
### The account’s model
|
||||
---
|
||||
|
||||
To achieve both state separation and full programmability, NSSA adopts a stateless program model. Programs do not hold internal state. Instead, all persistent data resides in accounts explicitly passed to the program during execution. This design enables fine-grained control over access and visibility while maintaining composability across public and private states.
|
||||
## The account’s model
|
||||
|
||||
To achieve both state separation and full programmability, LEZ uses a stateless program model. Programs hold no internal state. All persistent data is stored in accounts passed explicitly into each execution. This enables precise access control and visibility while preserving composability across public and private states.
|
||||
|
||||
### Execution types
|
||||
|
||||
Execution is divided into two fundamentally distinct types based on how they are processed: public execution, which is executed transparently on-chain, and private execution, which occurs off-chain. For private execution, the blockchain relies on ZKPs to verify the correctness of execution and ensure that all system invariants are preserved.
|
||||
LEZ supports two execution types:
|
||||
- Public execution runs transparently on-chain.
|
||||
- Private execution runs off-chain and is verified on-chain with ZKPs.
|
||||
|
||||
Both public and private executions of the same program are enforced to use the same Risc0 VM bytecode. For public transactions, programs are executed directly on-chain like any standard RISC-V VM execution, without generating or verifying proofs. For privacy-preserving transactions, users generate Risc0 ZKPs of correct execution, and validator nodes only verify these proofs rather than re-executing the program. This design ensures that from a validator’s perspective, public transactions are processed as quickly as any RISC-V–based VM, while verification of ZKPs keeps privacy-preserving transactions efficient as well. Additionally, the system naturally supports parallel execution similar to Solana, further increasing throughput. The main computational bottleneck for privacy-preserving transactions lies on the user side, in generating zk proofs.
|
||||
Both public and private executions use the same Risc0 VM bytecode. Public transactions are executed directly on-chain like any standard RISC-V VM call, without proof generation. Private transactions are executed locally by users, who generate Risc0 proofs that validators verify instead of re-executing the program.
|
||||
|
||||
### Resources
|
||||
- [IFT Research call](https://forum.vac.dev/t/ift-research-call-september-10th-2025-updates-on-the-development-of-nescience/566)
|
||||
- [NSSA v0.2 specs](https://www.notion.so/NSSA-v0-2-specifications-2848f96fb65c800c9818e6f66d9be8f2)
|
||||
- [Choice of VM/zkVM](https://www.notion.so/Conclusion-on-the-chosen-VM-and-zkVM-for-NSSA-2318f96fb65c806a810ed1300f56992d)
|
||||
- [NSSA vs other privacy projects](https://www.notion.so/Privacy-projects-comparison-2688f96fb65c8096b694ecf7e4deca30)
|
||||
- [NSSA state model](https://www.notion.so/Public-state-model-decision-2388f96fb65c80758b20c76de07b1fcc)
|
||||
- [NSSA sequencer specs](https://www.notion.so/Sequencer-specs-2428f96fb65c802da2bfea7b0b214ecb)
|
||||
- [NSSA sequencer code](https://www.notion.so/NSSA-sequencer-pseudocode-2508f96fb65c805e8859e047dffd6785)
|
||||
- [NSSA Token program desing](https://www.notion.so/Token-program-design-2538f96fb65c80a1b4bdc4fd9dd162d7)
|
||||
- [NSSA cross program calls](https://www.notion.so/NSSA-cross-program-calls-Tail-call-model-proposal-extended-version-2838f96fb65c8096b3a2d390444193b6)
|
||||
This design keeps public transactions as fast as any RISC-V–based VM and makes private transactions efficient for validators. It also supports parallel execution similar to Solana, improving throughput. The main computational cost for privacy-preserving transactions is on the user side, where ZK proofs are generated.
|
||||
|
||||
---
|
||||
---
|
||||
|
||||
# Install dependencies
|
||||
Install build dependencies
|
||||
### Install build dependencies
|
||||
|
||||
- On Linux
|
||||
Ubuntu / Debian
|
||||
@ -72,7 +77,7 @@ Ubuntu / Debian
|
||||
apt install build-essential clang libclang-dev libssl-dev pkg-config
|
||||
```
|
||||
|
||||
Fedora
|
||||
- On Fedora
|
||||
```sh
|
||||
sudo dnf install clang clang-devel openssl-devel pkgconf
|
||||
```
|
||||
@ -83,25 +88,26 @@ xcode-select --install
|
||||
brew install pkg-config openssl
|
||||
```
|
||||
|
||||
Install Rust
|
||||
### Install Rust
|
||||
|
||||
```sh
|
||||
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
|
||||
```
|
||||
|
||||
Install Risc0
|
||||
### Install Risc0
|
||||
|
||||
```sh
|
||||
curl -L https://risczero.com/install | bash
|
||||
```
|
||||
|
||||
Then restart your shell and run
|
||||
### Then restart your shell and run
|
||||
```sh
|
||||
rzup install
|
||||
```
|
||||
|
||||
# Run tests
|
||||
|
||||
The NSSA repository includes both unit and integration test suites.
|
||||
The LEZ repository includes both unit and integration test suites.
|
||||
|
||||
### Unit tests
|
||||
|
||||
@ -119,635 +125,23 @@ cd integration_tests
|
||||
RUST_LOG=info RISC0_DEV_MODE=1 cargo run $(pwd)/configs/debug all
|
||||
```
|
||||
|
||||
# Run the sequencer
|
||||
# Run the sequencer and node
|
||||
|
||||
The sequencer can be run locally:
|
||||
The sequencer and node can be run locally:
|
||||
|
||||
```bash
|
||||
cd sequencer_runner
|
||||
RUST_LOG=info cargo run --release configs/debug
|
||||
```
|
||||
1. On one terminal go to the `logos-blockchain/logos-blockchain` repo and run a local logos blockchain node:
|
||||
- `git checkout master; git pull`
|
||||
- `cargo clean`
|
||||
- `rm ~/.logos-blockchain-circuits`
|
||||
- `./scripts/setup-logos-blockchain-circuits.sh`
|
||||
- `cargo build --all-features`
|
||||
- `./target/debug/logos-blockchain-node nodes/node/config-one-node.yaml`
|
||||
|
||||
If everything went well you should see an output similar to this:
|
||||
```bash
|
||||
[2025-11-13T19:50:29Z INFO sequencer_runner] Sequencer core set up
|
||||
[2025-11-13T19:50:29Z INFO network] Starting http server at 0.0.0.0:3040
|
||||
[2025-11-13T19:50:29Z INFO actix_server::builder] starting 8 workers
|
||||
[2025-11-13T19:50:29Z INFO sequencer_runner] HTTP server started
|
||||
[2025-11-13T19:50:29Z INFO sequencer_runner] Starting main sequencer loop
|
||||
[2025-11-13T19:50:29Z INFO actix_server::server] Tokio runtime found; starting in existing Tokio runtime
|
||||
[2025-11-13T19:50:29Z INFO actix_server::server] starting service: "actix-web-service-0.0.0.0:3040", workers: 8, listening on: 0.0.0.0:3040
|
||||
[2025-11-13T19:50:39Z INFO sequencer_runner] Collecting transactions from mempool, block creation
|
||||
[2025-11-13T19:50:39Z INFO sequencer_core] Created block with 0 transactions in 0 seconds
|
||||
[2025-11-13T19:50:39Z INFO sequencer_runner] Block with id 2 created
|
||||
[2025-11-13T19:50:39Z INFO sequencer_runner] Waiting for new transactions
|
||||
```
|
||||
2. On another terminal go to the `logos-blockchain/lssa` repo and run indexer service:
|
||||
- `git checkout schouhy/full-bedrock-integration`
|
||||
- `RUST_LOG=info cargo run --release -p indexer_service $(pwd)/integration_tests/configs/indexer/indexer_config.json`
|
||||
|
||||
# Try the Wallet CLI
|
||||
|
||||
## Install
|
||||
|
||||
This repository includes a CLI for interacting with the Nescience sequencer. To install it, run the following command from the root of the repository:
|
||||
|
||||
```bash
|
||||
cargo install --path wallet --force
|
||||
```
|
||||
|
||||
Run `wallet help` to check everything went well.
|
||||
|
||||
Some completion scripts exists, see the [completions](./completions/README.md) folder.
|
||||
|
||||
## Tutorial
|
||||
|
||||
This tutorial walks you through creating accounts and executing NSSA programs in both public and private contexts.
|
||||
|
||||
> [!NOTE]
|
||||
> The NSSA state is split into two separate but interconnected components: the public state and the private state.
|
||||
> The public state is an on-chain, publicly visible record of accounts indexed by their Account IDs
|
||||
> The private state mirrors this, but the actual account values are stored locally by each account owner. On-chain, only a hidden commitment to each private account state is recorded. This allows the chain to enforce freshness (i.e., prevent the reuse of stale private states) while preserving privacy and unlinkability across executions and private accounts.
|
||||
>
|
||||
> Every piece of state in NSSA is stored in an account (public or private). Accounts are either uninitialized or are owned by a program, and programs can only modify the accounts they own.
|
||||
>
|
||||
> In NSSA, accounts can only be modified through program execution. A program is the sole mechanism that can change an account’s value.
|
||||
> Programs run publicly when all involved accounts are public, and privately when at least one private account participates.
|
||||
|
||||
### Health-check
|
||||
|
||||
Verify that the node is running and that the wallet can connect to it:
|
||||
|
||||
```bash
|
||||
wallet check-health
|
||||
```
|
||||
|
||||
You should see `✅ All looks good!`.
|
||||
|
||||
### The commands
|
||||
|
||||
The wallet provides several commands to interact with the node and query state. To see the full list, run `wallet help`:
|
||||
|
||||
```bash
|
||||
Commands:
|
||||
auth-transfer Authenticated transfer subcommand
|
||||
chain-info Generic chain info subcommand
|
||||
account Account view and sync subcommand
|
||||
pinata Pinata program interaction subcommand
|
||||
token Token program interaction subcommand
|
||||
amm AMM program interaction subcommand
|
||||
check-health Check the wallet can connect to the node and builtin local programs match the remote versions
|
||||
```
|
||||
|
||||
### Accounts
|
||||
|
||||
> [!NOTE]
|
||||
> Accounts are the basic unit of state in NSSA. They essentially hold native tokens and arbitrary data managed by some program.
|
||||
|
||||
The CLI provides commands to manage accounts. Run `wallet account` to see the options available:
|
||||
```bash
|
||||
Commands:
|
||||
get Get account data
|
||||
new Produce new public or private account
|
||||
sync-private Sync private accounts
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
```
|
||||
|
||||
#### Create a new public account
|
||||
|
||||
You can create both public and private accounts through the CLI. For example:
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
```
|
||||
|
||||
This id is required when executing any program that interacts with the account.
|
||||
|
||||
> [!NOTE]
|
||||
> Public accounts live on-chain and are identified by a 32-byte Account ID.
|
||||
> Running `wallet account new public` generates a fresh keypair for the signature scheme used in NSSA.
|
||||
> The account ID is derived from the public key. The private key is used to sign transactions and to authorize the account in program executions.
|
||||
|
||||
#### Account initialization
|
||||
|
||||
To query the account’s current status, run:
|
||||
|
||||
```bash
|
||||
# Replace the id with yours
|
||||
wallet account get --account-id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
|
||||
# Output:
|
||||
Account is Uninitialized
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> New accounts begin in an uninitialized state, meaning they are not yet owned by any program. A program may claim an uninitialized account; once claimed, the account becomes owned by that program.
|
||||
> Owned accounts can only be modified through executions of the owning program. The only exception is native-token credits: any program may credit native tokens to any account.
|
||||
> However, debiting native tokens from an account must always be performed by its owning program.
|
||||
|
||||
In this example, we will initialize the account for the Authenticated transfer program, which securely manages native token transfers by requiring authentication for debits.
|
||||
|
||||
Initialize the account by running:
|
||||
|
||||
```bash
|
||||
# This command submits a public transaction executing the `init` function of the
|
||||
# Authenticated-transfer program. The wallet polls the sequencer until the
|
||||
# transaction is included in a block, which may take several seconds.
|
||||
wallet auth-transfer init --account-id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
```
|
||||
|
||||
After it completes, check the updated account status:
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated transfer program
|
||||
{"balance":0}
|
||||
```
|
||||
|
||||
### Funding the account: executing the Piñata program
|
||||
|
||||
Now that we have a public account initialized by the authenticated transfer program, we need to fund it. For that, the testnet provides the Piñata program.
|
||||
|
||||
```bash
|
||||
# Complete with your id
|
||||
wallet pinata claim --to Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
```
|
||||
|
||||
After the claim succeeds, the account will be funded with some tokens:
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated transfer program
|
||||
{"balance":150}
|
||||
```
|
||||
|
||||
### Native token transfers: executing the Authenticated transfers program
|
||||
|
||||
NSSA comes with a program for managing and transferring native tokens. Run `wallet auth-transfer` to see the options available:
|
||||
```bash
|
||||
Commands:
|
||||
init Initialize account under authenticated transfer program
|
||||
send Send native tokens from one account to another with variable privacy
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
```
|
||||
|
||||
We have already used the `init` command. The `send` command is used to execute the `Transfer` function of the authenticated program.
|
||||
Let's try it. For that we need to create another account for the recipient of the transfer.
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS
|
||||
```
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
> The new account is uninitialized. The authenticated transfers program will claim any uninitialized account used in a transfer. So we don't need to manually initialize the recipient account.
|
||||
|
||||
Let's send 37 tokens to the new account.
|
||||
|
||||
```bash
|
||||
wallet auth-transfer send \
|
||||
--from Public/9ypzv6GGr3fwsgxY7EZezg5rz6zj52DPCkmf1vVujEiJ \
|
||||
--to Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS \
|
||||
--amount 37
|
||||
```
|
||||
|
||||
Once that succeeds we can check the states.
|
||||
|
||||
```bash
|
||||
# Sender account
|
||||
wallet account get --account-id Public/HrA8TVjBS8UVf9akV7LRhyh6k4c7F6PS7PvqgtPmKAT8
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated transfer program
|
||||
{"balance":113}
|
||||
```
|
||||
|
||||
```bash
|
||||
# Recipient account
|
||||
wallet account get --account-id Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated transfer program
|
||||
{"balance":37}
|
||||
```
|
||||
|
||||
#### Create a new private account
|
||||
|
||||
> [!NOTE]
|
||||
> Private accounts are structurally identical to public accounts; they differ only in how their state is stored off-chain and represented on-chain.
|
||||
> The raw values of a private account are never stored on-chain. Instead, the chain only holds a 32-byte commitment (a hash-like binding to the actual values). Transactions include encrypted versions of the private values so that users can recover them from the blockchain. The decryption keys are known only to the user and are never shared.
|
||||
> Private accounts are not managed through the usual signature mechanism used for public accounts. Instead, each private account is associated with two keypairs:
|
||||
> - *Nullifier keys*, for using the corresponding private account in privacy preserving executions.
|
||||
> - *Viewing keys*, used for encrypting and decrypting the values included in transactions.
|
||||
>
|
||||
> Private accounts also have a 32-byte identifier, derived from the nullifier public key.
|
||||
>
|
||||
> Just like public accounts, private accounts can only be initialized once. Any user can initialize them without knowing the owner's secret keys. However, modifying an initialized private account through an off-chain program execution requires knowledge of the owner’s secret keys.
|
||||
>
|
||||
> Transactions that modify the values of a private account include a commitment to the new values, which will be added to the on-chain commitment set. They also include a nullifier that marks the previous version as old.
|
||||
> The nullifier is constructed so that it cannot be linked to any prior commitment, ensuring that updates to the same private account cannot be correlated.
|
||||
|
||||
Now let’s switch to the private state and create a private account.
|
||||
|
||||
```bash
|
||||
wallet account new private
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Private/HacPU3hakLYzWtSqUPw6TUr8fqoMieVWovsUR6sJf7cL
|
||||
With npk e6366f79d026c8bd64ae6b3d601f0506832ec682ab54897f205fffe64ec0d951
|
||||
With ipk 02ddc96d0eb56e00ce14994cfdaec5ae1f76244180a919545983156e3519940a17
|
||||
```
|
||||
|
||||
For now, focus only on the account id. Ignore the `npk` and `ipk` values. These are the Nullifier public key and the Viewing public key. They are stored locally in the wallet and are used internally to build privacy-preserving transactions.
|
||||
Also, the account id for private accounts is derived from the `npk` value. But we won't need them now.
|
||||
|
||||
Just like public accounts, new private accounts start out uninitialized:
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Private/HacPU3hakLYzWtSqUPw6TUr8fqoMieVWovsUR6sJf7cL
|
||||
|
||||
# Output:
|
||||
Account is Uninitialized
|
||||
```
|
||||
Unlike public accounts, private accounts are never visible to the network. They exist only in your local wallet storage.
|
||||
|
||||
#### Sending tokens from the public account to the private account
|
||||
|
||||
Sending tokens to an uninitialized private account causes the Authenticated-Transfers program to claim it. Just like with public accounts.
|
||||
This happens because program execution logic does not depend on whether the involved accounts are public or private.
|
||||
|
||||
Let’s send 17 tokens to the new private account.
|
||||
|
||||
The syntax is identical to the public-to-public transfer; just set the private ID as the recipient.
|
||||
|
||||
This command will run the Authenticated-Transfer program locally, generate a proof, and submit it to the sequencer. Depending on your machine, this can take from 30 seconds to 4 minutes.
|
||||
|
||||
```bash
|
||||
wallet auth-transfer send \
|
||||
--from Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS \
|
||||
--to Private/HacPU3hakLYzWtSqUPw6TUr8fqoMieVWovsUR6sJf7cL \
|
||||
--amount 17
|
||||
```
|
||||
|
||||
After it succeeds, check both accounts:
|
||||
|
||||
```bash
|
||||
# Public sender account
|
||||
wallet account get --account-id Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated transfer program
|
||||
{"balance":20}
|
||||
```
|
||||
|
||||
```bash
|
||||
# Private recipient account
|
||||
wallet account get --account-id Private/HacPU3hakLYzWtSqUPw6TUr8fqoMieVWovsUR6sJf7cL
|
||||
|
||||
# Output:
|
||||
Account owned by authenticated transfer program
|
||||
{"balance":17}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> The last command does not query the network.
|
||||
> It works even offline because private account data lives only in your wallet storage. Other users cannot read your private balances.
|
||||
|
||||
#### Digression: modifying private accounts
|
||||
|
||||
As a general rule, private accounts can only be modified through a program execution performed by their owner. That is, the person who holds the private key for that account. There is one exception: an uninitialized private account may be initialized by any user, without requiring the private key. After initialization, only the owner can modify it.
|
||||
|
||||
This mechanism enables a common use case: transferring funds from any account (public or private) to a private account owned by someone else. For such transfers, the recipient’s private account must be uninitialized.
|
||||
|
||||
|
||||
#### Sending tokens from the public account to a private account owned by someone else
|
||||
|
||||
For this tutorial, we’ll simulate that scenario by creating a new private account that we own, but we’ll treat it as if it belonged to someone else.
|
||||
|
||||
Let's create a new (uninitialized) private account like before:
|
||||
|
||||
```bash
|
||||
wallet account new private
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Private/AukXPRBmrYVqoqEW2HTs7N3hvTn3qdNFDcxDHVr5hMm5
|
||||
With npk 0c95ebc4b3830f53da77bb0b80a276a776cdcf6410932acc718dcdb3f788a00e
|
||||
With ipk 039fd12a3674a880d3e917804129141e4170d419d1f9e28a3dcf979c1f2369cb72
|
||||
```
|
||||
|
||||
Now we'll ignore the private account ID and focus on the `npk` and `ipk` values. We'll need this to send tokens to a foreign private account. Syntax is very similar.
|
||||
|
||||
```bash
|
||||
wallet auth-transfer send \
|
||||
--from Public/Ev1JprP9BmhbFVQyBcbznU8bAXcwrzwRoPTetXdQPAWS \
|
||||
--to-npk 0c95ebc4b3830f53da77bb0b80a276a776cdcf6410932acc718dcdb3f788a00e \
|
||||
--to-ipk 039fd12a3674a880d3e917804129141e4170d419d1f9e28a3dcf979c1f2369cb72 \
|
||||
--amount 3
|
||||
```
|
||||
|
||||
The command above produces a privacy-preserving transaction, which may take a few minutes to complete. The updated values of the private account are encrypted and included in the transaction.
|
||||
|
||||
Once the transaction is accepted, the recipient must run `wallet account sync-private`. This command scans the chain for encrypted values that belong to their private accounts and updates the local versions accordingly.
|
||||
|
||||
|
||||
#### Transfers in other combinations of public and private accounts
|
||||
|
||||
We’ve shown how to use the authenticated-transfers program for transfers between two public accounts, and for transfers from a public sender to a private recipient. Sending tokens from a private account (whether to a public account or to another private account) works in essentially the same way.
|
||||
|
||||
### The token program
|
||||
|
||||
So far, we’ve made transfers using the authenticated-transfers program, which handles native token transfers. The Token program, on the other hand, is used for creating and managing custom tokens.
|
||||
|
||||
> [!NOTE]
|
||||
> The token program is a single program responsible for creating and managing all tokens. There is no need to deploy new programs to introduce new tokens. All token-related operations are performed by invoking the appropriate functions of the token program.
|
||||
|
||||
The CLI provides commands to execute the token program. To see the options available run `wallet token`:
|
||||
|
||||
```bash
|
||||
Commands:
|
||||
new Produce a new token
|
||||
send Send tokens from one account to another with variable privacy
|
||||
help Print this message or the help of the given subcommand(s)
|
||||
```
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
> The Token program manages its accounts in two categories. Meaning, all accounts owned by the Token program fall into one of these types.
|
||||
> - Token definition accounts: these accounts store metadata about a token, such as its name, total supply, and other identifying properties. They act as the token’s unique identifier.
|
||||
> - Token holding accounts: these accounts hold actual token balances. In addition to the balance, they also record which token definition they belong to.
|
||||
|
||||
#### Creating a new token
|
||||
|
||||
To create a new token, simply run `wallet token new`. This will create a transaction to execute the `New` function of the token program.
|
||||
The command expects a name, the desired total supply, and two uninitialized accounts:
|
||||
- One that will be initialized as the token definition account for the new token.
|
||||
- Another that will be initialized as a token holding account and receive the token’s entire initial supply.
|
||||
|
||||
|
||||
##### New token with both definition and supply accounts set as public
|
||||
|
||||
For example, let's create two new (uninitialized) public accounts and then use them to create a new token.
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7
|
||||
```
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw
|
||||
```
|
||||
|
||||
Now we use them to create a new token. Let's call it the "Token A"
|
||||
|
||||
```bash
|
||||
wallet token new \
|
||||
--name TOKENA \
|
||||
--total-supply 1337 \
|
||||
--definition-account-id Public/4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7 \
|
||||
--supply-account-id Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw
|
||||
```
|
||||
|
||||
After it succeeds, we can inspect the two accounts to see how they were initialized.
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7
|
||||
|
||||
# Output:
|
||||
Definition account owned by token program
|
||||
{"account_type":"Token definition","name":"TOKENA","total_supply":1337}
|
||||
```
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw
|
||||
|
||||
# Output:
|
||||
Holding account owned by token program
|
||||
{"account_type":"Token holding","definition_id":"4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7","balance":1337}
|
||||
```
|
||||
|
||||
##### New token with public account definition but private holding account for initial supply
|
||||
|
||||
Let’s create a new token, but this time using a public definition account and a private holding account to store the entire supply.
|
||||
|
||||
Since we can’t reuse the accounts from the previous example, we need to create fresh ones for this case.
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii
|
||||
```
|
||||
|
||||
```bash
|
||||
wallet account new private
|
||||
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Private/HMRHZdPw4pbyPVZHNGrV6K5AA95wACFsHTRST84fr3CF
|
||||
With npk 6a2dfe433cf28e525aa0196d719be3c16146f7ee358ca39595323f94fde38f93
|
||||
With ipk 03d59abf4bee974cc12ddb44641c19f0b5441fef39191f047c988c29a77252a577
|
||||
```
|
||||
|
||||
And we use them to create the token.
|
||||
|
||||
Now we use them to create a new token. Let's call it "Token B".
|
||||
|
||||
```bash
|
||||
wallet token new \
|
||||
--name TOKENB \
|
||||
--total-supply 7331 \
|
||||
--definition-account-id Public/GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii \
|
||||
--supply-account-id Private/HMRHZdPw4pbyPVZHNGrV6K5AA95wACFsHTRST84fr3CF
|
||||
```
|
||||
|
||||
After it succeeds, we can check their values
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii
|
||||
|
||||
# Output:
|
||||
Definition account owned by token program
|
||||
{"account_type":"Token definition","name":"TOKENB","total_supply":7331}
|
||||
```
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Private/HMRHZdPw4pbyPVZHNGrV6K5AA95wACFsHTRST84fr3CF
|
||||
|
||||
# Output:
|
||||
Holding account owned by token program
|
||||
{"account_type":"Token holding","definition_id":"GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii","balance":7331}
|
||||
```
|
||||
|
||||
Like any other private account owned by us, it cannot be seen by other users.
|
||||
|
||||
#### Custom token transfers
|
||||
|
||||
The Token program has a function to move funds from one token holding account to another one. If executed with an uninitialized account as the recipient, this will be automatically claimed by the token program.
|
||||
|
||||
The transfer function can be executed with the `wallet token send` command.
|
||||
|
||||
Let's create a new public account for the recipient.
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6
|
||||
```
|
||||
|
||||
Let's send 1000 B tokens to this new account. We'll debit this from the supply account used in the creation of the token.
|
||||
|
||||
```bash
|
||||
wallet token send \
|
||||
--from Private/HMRHZdPw4pbyPVZHNGrV6K5AA95wACFsHTRST84fr3CF \
|
||||
--to Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
--amount 1000
|
||||
```
|
||||
|
||||
Let's inspect the public account:
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6
|
||||
|
||||
# Output:
|
||||
Holding account owned by token program
|
||||
{"account_type":"Token holding","definition_id":"GQ3C8rbprTtQUCvkuVBRu3v9wvUvjafCMFqoSPvTEVii","balance":1000}
|
||||
```
|
||||
|
||||
### Chain information
|
||||
|
||||
The wallet provides some commands to query information about the chain. These are under the `wallet chain-info` command.
|
||||
|
||||
```bash
|
||||
Commands:
|
||||
current-block-id Get current block id from sequencer
|
||||
block Get block at id from sequencer
|
||||
transaction Get transaction at hash from sequencer
|
||||
```
|
||||
|
||||
For example, run this to find the current block id.
|
||||
|
||||
```bash
|
||||
wallet chain-info current-block-id
|
||||
|
||||
# Output:
|
||||
Last block id is 65537
|
||||
```
|
||||
|
||||
|
||||
### Automated Market Maker (AMM)
|
||||
|
||||
NSSA includes an AMM program that manages liquidity pools and enables swaps between custom tokens. To test this functionality, we first need to create a liquidity pool.
|
||||
|
||||
#### Creating a liquidity pool for a token pair
|
||||
|
||||
We start by creating a new pool for the tokens previously created. In return for providing liquidity, we will receive liquidity provider (LP) tokens, which represent our share of the pool and are required to withdraw liquidity later.
|
||||
|
||||
>[!NOTE]
|
||||
> The AMM program does not currently charge swap fees or distribute rewards to liquidity providers. LP tokens therefore only represent a proportional share of the pool reserves and do not provide additional value from swap activity. Fee support for liquidity providers will be added in future versions of the AMM program.
|
||||
|
||||
To hold these LP tokens, we first create a new account:
|
||||
|
||||
```bash
|
||||
wallet account new public
|
||||
|
||||
# Output:
|
||||
Generated new account with account_id Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf
|
||||
```
|
||||
|
||||
Next, we initialize the liquidity pool by depositing tokens A and B and specifying the account that will receive the LP tokens:
|
||||
|
||||
```bash
|
||||
wallet amm new \
|
||||
--user-holding-a Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw \
|
||||
--user-holding-b Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
--user-holding-lp Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf \
|
||||
--balance-a 100 \
|
||||
--balance-b 200
|
||||
```
|
||||
|
||||
The newly created account is owned by the token program, meaning that LP tokens are managed by the same token infrastructure as regular tokens.
|
||||
|
||||
```bash
|
||||
wallet account get --account-id Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf
|
||||
|
||||
# Output:
|
||||
Holding account owned by token program
|
||||
{"account_type":"Token holding","definition_id":"7BeDS3e28MA5Err7gBswmR1fUKdHXqmUpTefNPu3pJ9i","balance":100}
|
||||
```
|
||||
|
||||
If you inspect the `user-holding-a` and `user-holding-b` accounts passed to the `wallet amm new` command, you will see that 100 and 200 tokens were deducted, respectively. These tokens now reside in the liquidity pool and are available for swaps by any user.
|
||||
|
||||
|
||||
#### Swaping
|
||||
|
||||
Token swaps can be performed using the wallet amm swap command:
|
||||
|
||||
```bash
|
||||
wallet amm swap \
|
||||
--user-holding-a Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw \
|
||||
--user-holding-b Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
# The amount of tokens to swap
|
||||
--amount-in 5 \
|
||||
# The minimum number of tokens expected in return
|
||||
--min-amount-out 8 \
|
||||
# The definition ID of the token being provided to the swap
|
||||
# In this case, we are swapping from TOKENA to TOKENB, and so this is the definition ID of TOKENA
|
||||
--token-definition 4X9kAcnCZ1Ukkbm3nywW9xfCNPK8XaMWCk3zfs1sP4J7
|
||||
```
|
||||
|
||||
Once executed, 5 tokens are deducted from the Token A holding account and the corresponding amount (determined by the pool’s pricing function) is credited to the Token B holding account.
|
||||
|
||||
|
||||
#### Withdrawing liquidity from the pool
|
||||
|
||||
Liquidity providers can withdraw assets from the pool by redeeming (burning) LP tokens. The amount of tokens received is proportional to the share of LP tokens being redeemed relative to the total LP supply.
|
||||
|
||||
This operation is performed using the `wallet amm remove-liquidity` command:
|
||||
|
||||
```bash
|
||||
wallet amm remove-liquidity \
|
||||
--user-holding-a Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw \
|
||||
--user-holding-b Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
--user-holding-lp Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf \
|
||||
--balance-lp 20 \
|
||||
--min-amount-a 1 \
|
||||
--min-amount-b 1
|
||||
```
|
||||
|
||||
This instruction burns `balance-lp` LP tokens from the user’s LP holding account. In exchange, the AMM transfers tokens A and B from the pool’s vault accounts to the user’s holding accounts, according to the current pool reserves.
|
||||
|
||||
The `min-amount-a` and `min-amount-b` parameters specify the minimum acceptable amounts of tokens A and B to be received. If the computed outputs fall below either threshold, the instruction fails, protecting the user against unfavorable pool state changes.
|
||||
|
||||
#### Adding liquidity to the pool
|
||||
|
||||
Additional liquidity can be added to an existing pool by depositing tokens A and B in the ratio implied by the current pool reserves. In return, new LP tokens are minted to represent the user’s proportional share of the pool.
|
||||
|
||||
This is done using the `wallet amm add-liquidity` command:
|
||||
|
||||
```bash
|
||||
wallet amm add-liquidity \
|
||||
--user-holding-a Public/9RRSMm3w99uCD2Jp2Mqqf6dfc8me2tkFRE9HeU2DFftw \
|
||||
--user-holding-b Public/88f2zeTgiv9LUthQwPJbrmufb9SiDfmpCs47B7vw6Gd6 \
|
||||
--user-holding-lp Public/FHgLW9jW4HXMV6egLWbwpTqVAGiCHw2vkg71KYSuimVf \
|
||||
--min-amount-lp 1 \
|
||||
--max-amount-a 10 \
|
||||
--max-amount-b 10
|
||||
```
|
||||
|
||||
In this instruction, `max-amount-a` and `max-amount-b` define upper bounds on the number of tokens A and B that may be withdrawn from the user’s accounts. The AMM computes the actual required amounts based on the pool’s reserve ratio.
|
||||
|
||||
The `min-amount-lp` parameter specifies the minimum number of LP tokens that must be minted for the transaction to succeed. If the resulting LP token amount is below this threshold, the instruction fails.
|
||||
3. On another terminal go to the `logos-blockchain/lssa` repo and run the sequencer:
|
||||
- `git checkout schouhy/full-bedrock-integration`
|
||||
- `RUST_LOG=info RISC0_DEV_MODE=1 cargo run --release -p sequencer_runner sequencer_runner/configs/debug`
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -2,6 +2,7 @@
|
||||
name = "bedrock_client"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
reqwest.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "common"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa.workspace = true
|
||||
|
||||
@ -150,10 +150,11 @@ _wallet_account() {
|
||||
subcommand)
|
||||
subcommands=(
|
||||
'get:Get account data'
|
||||
'list:List all accounts'
|
||||
'list:List all accounts owned by the wallet'
|
||||
'ls:List all accounts (alias for list)'
|
||||
'new:Produce new public or private account'
|
||||
'sync-private:Sync private accounts'
|
||||
'label:Set a label for an account'
|
||||
'help:Print this message or the help of the given subcommand(s)'
|
||||
)
|
||||
_describe -t subcommands 'account subcommands' subcommands
|
||||
@ -184,6 +185,11 @@ _wallet_account() {
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
label)
|
||||
_arguments \
|
||||
'(-a --account-id)'{-a,--account-id}'[Account ID to label]:account_id:_wallet_account_ids' \
|
||||
'(-l --label)'{-l,--label}'[The label to assign to the account]:label:'
|
||||
;;
|
||||
esac
|
||||
;;
|
||||
esac
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "program_deployment"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "example_program_deployment_methods"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
risc0-build.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "example_program_deployment_programs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa_core.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "indexer_core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
common.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "indexer_service"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
indexer_service_protocol.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "indexer_service_protocol"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa_core = { workspace = true, optional = true, features = ["host"] }
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "indexer_service_rpc"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
indexer_service_protocol = { workspace = true }
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "integration_tests"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa_core = { workspace = true, features = ["host"] }
|
||||
@ -12,8 +13,11 @@ wallet.workspace = true
|
||||
common.workspace = true
|
||||
key_protocol.workspace = true
|
||||
indexer_core.workspace = true
|
||||
url.workspace = true
|
||||
wallet-ffi.workspace = true
|
||||
serde_json.workspace = true
|
||||
token_core.workspace = true
|
||||
|
||||
url.workspace = true
|
||||
anyhow.workspace = true
|
||||
env_logger.workspace = true
|
||||
log.workspace = true
|
||||
|
||||
@ -44,6 +44,7 @@ pub struct TestContext {
|
||||
indexer_loop_handle: Option<JoinHandle<Result<()>>>,
|
||||
sequencer_client: SequencerClient,
|
||||
wallet: WalletCore,
|
||||
wallet_password: String,
|
||||
_temp_sequencer_dir: TempDir,
|
||||
_temp_wallet_dir: TempDir,
|
||||
}
|
||||
@ -114,7 +115,7 @@ impl TestContext {
|
||||
format!("http://{sequencer_addr}")
|
||||
};
|
||||
|
||||
let (wallet, temp_wallet_dir) = Self::setup_wallet(sequencer_addr.clone())
|
||||
let (wallet, temp_wallet_dir, wallet_password) = Self::setup_wallet(sequencer_addr.clone())
|
||||
.await
|
||||
.context("Failed to setup wallet")?;
|
||||
|
||||
@ -142,6 +143,7 @@ impl TestContext {
|
||||
wallet,
|
||||
_temp_sequencer_dir: temp_sequencer_dir,
|
||||
_temp_wallet_dir: temp_wallet_dir,
|
||||
wallet_password,
|
||||
})
|
||||
} else {
|
||||
Ok(Self {
|
||||
@ -153,6 +155,7 @@ impl TestContext {
|
||||
wallet,
|
||||
_temp_sequencer_dir: temp_sequencer_dir,
|
||||
_temp_wallet_dir: temp_wallet_dir,
|
||||
wallet_password,
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -193,7 +196,7 @@ impl TestContext {
|
||||
))
|
||||
}
|
||||
|
||||
async fn setup_wallet(sequencer_addr: String) -> Result<(WalletCore, TempDir)> {
|
||||
async fn setup_wallet(sequencer_addr: String) -> Result<(WalletCore, TempDir, String)> {
|
||||
let manifest_dir = env!("CARGO_MANIFEST_DIR");
|
||||
let wallet_config_source_path =
|
||||
PathBuf::from(manifest_dir).join("configs/wallet/wallet_config.json");
|
||||
@ -211,11 +214,12 @@ impl TestContext {
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let wallet_password = "test_pass".to_owned();
|
||||
let wallet = WalletCore::new_init_storage(
|
||||
config_path,
|
||||
storage_path,
|
||||
Some(config_overrides),
|
||||
"test_pass".to_owned(),
|
||||
wallet_password.clone(),
|
||||
)
|
||||
.context("Failed to init wallet")?;
|
||||
wallet
|
||||
@ -223,7 +227,7 @@ impl TestContext {
|
||||
.await
|
||||
.context("Failed to store wallet persistent data")?;
|
||||
|
||||
Ok((wallet, temp_wallet_dir))
|
||||
Ok((wallet, temp_wallet_dir, wallet_password))
|
||||
}
|
||||
|
||||
/// Get reference to the wallet.
|
||||
@ -231,6 +235,10 @@ impl TestContext {
|
||||
&self.wallet
|
||||
}
|
||||
|
||||
pub fn wallet_password(&self) -> &str {
|
||||
&self.wallet_password
|
||||
}
|
||||
|
||||
/// Get mutable reference to the wallet.
|
||||
pub fn wallet_mut(&mut self) -> &mut WalletCore {
|
||||
&mut self.wallet
|
||||
@ -255,6 +263,7 @@ impl Drop for TestContext {
|
||||
wallet: _,
|
||||
_temp_sequencer_dir,
|
||||
_temp_wallet_dir,
|
||||
wallet_password: _,
|
||||
} = self;
|
||||
|
||||
sequencer_loop_handle.abort();
|
||||
@ -268,6 +277,20 @@ impl Drop for TestContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// A test context to be used in normal #[test] tests
|
||||
pub struct BlockingTestContext {
|
||||
pub ctx: TestContext,
|
||||
pub runtime: tokio::runtime::Runtime,
|
||||
}
|
||||
|
||||
impl BlockingTestContext {
|
||||
pub fn new() -> Result<Self> {
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let ctx = runtime.block_on(TestContext::new())?;
|
||||
Ok(Self { ctx, runtime })
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format_public_account_id(account_id: &str) -> String {
|
||||
format!("Public/{account_id}")
|
||||
}
|
||||
|
||||
@ -8,6 +8,7 @@ use integration_tests::{
|
||||
use key_protocol::key_management::key_tree::chain_index::ChainIndex;
|
||||
use log::info;
|
||||
use nssa::program::Program;
|
||||
use token_core::{TokenDefinition, TokenHolding};
|
||||
use tokio::test;
|
||||
use wallet::cli::{
|
||||
Command, SubcommandReturnValue,
|
||||
@ -59,11 +60,13 @@ async fn create_and_transfer_public_token() -> Result<()> {
|
||||
};
|
||||
|
||||
// Create new token
|
||||
let name = "A NAME".to_string();
|
||||
let total_supply = 37;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::New {
|
||||
definition_account_id: format_public_account_id(&definition_account_id.to_string()),
|
||||
supply_account_id: format_public_account_id(&supply_account_id.to_string()),
|
||||
name: "A NAME".to_string(),
|
||||
total_supply: 37,
|
||||
name: name.clone(),
|
||||
total_supply,
|
||||
};
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
|
||||
@ -76,16 +79,16 @@ async fn create_and_transfer_public_token() -> Result<()> {
|
||||
.get_account(definition_account_id.to_string())
|
||||
.await?
|
||||
.account;
|
||||
let token_definition = TokenDefinition::try_from(&definition_acc.data)?;
|
||||
|
||||
assert_eq!(definition_acc.program_owner, Program::token().id());
|
||||
// The data of a token definition account has the following layout:
|
||||
// [ 0x00 || name (6 bytes) || total supply (little endian 16 bytes) || metadata id (32 bytes)]
|
||||
assert_eq!(
|
||||
definition_acc.data.as_ref(),
|
||||
&[
|
||||
0, 65, 32, 78, 65, 77, 69, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
]
|
||||
token_definition,
|
||||
TokenDefinition::Fungible {
|
||||
name: name.clone(),
|
||||
total_supply,
|
||||
metadata_id: None
|
||||
}
|
||||
);
|
||||
|
||||
// Check the status of the token holding account with the total supply
|
||||
@ -97,24 +100,23 @@ async fn create_and_transfer_public_token() -> Result<()> {
|
||||
|
||||
// The account must be owned by the token program
|
||||
assert_eq!(supply_acc.program_owner, Program::token().id());
|
||||
// The data of a token holding account has the following layout:
|
||||
// [ 0x01 || corresponding_token_definition_id (32 bytes) || balance (little endian 16 bytes) ]
|
||||
// First byte of the data equal to 1 means it's a token holding account
|
||||
assert_eq!(supply_acc.data.as_ref()[0], 1);
|
||||
// Bytes from 1 to 33 represent the id of the token this account is associated with
|
||||
let token_holding = TokenHolding::try_from(&supply_acc.data)?;
|
||||
assert_eq!(
|
||||
&supply_acc.data.as_ref()[1..33],
|
||||
definition_account_id.to_bytes()
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: total_supply
|
||||
}
|
||||
);
|
||||
assert_eq!(u128::from_le_bytes(supply_acc.data[33..].try_into()?), 37);
|
||||
|
||||
// Transfer 7 tokens from supply_acc to recipient_account_id
|
||||
let transfer_amount = 7;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
||||
from: format_public_account_id(&supply_account_id.to_string()),
|
||||
to: Some(format_public_account_id(&recipient_account_id.to_string())),
|
||||
to_npk: None,
|
||||
to_ipk: None,
|
||||
amount: 7,
|
||||
amount: transfer_amount,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -129,9 +131,14 @@ async fn create_and_transfer_public_token() -> Result<()> {
|
||||
.await?
|
||||
.account;
|
||||
assert_eq!(supply_acc.program_owner, Program::token().id());
|
||||
assert_eq!(supply_acc.data[0], 1);
|
||||
assert_eq!(&supply_acc.data[1..33], definition_account_id.to_bytes());
|
||||
assert_eq!(u128::from_le_bytes(supply_acc.data[33..].try_into()?), 30);
|
||||
let token_holding = TokenHolding::try_from(&supply_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: total_supply - transfer_amount
|
||||
}
|
||||
);
|
||||
|
||||
// Check the status of the recipient account after transfer
|
||||
let recipient_acc = ctx
|
||||
@ -140,15 +147,21 @@ async fn create_and_transfer_public_token() -> Result<()> {
|
||||
.await?
|
||||
.account;
|
||||
assert_eq!(recipient_acc.program_owner, Program::token().id());
|
||||
assert_eq!(recipient_acc.data[0], 1);
|
||||
assert_eq!(&recipient_acc.data[1..33], definition_account_id.to_bytes());
|
||||
assert_eq!(u128::from_le_bytes(recipient_acc.data[33..].try_into()?), 7);
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: transfer_amount
|
||||
}
|
||||
);
|
||||
|
||||
// Burn 3 tokens from recipient_acc
|
||||
let burn_amount = 3;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Burn {
|
||||
definition: format_public_account_id(&definition_account_id.to_string()),
|
||||
holder: format_public_account_id(&recipient_account_id.to_string()),
|
||||
amount: 3,
|
||||
amount: burn_amount,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -162,13 +175,15 @@ async fn create_and_transfer_public_token() -> Result<()> {
|
||||
.get_account(definition_account_id.to_string())
|
||||
.await?
|
||||
.account;
|
||||
let token_definition = TokenDefinition::try_from(&definition_acc.data)?;
|
||||
|
||||
assert_eq!(
|
||||
definition_acc.data.as_ref(),
|
||||
&[
|
||||
0, 65, 32, 78, 65, 77, 69, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
]
|
||||
token_definition,
|
||||
TokenDefinition::Fungible {
|
||||
name: name.clone(),
|
||||
total_supply: total_supply - burn_amount,
|
||||
metadata_id: None
|
||||
}
|
||||
);
|
||||
|
||||
// Check the status of the recipient account after burn
|
||||
@ -177,16 +192,24 @@ async fn create_and_transfer_public_token() -> Result<()> {
|
||||
.get_account(recipient_account_id.to_string())
|
||||
.await?
|
||||
.account;
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc.data)?;
|
||||
|
||||
assert_eq!(u128::from_le_bytes(recipient_acc.data[33..].try_into()?), 4);
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: transfer_amount - burn_amount
|
||||
}
|
||||
);
|
||||
|
||||
// Mint 10 tokens at recipient_acc
|
||||
let mint_amount = 10;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Mint {
|
||||
definition: format_public_account_id(&definition_account_id.to_string()),
|
||||
holder: Some(format_public_account_id(&recipient_account_id.to_string())),
|
||||
holder_npk: None,
|
||||
holder_ipk: None,
|
||||
amount: 10,
|
||||
amount: mint_amount,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -200,13 +223,15 @@ async fn create_and_transfer_public_token() -> Result<()> {
|
||||
.get_account(definition_account_id.to_string())
|
||||
.await?
|
||||
.account;
|
||||
let token_definition = TokenDefinition::try_from(&definition_acc.data)?;
|
||||
|
||||
assert_eq!(
|
||||
definition_acc.data.as_ref(),
|
||||
&[
|
||||
0, 65, 32, 78, 65, 77, 69, 44, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
]
|
||||
token_definition,
|
||||
TokenDefinition::Fungible {
|
||||
name,
|
||||
total_supply: total_supply - burn_amount + mint_amount,
|
||||
metadata_id: None
|
||||
}
|
||||
);
|
||||
|
||||
// Check the status of the recipient account after mint
|
||||
@ -215,10 +240,14 @@ async fn create_and_transfer_public_token() -> Result<()> {
|
||||
.get_account(recipient_account_id.to_string())
|
||||
.await?
|
||||
.account;
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc.data)?;
|
||||
|
||||
assert_eq!(
|
||||
u128::from_le_bytes(recipient_acc.data[33..].try_into()?),
|
||||
14
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: transfer_amount - burn_amount + mint_amount
|
||||
}
|
||||
);
|
||||
|
||||
info!("Successfully created and transferred public token");
|
||||
@ -270,11 +299,13 @@ async fn create_and_transfer_token_with_private_supply() -> Result<()> {
|
||||
};
|
||||
|
||||
// Create new token
|
||||
let name = "A NAME".to_string();
|
||||
let total_supply = 37;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::New {
|
||||
definition_account_id: format_public_account_id(&definition_account_id.to_string()),
|
||||
supply_account_id: format_private_account_id(&supply_account_id.to_string()),
|
||||
name: "A NAME".to_string(),
|
||||
total_supply: 37,
|
||||
name: name.clone(),
|
||||
total_supply,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -288,14 +319,16 @@ async fn create_and_transfer_token_with_private_supply() -> Result<()> {
|
||||
.get_account(definition_account_id.to_string())
|
||||
.await?
|
||||
.account;
|
||||
let token_definition = TokenDefinition::try_from(&definition_acc.data)?;
|
||||
|
||||
assert_eq!(definition_acc.program_owner, Program::token().id());
|
||||
assert_eq!(
|
||||
definition_acc.data.as_ref(),
|
||||
&[
|
||||
0, 65, 32, 78, 65, 77, 69, 37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
]
|
||||
token_definition,
|
||||
TokenDefinition::Fungible {
|
||||
name: name.clone(),
|
||||
total_supply,
|
||||
metadata_id: None
|
||||
}
|
||||
);
|
||||
|
||||
let new_commitment1 = ctx
|
||||
@ -305,12 +338,13 @@ async fn create_and_transfer_token_with_private_supply() -> Result<()> {
|
||||
assert!(verify_commitment_is_in_state(new_commitment1, ctx.sequencer_client()).await);
|
||||
|
||||
// Transfer 7 tokens from supply_acc to recipient_account_id
|
||||
let transfer_amount = 7;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
||||
from: format_private_account_id(&supply_account_id.to_string()),
|
||||
to: Some(format_private_account_id(&recipient_account_id.to_string())),
|
||||
to_npk: None,
|
||||
to_ipk: None,
|
||||
amount: 7,
|
||||
amount: transfer_amount,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -331,10 +365,11 @@ async fn create_and_transfer_token_with_private_supply() -> Result<()> {
|
||||
assert!(verify_commitment_is_in_state(new_commitment2, ctx.sequencer_client()).await);
|
||||
|
||||
// Burn 3 tokens from recipient_acc
|
||||
let burn_amount = 3;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Burn {
|
||||
definition: format_public_account_id(&definition_account_id.to_string()),
|
||||
holder: format_private_account_id(&recipient_account_id.to_string()),
|
||||
amount: 3,
|
||||
amount: burn_amount,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -348,13 +383,15 @@ async fn create_and_transfer_token_with_private_supply() -> Result<()> {
|
||||
.get_account(definition_account_id.to_string())
|
||||
.await?
|
||||
.account;
|
||||
let token_definition = TokenDefinition::try_from(&definition_acc.data)?;
|
||||
|
||||
assert_eq!(
|
||||
definition_acc.data.as_ref(),
|
||||
&[
|
||||
0, 65, 32, 78, 65, 77, 69, 34, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
|
||||
]
|
||||
token_definition,
|
||||
TokenDefinition::Fungible {
|
||||
name,
|
||||
total_supply: total_supply - burn_amount,
|
||||
metadata_id: None
|
||||
}
|
||||
);
|
||||
|
||||
let new_commitment2 = ctx
|
||||
@ -368,10 +405,14 @@ async fn create_and_transfer_token_with_private_supply() -> Result<()> {
|
||||
.wallet()
|
||||
.get_account_private(&recipient_account_id)
|
||||
.context("Failed to get recipient account")?;
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc.data)?;
|
||||
|
||||
assert_eq!(
|
||||
u128::from_le_bytes(recipient_acc.data[33..].try_into()?),
|
||||
4 // 7 - 3
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: transfer_amount - burn_amount
|
||||
}
|
||||
);
|
||||
|
||||
info!("Successfully created and transferred token with private supply");
|
||||
@ -414,11 +455,13 @@ async fn create_token_with_private_definition() -> Result<()> {
|
||||
};
|
||||
|
||||
// Create token with private definition
|
||||
let name = "A NAME".to_string();
|
||||
let total_supply = 37;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::New {
|
||||
definition_account_id: format_private_account_id(&definition_account_id.to_string()),
|
||||
supply_account_id: format_public_account_id(&supply_account_id.to_string()),
|
||||
name: "A NAME".to_string(),
|
||||
total_supply: 37,
|
||||
name: name.clone(),
|
||||
total_supply,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -441,8 +484,14 @@ async fn create_token_with_private_definition() -> Result<()> {
|
||||
.account;
|
||||
|
||||
assert_eq!(supply_acc.program_owner, Program::token().id());
|
||||
assert_eq!(supply_acc.data.as_ref()[0], 1);
|
||||
assert_eq!(u128::from_le_bytes(supply_acc.data[33..].try_into()?), 37);
|
||||
let token_holding = TokenHolding::try_from(&supply_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: total_supply
|
||||
}
|
||||
);
|
||||
|
||||
// Create private recipient account
|
||||
let result = wallet::cli::execute_subcommand(
|
||||
@ -471,6 +520,7 @@ async fn create_token_with_private_definition() -> Result<()> {
|
||||
};
|
||||
|
||||
// Mint to public account
|
||||
let mint_amount_public = 10;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Mint {
|
||||
definition: format_private_account_id(&definition_account_id.to_string()),
|
||||
holder: Some(format_public_account_id(
|
||||
@ -478,7 +528,7 @@ async fn create_token_with_private_definition() -> Result<()> {
|
||||
)),
|
||||
holder_npk: None,
|
||||
holder_ipk: None,
|
||||
amount: 10,
|
||||
amount: mint_amount_public,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -491,10 +541,15 @@ async fn create_token_with_private_definition() -> Result<()> {
|
||||
.wallet()
|
||||
.get_account_private(&definition_account_id)
|
||||
.context("Failed to get definition account")?;
|
||||
let token_definition = TokenDefinition::try_from(&definition_acc.data)?;
|
||||
|
||||
assert_eq!(
|
||||
u128::from_le_bytes(definition_acc.data[7..23].try_into()?),
|
||||
47 // 37 + 10
|
||||
token_definition,
|
||||
TokenDefinition::Fungible {
|
||||
name: name.clone(),
|
||||
total_supply: total_supply + mint_amount_public,
|
||||
metadata_id: None
|
||||
}
|
||||
);
|
||||
|
||||
// Verify public recipient received tokens
|
||||
@ -503,13 +558,18 @@ async fn create_token_with_private_definition() -> Result<()> {
|
||||
.get_account(recipient_account_id_public.to_string())
|
||||
.await?
|
||||
.account;
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc.data)?;
|
||||
|
||||
assert_eq!(
|
||||
u128::from_le_bytes(recipient_acc.data[33..].try_into()?),
|
||||
10
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: mint_amount_public
|
||||
}
|
||||
);
|
||||
|
||||
// Mint to private account
|
||||
let mint_amount_private = 5;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Mint {
|
||||
definition: format_private_account_id(&definition_account_id.to_string()),
|
||||
holder: Some(format_private_account_id(
|
||||
@ -517,7 +577,7 @@ async fn create_token_with_private_definition() -> Result<()> {
|
||||
)),
|
||||
holder_npk: None,
|
||||
holder_ipk: None,
|
||||
amount: 5,
|
||||
amount: mint_amount_private,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -537,10 +597,14 @@ async fn create_token_with_private_definition() -> Result<()> {
|
||||
.wallet()
|
||||
.get_account_private(&recipient_account_id_private)
|
||||
.context("Failed to get private recipient account")?;
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc_private.data)?;
|
||||
|
||||
assert_eq!(
|
||||
u128::from_le_bytes(recipient_acc_private.data[33..].try_into()?),
|
||||
5
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: mint_amount_private
|
||||
}
|
||||
);
|
||||
|
||||
info!("Successfully created token with private definition and minted to both account types");
|
||||
@ -579,11 +643,13 @@ async fn create_token_with_private_definition_and_supply() -> Result<()> {
|
||||
};
|
||||
|
||||
// Create token with both private definition and supply
|
||||
let name = "A NAME".to_string();
|
||||
let total_supply = 37;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::New {
|
||||
definition_account_id: format_private_account_id(&definition_account_id.to_string()),
|
||||
supply_account_id: format_private_account_id(&supply_account_id.to_string()),
|
||||
name: "A NAME".to_string(),
|
||||
total_supply: 37,
|
||||
name,
|
||||
total_supply,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -610,8 +676,15 @@ async fn create_token_with_private_definition_and_supply() -> Result<()> {
|
||||
.wallet()
|
||||
.get_account_private(&supply_account_id)
|
||||
.context("Failed to get supply account")?;
|
||||
let token_holding = TokenHolding::try_from(&supply_acc.data)?;
|
||||
|
||||
assert_eq!(u128::from_le_bytes(supply_acc.data[33..].try_into()?), 37);
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: total_supply
|
||||
}
|
||||
);
|
||||
|
||||
// Create recipient account
|
||||
let result = wallet::cli::execute_subcommand(
|
||||
@ -627,12 +700,13 @@ async fn create_token_with_private_definition_and_supply() -> Result<()> {
|
||||
};
|
||||
|
||||
// Transfer tokens
|
||||
let transfer_amount = 7;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
||||
from: format_private_account_id(&supply_account_id.to_string()),
|
||||
to: Some(format_private_account_id(&recipient_account_id.to_string())),
|
||||
to_npk: None,
|
||||
to_ipk: None,
|
||||
amount: 7,
|
||||
amount: transfer_amount,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -658,13 +732,27 @@ async fn create_token_with_private_definition_and_supply() -> Result<()> {
|
||||
.wallet()
|
||||
.get_account_private(&supply_account_id)
|
||||
.context("Failed to get supply account")?;
|
||||
assert_eq!(u128::from_le_bytes(supply_acc.data[33..].try_into()?), 30);
|
||||
let token_holding = TokenHolding::try_from(&supply_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: total_supply - transfer_amount
|
||||
}
|
||||
);
|
||||
|
||||
let recipient_acc = ctx
|
||||
.wallet()
|
||||
.get_account_private(&recipient_account_id)
|
||||
.context("Failed to get recipient account")?;
|
||||
assert_eq!(u128::from_le_bytes(recipient_acc.data[33..].try_into()?), 7);
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: transfer_amount
|
||||
}
|
||||
);
|
||||
|
||||
info!("Successfully created and transferred token with both private definition and supply");
|
||||
|
||||
@ -715,11 +803,13 @@ async fn shielded_token_transfer() -> Result<()> {
|
||||
};
|
||||
|
||||
// Create token
|
||||
let name = "A NAME".to_string();
|
||||
let total_supply = 37;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::New {
|
||||
definition_account_id: format_public_account_id(&definition_account_id.to_string()),
|
||||
supply_account_id: format_public_account_id(&supply_account_id.to_string()),
|
||||
name: "A NAME".to_string(),
|
||||
total_supply: 37,
|
||||
name,
|
||||
total_supply,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -728,12 +818,13 @@ async fn shielded_token_transfer() -> Result<()> {
|
||||
tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await;
|
||||
|
||||
// Perform shielded transfer: public supply -> private recipient
|
||||
let transfer_amount = 7;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
||||
from: format_public_account_id(&supply_account_id.to_string()),
|
||||
to: Some(format_private_account_id(&recipient_account_id.to_string())),
|
||||
to_npk: None,
|
||||
to_ipk: None,
|
||||
amount: 7,
|
||||
amount: transfer_amount,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -747,7 +838,14 @@ async fn shielded_token_transfer() -> Result<()> {
|
||||
.get_account(supply_account_id.to_string())
|
||||
.await?
|
||||
.account;
|
||||
assert_eq!(u128::from_le_bytes(supply_acc.data[33..].try_into()?), 30);
|
||||
let token_holding = TokenHolding::try_from(&supply_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: total_supply - transfer_amount
|
||||
}
|
||||
);
|
||||
|
||||
// Verify recipient commitment exists
|
||||
let new_commitment = ctx
|
||||
@ -761,7 +859,14 @@ async fn shielded_token_transfer() -> Result<()> {
|
||||
.wallet()
|
||||
.get_account_private(&recipient_account_id)
|
||||
.context("Failed to get recipient account")?;
|
||||
assert_eq!(u128::from_le_bytes(recipient_acc.data[33..].try_into()?), 7);
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: transfer_amount
|
||||
}
|
||||
);
|
||||
|
||||
info!("Successfully performed shielded token transfer");
|
||||
|
||||
@ -812,11 +917,13 @@ async fn deshielded_token_transfer() -> Result<()> {
|
||||
};
|
||||
|
||||
// Create token with private supply
|
||||
let name = "A NAME".to_string();
|
||||
let total_supply = 37;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::New {
|
||||
definition_account_id: format_public_account_id(&definition_account_id.to_string()),
|
||||
supply_account_id: format_private_account_id(&supply_account_id.to_string()),
|
||||
name: "A NAME".to_string(),
|
||||
total_supply: 37,
|
||||
name,
|
||||
total_supply,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -825,12 +932,13 @@ async fn deshielded_token_transfer() -> Result<()> {
|
||||
tokio::time::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS)).await;
|
||||
|
||||
// Perform deshielded transfer: private supply -> public recipient
|
||||
let transfer_amount = 7;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Send {
|
||||
from: format_private_account_id(&supply_account_id.to_string()),
|
||||
to: Some(format_public_account_id(&recipient_account_id.to_string())),
|
||||
to_npk: None,
|
||||
to_ipk: None,
|
||||
amount: 7,
|
||||
amount: transfer_amount,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -850,7 +958,14 @@ async fn deshielded_token_transfer() -> Result<()> {
|
||||
.wallet()
|
||||
.get_account_private(&supply_account_id)
|
||||
.context("Failed to get supply account")?;
|
||||
assert_eq!(u128::from_le_bytes(supply_acc.data[33..].try_into()?), 30);
|
||||
let token_holding = TokenHolding::try_from(&supply_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: total_supply - transfer_amount
|
||||
}
|
||||
);
|
||||
|
||||
// Verify recipient balance
|
||||
let recipient_acc = ctx
|
||||
@ -858,7 +973,14 @@ async fn deshielded_token_transfer() -> Result<()> {
|
||||
.get_account(recipient_account_id.to_string())
|
||||
.await?
|
||||
.account;
|
||||
assert_eq!(u128::from_le_bytes(recipient_acc.data[33..].try_into()?), 7);
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: transfer_amount
|
||||
}
|
||||
);
|
||||
|
||||
info!("Successfully performed deshielded token transfer");
|
||||
|
||||
@ -896,11 +1018,13 @@ async fn token_claiming_path_with_private_accounts() -> Result<()> {
|
||||
};
|
||||
|
||||
// Create token
|
||||
let name = "A NAME".to_string();
|
||||
let total_supply = 37;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::New {
|
||||
definition_account_id: format_private_account_id(&definition_account_id.to_string()),
|
||||
supply_account_id: format_private_account_id(&supply_account_id.to_string()),
|
||||
name: "A NAME".to_string(),
|
||||
total_supply: 37,
|
||||
name,
|
||||
total_supply,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -931,12 +1055,13 @@ async fn token_claiming_path_with_private_accounts() -> Result<()> {
|
||||
.context("Failed to get private account keys")?;
|
||||
|
||||
// Mint using claiming path (foreign account)
|
||||
let mint_amount = 9;
|
||||
let subcommand = TokenProgramAgnosticSubcommand::Mint {
|
||||
definition: format_private_account_id(&definition_account_id.to_string()),
|
||||
holder: None,
|
||||
holder_npk: Some(hex::encode(holder_keys.nullifer_public_key.0)),
|
||||
holder_ipk: Some(hex::encode(holder_keys.incoming_viewing_public_key.0)),
|
||||
amount: 9,
|
||||
amount: mint_amount,
|
||||
};
|
||||
|
||||
wallet::cli::execute_subcommand(ctx.wallet_mut(), Command::Token(subcommand)).await?;
|
||||
@ -960,7 +1085,14 @@ async fn token_claiming_path_with_private_accounts() -> Result<()> {
|
||||
.wallet()
|
||||
.get_account_private(&recipient_account_id)
|
||||
.context("Failed to get recipient account")?;
|
||||
assert_eq!(u128::from_le_bytes(recipient_acc.data[33..].try_into()?), 9);
|
||||
let token_holding = TokenHolding::try_from(&recipient_acc.data)?;
|
||||
assert_eq!(
|
||||
token_holding,
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_account_id,
|
||||
balance: mint_amount
|
||||
}
|
||||
);
|
||||
|
||||
info!("Successfully minted tokens using claiming path");
|
||||
|
||||
|
||||
618
integration_tests/tests/wallet_ffi.rs
Normal file
618
integration_tests/tests/wallet_ffi.rs
Normal file
@ -0,0 +1,618 @@
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
ffi::{CStr, CString, c_char},
|
||||
io::Write,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use integration_tests::{
|
||||
ACC_RECEIVER, ACC_SENDER, ACC_SENDER_PRIVATE, BlockingTestContext,
|
||||
TIME_TO_WAIT_FOR_BLOCK_SECONDS,
|
||||
};
|
||||
use log::info;
|
||||
use nssa::{Account, AccountId, PublicKey, program::Program};
|
||||
use nssa_core::program::DEFAULT_PROGRAM_ID;
|
||||
use tempfile::tempdir;
|
||||
use wallet::WalletCore;
|
||||
use wallet_ffi::{
|
||||
FfiAccount, FfiAccountList, FfiBytes32, FfiPrivateAccountKeys, FfiPublicAccountKey,
|
||||
FfiTransferResult, WalletHandle, error,
|
||||
};
|
||||
|
||||
unsafe extern "C" {
|
||||
fn wallet_ffi_create_new(
|
||||
config_path: *const c_char,
|
||||
storage_path: *const c_char,
|
||||
password: *const c_char,
|
||||
) -> *mut WalletHandle;
|
||||
|
||||
fn wallet_ffi_destroy(handle: *mut WalletHandle);
|
||||
|
||||
fn wallet_ffi_create_account_public(
|
||||
handle: *mut WalletHandle,
|
||||
out_account_id: *mut FfiBytes32,
|
||||
) -> error::WalletFfiError;
|
||||
|
||||
fn wallet_ffi_create_account_private(
|
||||
handle: *mut WalletHandle,
|
||||
out_account_id: *mut FfiBytes32,
|
||||
) -> error::WalletFfiError;
|
||||
|
||||
fn wallet_ffi_list_accounts(
|
||||
handle: *mut WalletHandle,
|
||||
out_list: *mut FfiAccountList,
|
||||
) -> error::WalletFfiError;
|
||||
|
||||
fn wallet_ffi_free_account_list(list: *mut FfiAccountList);
|
||||
|
||||
fn wallet_ffi_get_balance(
|
||||
handle: *mut WalletHandle,
|
||||
account_id: *const FfiBytes32,
|
||||
is_public: bool,
|
||||
out_balance: *mut [u8; 16],
|
||||
) -> error::WalletFfiError;
|
||||
|
||||
fn wallet_ffi_get_account_public(
|
||||
handle: *mut WalletHandle,
|
||||
account_id: *const FfiBytes32,
|
||||
out_account: *mut FfiAccount,
|
||||
) -> error::WalletFfiError;
|
||||
|
||||
fn wallet_ffi_free_account_data(account: *mut FfiAccount);
|
||||
|
||||
fn wallet_ffi_get_public_account_key(
|
||||
handle: *mut WalletHandle,
|
||||
account_id: *const FfiBytes32,
|
||||
out_public_key: *mut FfiPublicAccountKey,
|
||||
) -> error::WalletFfiError;
|
||||
|
||||
fn wallet_ffi_get_private_account_keys(
|
||||
handle: *mut WalletHandle,
|
||||
account_id: *const FfiBytes32,
|
||||
out_keys: *mut FfiPrivateAccountKeys,
|
||||
) -> error::WalletFfiError;
|
||||
|
||||
fn wallet_ffi_free_private_account_keys(keys: *mut FfiPrivateAccountKeys);
|
||||
|
||||
fn wallet_ffi_account_id_to_base58(account_id: *const FfiBytes32) -> *mut std::ffi::c_char;
|
||||
|
||||
fn wallet_ffi_free_string(ptr: *mut c_char);
|
||||
|
||||
fn wallet_ffi_account_id_from_base58(
|
||||
base58_str: *const std::ffi::c_char,
|
||||
out_account_id: *mut FfiBytes32,
|
||||
) -> error::WalletFfiError;
|
||||
|
||||
fn wallet_ffi_transfer_public(
|
||||
handle: *mut WalletHandle,
|
||||
from: *const FfiBytes32,
|
||||
to: *const FfiBytes32,
|
||||
amount: *const [u8; 16],
|
||||
out_result: *mut FfiTransferResult,
|
||||
) -> error::WalletFfiError;
|
||||
|
||||
fn wallet_ffi_free_transfer_result(result: *mut FfiTransferResult);
|
||||
|
||||
fn wallet_ffi_register_public_account(
|
||||
handle: *mut WalletHandle,
|
||||
account_id: *const FfiBytes32,
|
||||
out_result: *mut FfiTransferResult,
|
||||
) -> error::WalletFfiError;
|
||||
}
|
||||
|
||||
fn new_wallet_ffi_with_test_context_config(ctx: &BlockingTestContext) -> *mut WalletHandle {
|
||||
let tempdir = tempfile::tempdir().unwrap();
|
||||
let config_path = tempdir.path().join("wallet_config.json");
|
||||
let storage_path = tempdir.path().join("storage.json");
|
||||
let mut config = ctx.ctx.wallet().config().to_owned();
|
||||
if let Some(config_overrides) = ctx.ctx.wallet().config_overrides().clone() {
|
||||
config.apply_overrides(config_overrides);
|
||||
}
|
||||
let mut file = std::fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(true)
|
||||
.open(&config_path)
|
||||
.unwrap();
|
||||
|
||||
let config_with_overrides_serialized = serde_json::to_vec_pretty(&config).unwrap();
|
||||
|
||||
file.write_all(&config_with_overrides_serialized).unwrap();
|
||||
|
||||
let config_path = CString::new(config_path.to_str().unwrap()).unwrap();
|
||||
let storage_path = CString::new(storage_path.to_str().unwrap()).unwrap();
|
||||
let password = CString::new(ctx.ctx.wallet_password()).unwrap();
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_create_new(
|
||||
config_path.as_ptr(),
|
||||
storage_path.as_ptr(),
|
||||
password.as_ptr(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn new_wallet_ffi_with_default_config(password: &str) -> *mut WalletHandle {
|
||||
let tempdir = tempdir().unwrap();
|
||||
let config_path = tempdir.path().join("wallet_config.json");
|
||||
let storage_path = tempdir.path().join("storage.json");
|
||||
let config_path_c = CString::new(config_path.to_str().unwrap()).unwrap();
|
||||
let storage_path_c = CString::new(storage_path.to_str().unwrap()).unwrap();
|
||||
let password = CString::new(password).unwrap();
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_create_new(
|
||||
config_path_c.as_ptr(),
|
||||
storage_path_c.as_ptr(),
|
||||
password.as_ptr(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn new_wallet_rust_with_default_config(password: &str) -> WalletCore {
|
||||
let tempdir = tempdir().unwrap();
|
||||
let config_path = tempdir.path().join("wallet_config.json");
|
||||
let storage_path = tempdir.path().join("storage.json");
|
||||
|
||||
WalletCore::new_init_storage(
|
||||
config_path.to_path_buf(),
|
||||
storage_path.to_path_buf(),
|
||||
None,
|
||||
password.to_string(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_create_public_accounts() {
|
||||
let password = "password_for_tests";
|
||||
let n_accounts = 10;
|
||||
// First `n_accounts` public accounts created with Rust wallet
|
||||
let new_public_account_ids_rust = {
|
||||
let mut account_ids = Vec::new();
|
||||
|
||||
let mut wallet_rust = new_wallet_rust_with_default_config(password);
|
||||
for _ in 0..n_accounts {
|
||||
let account_id = wallet_rust.create_new_account_public(None).0;
|
||||
account_ids.push(*account_id.value());
|
||||
}
|
||||
account_ids
|
||||
};
|
||||
|
||||
// First `n_accounts` public accounts created with wallet FFI
|
||||
let new_public_account_ids_ffi = unsafe {
|
||||
let mut account_ids = Vec::new();
|
||||
|
||||
let wallet_ffi_handle = new_wallet_ffi_with_default_config(password);
|
||||
for _ in 0..n_accounts {
|
||||
let mut out_account_id = FfiBytes32::from_bytes([0; 32]);
|
||||
wallet_ffi_create_account_public(
|
||||
wallet_ffi_handle,
|
||||
(&mut out_account_id) as *mut FfiBytes32,
|
||||
);
|
||||
account_ids.push(out_account_id.data);
|
||||
}
|
||||
wallet_ffi_destroy(wallet_ffi_handle);
|
||||
account_ids
|
||||
};
|
||||
|
||||
assert_eq!(new_public_account_ids_ffi, new_public_account_ids_rust);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_create_private_accounts() {
|
||||
let password = "password_for_tests";
|
||||
let n_accounts = 10;
|
||||
// First `n_accounts` private accounts created with Rust wallet
|
||||
let new_private_account_ids_rust = {
|
||||
let mut account_ids = Vec::new();
|
||||
|
||||
let mut wallet_rust = new_wallet_rust_with_default_config(password);
|
||||
for _ in 0..n_accounts {
|
||||
let account_id = wallet_rust.create_new_account_private(None).0;
|
||||
account_ids.push(*account_id.value());
|
||||
}
|
||||
account_ids
|
||||
};
|
||||
|
||||
// First `n_accounts` private accounts created with wallet FFI
|
||||
let new_private_account_ids_ffi = unsafe {
|
||||
let mut account_ids = Vec::new();
|
||||
|
||||
let wallet_ffi_handle = new_wallet_ffi_with_default_config(password);
|
||||
for _ in 0..n_accounts {
|
||||
let mut out_account_id = FfiBytes32::from_bytes([0; 32]);
|
||||
wallet_ffi_create_account_private(
|
||||
wallet_ffi_handle,
|
||||
(&mut out_account_id) as *mut FfiBytes32,
|
||||
);
|
||||
account_ids.push(out_account_id.data);
|
||||
}
|
||||
wallet_ffi_destroy(wallet_ffi_handle);
|
||||
account_ids
|
||||
};
|
||||
|
||||
assert_eq!(new_private_account_ids_ffi, new_private_account_ids_rust)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_list_accounts() {
|
||||
let password = "password_for_tests";
|
||||
|
||||
// Create the wallet FFI
|
||||
let wallet_ffi_handle = unsafe {
|
||||
let handle = new_wallet_ffi_with_default_config(password);
|
||||
// Create 5 public accounts and 5 private accounts
|
||||
for _ in 0..5 {
|
||||
let mut out_account_id = FfiBytes32::from_bytes([0; 32]);
|
||||
wallet_ffi_create_account_public(handle, (&mut out_account_id) as *mut FfiBytes32);
|
||||
wallet_ffi_create_account_private(handle, (&mut out_account_id) as *mut FfiBytes32);
|
||||
}
|
||||
|
||||
handle
|
||||
};
|
||||
|
||||
// Create the wallet Rust
|
||||
let wallet_rust = {
|
||||
let mut wallet = new_wallet_rust_with_default_config(password);
|
||||
// Create 5 public accounts and 5 private accounts
|
||||
for _ in 0..5 {
|
||||
wallet.create_new_account_public(None);
|
||||
wallet.create_new_account_private(None);
|
||||
}
|
||||
wallet
|
||||
};
|
||||
|
||||
// Get the account list with FFI method
|
||||
let mut wallet_ffi_account_list = unsafe {
|
||||
let mut out_list = FfiAccountList::default();
|
||||
wallet_ffi_list_accounts(wallet_ffi_handle, (&mut out_list) as *mut FfiAccountList);
|
||||
out_list
|
||||
};
|
||||
|
||||
let wallet_rust_account_ids = wallet_rust
|
||||
.storage()
|
||||
.user_data
|
||||
.account_ids()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
// Assert same number of elements between Rust and FFI result
|
||||
assert_eq!(wallet_rust_account_ids.len(), wallet_ffi_account_list.count);
|
||||
|
||||
let wallet_ffi_account_list_slice = unsafe {
|
||||
core::slice::from_raw_parts(
|
||||
wallet_ffi_account_list.entries,
|
||||
wallet_ffi_account_list.count,
|
||||
)
|
||||
};
|
||||
|
||||
// Assert same account ids between Rust and FFI result
|
||||
assert_eq!(
|
||||
wallet_rust_account_ids
|
||||
.iter()
|
||||
.map(|id| id.value())
|
||||
.collect::<HashSet<_>>(),
|
||||
wallet_ffi_account_list_slice
|
||||
.iter()
|
||||
.map(|entry| &entry.account_id.data)
|
||||
.collect::<HashSet<_>>()
|
||||
);
|
||||
|
||||
// Assert `is_pub` flag is correct in the FFI result
|
||||
for entry in wallet_ffi_account_list_slice.iter() {
|
||||
let account_id = AccountId::new(entry.account_id.data);
|
||||
let is_pub_default_in_rust_wallet = wallet_rust
|
||||
.storage()
|
||||
.user_data
|
||||
.default_pub_account_signing_keys
|
||||
.contains_key(&account_id);
|
||||
let is_pub_key_tree_wallet_rust = wallet_rust
|
||||
.storage()
|
||||
.user_data
|
||||
.public_key_tree
|
||||
.account_id_map
|
||||
.contains_key(&account_id);
|
||||
|
||||
let is_public_in_rust_wallet = is_pub_default_in_rust_wallet || is_pub_key_tree_wallet_rust;
|
||||
|
||||
assert_eq!(entry.is_public, is_public_in_rust_wallet);
|
||||
}
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_free_account_list((&mut wallet_ffi_account_list) as *mut FfiAccountList);
|
||||
wallet_ffi_destroy(wallet_ffi_handle);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_get_balance_public() -> Result<()> {
|
||||
let ctx = BlockingTestContext::new()?;
|
||||
let account_id: AccountId = ACC_SENDER.parse().unwrap();
|
||||
let wallet_ffi_handle = new_wallet_ffi_with_test_context_config(&ctx);
|
||||
|
||||
let balance = unsafe {
|
||||
let mut out_balance: [u8; 16] = [0; 16];
|
||||
let ffi_account_id = FfiBytes32::from(&account_id);
|
||||
let _result = wallet_ffi_get_balance(
|
||||
wallet_ffi_handle,
|
||||
(&ffi_account_id) as *const FfiBytes32,
|
||||
true,
|
||||
(&mut out_balance) as *mut [u8; 16],
|
||||
);
|
||||
u128::from_le_bytes(out_balance)
|
||||
};
|
||||
assert_eq!(balance, 10000);
|
||||
|
||||
info!("Successfully retrieved account balance");
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_destroy(wallet_ffi_handle);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_get_account_public() -> Result<()> {
|
||||
let ctx = BlockingTestContext::new()?;
|
||||
let account_id: AccountId = ACC_SENDER.parse().unwrap();
|
||||
let wallet_ffi_handle = new_wallet_ffi_with_test_context_config(&ctx);
|
||||
let mut out_account = FfiAccount::default();
|
||||
|
||||
let account: Account = unsafe {
|
||||
let ffi_account_id = FfiBytes32::from(&account_id);
|
||||
let _result = wallet_ffi_get_account_public(
|
||||
wallet_ffi_handle,
|
||||
(&ffi_account_id) as *const FfiBytes32,
|
||||
(&mut out_account) as *mut FfiAccount,
|
||||
);
|
||||
(&out_account).try_into().unwrap()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
account.program_owner,
|
||||
Program::authenticated_transfer_program().id()
|
||||
);
|
||||
assert_eq!(account.balance, 10000);
|
||||
assert!(account.data.is_empty());
|
||||
assert_eq!(account.nonce, 0);
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_free_account_data((&mut out_account) as *mut FfiAccount);
|
||||
wallet_ffi_destroy(wallet_ffi_handle);
|
||||
}
|
||||
|
||||
info!("Successfully retrieved account with correct details");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_get_public_account_keys() -> Result<()> {
|
||||
let ctx = BlockingTestContext::new()?;
|
||||
let account_id: AccountId = ACC_SENDER.parse().unwrap();
|
||||
let wallet_ffi_handle = new_wallet_ffi_with_test_context_config(&ctx);
|
||||
let mut out_key = FfiPublicAccountKey::default();
|
||||
|
||||
let key: PublicKey = unsafe {
|
||||
let ffi_account_id = FfiBytes32::from(&account_id);
|
||||
let _result = wallet_ffi_get_public_account_key(
|
||||
wallet_ffi_handle,
|
||||
(&ffi_account_id) as *const FfiBytes32,
|
||||
(&mut out_key) as *mut FfiPublicAccountKey,
|
||||
);
|
||||
(&out_key).try_into().unwrap()
|
||||
};
|
||||
|
||||
let expected_key = {
|
||||
let private_key = ctx
|
||||
.ctx
|
||||
.wallet()
|
||||
.get_account_public_signing_key(&account_id)
|
||||
.unwrap();
|
||||
PublicKey::new_from_private_key(private_key)
|
||||
};
|
||||
|
||||
assert_eq!(key, expected_key);
|
||||
|
||||
info!("Successfully retrieved account key");
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_destroy(wallet_ffi_handle);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_get_private_account_keys() -> Result<()> {
|
||||
let ctx = BlockingTestContext::new()?;
|
||||
let account_id: AccountId = ACC_SENDER_PRIVATE.parse().unwrap();
|
||||
let wallet_ffi_handle = new_wallet_ffi_with_test_context_config(&ctx);
|
||||
let mut keys = FfiPrivateAccountKeys::default();
|
||||
|
||||
unsafe {
|
||||
let ffi_account_id = FfiBytes32::from(&account_id);
|
||||
let _result = wallet_ffi_get_private_account_keys(
|
||||
wallet_ffi_handle,
|
||||
(&ffi_account_id) as *const FfiBytes32,
|
||||
(&mut keys) as *mut FfiPrivateAccountKeys,
|
||||
);
|
||||
};
|
||||
|
||||
let key_chain = &ctx
|
||||
.ctx
|
||||
.wallet()
|
||||
.storage()
|
||||
.user_data
|
||||
.get_private_account(&account_id)
|
||||
.unwrap()
|
||||
.0;
|
||||
|
||||
let expected_npk = &key_chain.nullifer_public_key;
|
||||
let expected_ivk = &key_chain.incoming_viewing_public_key;
|
||||
|
||||
assert_eq!(&keys.npk(), expected_npk);
|
||||
assert_eq!(&keys.ivk().unwrap(), expected_ivk);
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_free_private_account_keys((&mut keys) as *mut FfiPrivateAccountKeys);
|
||||
wallet_ffi_destroy(wallet_ffi_handle);
|
||||
}
|
||||
|
||||
info!("Successfully retrieved account keys");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_account_id_to_base58() {
|
||||
let account_id_str = ACC_SENDER;
|
||||
let account_id: AccountId = account_id_str.parse().unwrap();
|
||||
let ffi_bytes: FfiBytes32 = (&account_id).into();
|
||||
let ptr = unsafe { wallet_ffi_account_id_to_base58((&ffi_bytes) as *const FfiBytes32) };
|
||||
|
||||
let ffi_result = unsafe { CStr::from_ptr(ptr).to_str().unwrap() };
|
||||
|
||||
assert_eq!(account_id_str, ffi_result);
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_free_string(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_base58_to_account_id() {
|
||||
let account_id_str = ACC_SENDER;
|
||||
let account_id_c_str = CString::new(account_id_str).unwrap();
|
||||
let account_id: AccountId = unsafe {
|
||||
let mut out_account_id_bytes = FfiBytes32::default();
|
||||
wallet_ffi_account_id_from_base58(
|
||||
account_id_c_str.as_ptr(),
|
||||
(&mut out_account_id_bytes) as *mut FfiBytes32,
|
||||
);
|
||||
out_account_id_bytes.into()
|
||||
};
|
||||
|
||||
let expected_account_id = account_id_str.parse().unwrap();
|
||||
|
||||
assert_eq!(account_id, expected_account_id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_init_public_account_auth_transfer() -> Result<()> {
|
||||
let ctx = BlockingTestContext::new().unwrap();
|
||||
let wallet_ffi_handle = new_wallet_ffi_with_test_context_config(&ctx);
|
||||
|
||||
// Create a new uninitialized public account
|
||||
let mut out_account_id = FfiBytes32::from_bytes([0; 32]);
|
||||
unsafe {
|
||||
wallet_ffi_create_account_public(
|
||||
wallet_ffi_handle,
|
||||
(&mut out_account_id) as *mut FfiBytes32,
|
||||
);
|
||||
}
|
||||
|
||||
// Check its program owner is the default program id
|
||||
let account: Account = unsafe {
|
||||
let mut out_account = FfiAccount::default();
|
||||
let _result = wallet_ffi_get_account_public(
|
||||
wallet_ffi_handle,
|
||||
(&out_account_id) as *const FfiBytes32,
|
||||
(&mut out_account) as *mut FfiAccount,
|
||||
);
|
||||
(&out_account).try_into().unwrap()
|
||||
};
|
||||
assert_eq!(account.program_owner, DEFAULT_PROGRAM_ID);
|
||||
|
||||
// Call the init funciton
|
||||
let mut transfer_result = FfiTransferResult::default();
|
||||
unsafe {
|
||||
wallet_ffi_register_public_account(
|
||||
wallet_ffi_handle,
|
||||
(&out_account_id) as *const FfiBytes32,
|
||||
(&mut transfer_result) as *mut FfiTransferResult,
|
||||
);
|
||||
}
|
||||
|
||||
info!("Waiting for next block creation");
|
||||
std::thread::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS));
|
||||
|
||||
// Check that the program owner is now the authenticated transfer program
|
||||
let account: Account = unsafe {
|
||||
let mut out_account = FfiAccount::default();
|
||||
let _result = wallet_ffi_get_account_public(
|
||||
wallet_ffi_handle,
|
||||
(&out_account_id) as *const FfiBytes32,
|
||||
(&mut out_account) as *mut FfiAccount,
|
||||
);
|
||||
(&out_account).try_into().unwrap()
|
||||
};
|
||||
assert_eq!(
|
||||
account.program_owner,
|
||||
Program::authenticated_transfer_program().id()
|
||||
);
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_free_transfer_result((&mut transfer_result) as *mut FfiTransferResult);
|
||||
wallet_ffi_destroy(wallet_ffi_handle);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_wallet_ffi_transfer_public() -> Result<()> {
|
||||
let ctx = BlockingTestContext::new().unwrap();
|
||||
let wallet_ffi_handle = new_wallet_ffi_with_test_context_config(&ctx);
|
||||
let from: FfiBytes32 = (&ACC_SENDER.parse::<AccountId>().unwrap()).into();
|
||||
let to: FfiBytes32 = (&ACC_RECEIVER.parse::<AccountId>().unwrap()).into();
|
||||
let amount: [u8; 16] = 100u128.to_le_bytes();
|
||||
|
||||
let mut transfer_result = FfiTransferResult::default();
|
||||
unsafe {
|
||||
wallet_ffi_transfer_public(
|
||||
wallet_ffi_handle,
|
||||
(&from) as *const FfiBytes32,
|
||||
(&to) as *const FfiBytes32,
|
||||
(&amount) as *const [u8; 16],
|
||||
(&mut transfer_result) as *mut FfiTransferResult,
|
||||
);
|
||||
}
|
||||
|
||||
info!("Waiting for next block creation");
|
||||
std::thread::sleep(Duration::from_secs(TIME_TO_WAIT_FOR_BLOCK_SECONDS));
|
||||
|
||||
let from_balance = unsafe {
|
||||
let mut out_balance: [u8; 16] = [0; 16];
|
||||
let _result = wallet_ffi_get_balance(
|
||||
wallet_ffi_handle,
|
||||
(&from) as *const FfiBytes32,
|
||||
true,
|
||||
(&mut out_balance) as *mut [u8; 16],
|
||||
);
|
||||
u128::from_le_bytes(out_balance)
|
||||
};
|
||||
|
||||
let to_balance = unsafe {
|
||||
let mut out_balance: [u8; 16] = [0; 16];
|
||||
let _result = wallet_ffi_get_balance(
|
||||
wallet_ffi_handle,
|
||||
(&to) as *const FfiBytes32,
|
||||
true,
|
||||
(&mut out_balance) as *mut [u8; 16],
|
||||
);
|
||||
u128::from_le_bytes(out_balance)
|
||||
};
|
||||
|
||||
assert_eq!(from_balance, 9900);
|
||||
assert_eq!(to_balance, 20100);
|
||||
|
||||
unsafe {
|
||||
wallet_ffi_free_transfer_result((&mut transfer_result) as *mut FfiTransferResult);
|
||||
wallet_ffi_destroy(wallet_ffi_handle);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@ -2,6 +2,7 @@
|
||||
name = "key_protocol"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "mempool"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
tokio = { workspace = true, features = ["sync"] }
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "nssa"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa_core = { workspace = true, features = ["host"] }
|
||||
@ -23,7 +24,9 @@ risc0-build = "3.0.3"
|
||||
risc0-binfmt = "3.0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
token_core.workspace = true
|
||||
test_program_methods.workspace = true
|
||||
|
||||
env_logger.workspace = true
|
||||
hex-literal = "1.0.0"
|
||||
test-case = "3.3.1"
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "nssa_core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
risc0-zkvm.workspace = true
|
||||
|
||||
@ -20,8 +20,7 @@ pub struct ProgramInput<T> {
|
||||
/// Each program can derive up to `2^256` unique account IDs by choosing different
|
||||
/// seeds. PDAs allow programs to control namespaced account identifiers without
|
||||
/// collisions between programs.
|
||||
#[derive(Serialize, Deserialize, Clone, Eq, PartialEq)]
|
||||
#[cfg_attr(any(feature = "host", test), derive(Debug))]
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
|
||||
pub struct PdaSeed([u8; 32]);
|
||||
|
||||
impl PdaSeed {
|
||||
@ -65,23 +64,44 @@ impl From<(&ProgramId, &PdaSeed)> for AccountId {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone, PartialEq, Eq)]
|
||||
#[cfg_attr(any(feature = "host", test), derive(Debug,))]
|
||||
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
|
||||
pub struct ChainedCall {
|
||||
/// The program ID of the program to execute
|
||||
pub program_id: ProgramId,
|
||||
pub pre_states: Vec<AccountWithMetadata>,
|
||||
/// The instruction data to pass
|
||||
pub instruction_data: InstructionData,
|
||||
pub pre_states: Vec<AccountWithMetadata>,
|
||||
pub pda_seeds: Vec<PdaSeed>,
|
||||
}
|
||||
|
||||
impl ChainedCall {
|
||||
/// Creates a new chained call serializing the given instruction.
|
||||
pub fn new<I: Serialize>(
|
||||
program_id: ProgramId,
|
||||
pre_states: Vec<AccountWithMetadata>,
|
||||
instruction: &I,
|
||||
) -> Self {
|
||||
Self {
|
||||
program_id,
|
||||
pre_states,
|
||||
instruction_data: risc0_zkvm::serde::to_vec(instruction)
|
||||
.expect("Serialization to Vec<u32> should not fail"),
|
||||
pda_seeds: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_pda_seeds(mut self, pda_seeds: Vec<PdaSeed>) -> Self {
|
||||
self.pda_seeds = pda_seeds;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents the final state of an `Account` after a program execution.
|
||||
/// A post state may optionally request that the executing program
|
||||
/// becomes the owner of the account (a “claim”). This is used to signal
|
||||
/// that the program intends to take ownership of the account.
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
#[cfg_attr(any(feature = "host", test), derive(Debug, PartialEq, Eq))]
|
||||
#[derive(Debug, Serialize, Deserialize, Clone)]
|
||||
#[cfg_attr(any(feature = "host", test), derive(PartialEq, Eq))]
|
||||
pub struct AccountPostState {
|
||||
account: Account,
|
||||
claim: bool,
|
||||
|
||||
@ -14,7 +14,7 @@ mod state;
|
||||
|
||||
pub use nssa_core::{
|
||||
SharedSecretKey,
|
||||
account::{Account, AccountId},
|
||||
account::{Account, AccountId, Data},
|
||||
encryption::EphemeralPublicKey,
|
||||
program::ProgramId,
|
||||
};
|
||||
|
||||
@ -317,6 +317,7 @@ pub mod tests {
|
||||
encryption::{EphemeralPublicKey, IncomingViewingPublicKey, Scalar},
|
||||
program::{PdaSeed, ProgramId},
|
||||
};
|
||||
use token_core::{TokenDefinition, TokenHolding};
|
||||
|
||||
use crate::{
|
||||
PublicKey, PublicTransaction, V02State,
|
||||
@ -2328,53 +2329,6 @@ pub mod tests {
|
||||
));
|
||||
}
|
||||
|
||||
// TODO: repeated code needs to be cleaned up
|
||||
// from token.rs (also repeated in amm.rs)
|
||||
const TOKEN_DEFINITION_DATA_SIZE: usize = 55;
|
||||
|
||||
const TOKEN_HOLDING_DATA_SIZE: usize = 49;
|
||||
|
||||
struct TokenDefinition {
|
||||
account_type: u8,
|
||||
name: [u8; 6],
|
||||
total_supply: u128,
|
||||
metadata_id: AccountId,
|
||||
}
|
||||
|
||||
struct TokenHolding {
|
||||
account_type: u8,
|
||||
definition_id: AccountId,
|
||||
balance: u128,
|
||||
}
|
||||
impl TokenDefinition {
|
||||
fn into_data(self) -> Data {
|
||||
let mut bytes = Vec::<u8>::new();
|
||||
bytes.extend_from_slice(&[self.account_type]);
|
||||
bytes.extend_from_slice(&self.name);
|
||||
bytes.extend_from_slice(&self.total_supply.to_le_bytes());
|
||||
bytes.extend_from_slice(&self.metadata_id.to_bytes());
|
||||
|
||||
if bytes.len() != TOKEN_DEFINITION_DATA_SIZE {
|
||||
panic!("Invalid Token Definition data");
|
||||
}
|
||||
|
||||
Data::try_from(bytes).expect("Token definition data size must fit into data")
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenHolding {
|
||||
fn into_data(self) -> Data {
|
||||
let mut bytes = [0; TOKEN_HOLDING_DATA_SIZE];
|
||||
bytes[0] = self.account_type;
|
||||
bytes[1..33].copy_from_slice(&self.definition_id.to_bytes());
|
||||
bytes[33..].copy_from_slice(&self.balance.to_le_bytes());
|
||||
bytes
|
||||
.to_vec()
|
||||
.try_into()
|
||||
.expect("33 bytes should fit into Data")
|
||||
}
|
||||
}
|
||||
|
||||
// TODO repeated code should ultimately be removed;
|
||||
fn compute_pool_pda(
|
||||
amm_program_id: ProgramId,
|
||||
@ -2747,8 +2701,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::user_token_a_holding_init(),
|
||||
}),
|
||||
@ -2760,8 +2713,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::user_token_b_holding_init(),
|
||||
}),
|
||||
@ -2793,11 +2745,10 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenDefinition::into_data(TokenDefinition {
|
||||
account_type: 0u8,
|
||||
name: [1u8; 6],
|
||||
data: Data::from(&TokenDefinition::Fungible {
|
||||
name: String::from("test"),
|
||||
total_supply: BalanceForTests::token_a_supply(),
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
metadata_id: None,
|
||||
}),
|
||||
nonce: 0,
|
||||
}
|
||||
@ -2807,11 +2758,10 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenDefinition::into_data(TokenDefinition {
|
||||
account_type: 0u8,
|
||||
name: [1u8; 6],
|
||||
data: Data::from(&TokenDefinition::Fungible {
|
||||
name: String::from("test"),
|
||||
total_supply: BalanceForTests::token_b_supply(),
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
metadata_id: None,
|
||||
}),
|
||||
nonce: 0,
|
||||
}
|
||||
@ -2821,11 +2771,10 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenDefinition::into_data(TokenDefinition {
|
||||
account_type: 0u8,
|
||||
name: [1u8; 6],
|
||||
data: Data::from(&TokenDefinition::Fungible {
|
||||
name: String::from("LP Token"),
|
||||
total_supply: BalanceForTests::token_lp_supply(),
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
metadata_id: None,
|
||||
}),
|
||||
nonce: 0,
|
||||
}
|
||||
@ -2835,8 +2784,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::vault_a_balance_init(),
|
||||
}),
|
||||
@ -2848,8 +2796,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::vault_b_balance_init(),
|
||||
}),
|
||||
@ -2861,8 +2808,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_lp_definition_id(),
|
||||
balance: BalanceForTests::user_token_lp_holding_init(),
|
||||
}),
|
||||
@ -2874,8 +2820,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::vault_a_balance_swap_1(),
|
||||
}),
|
||||
@ -2887,8 +2832,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::vault_b_balance_swap_1(),
|
||||
}),
|
||||
@ -2920,8 +2864,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::user_token_a_holding_swap_1(),
|
||||
}),
|
||||
@ -2933,8 +2876,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::user_token_b_holding_swap_1(),
|
||||
}),
|
||||
@ -2946,8 +2888,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::vault_a_balance_swap_2(),
|
||||
}),
|
||||
@ -2959,8 +2900,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::vault_b_balance_swap_2(),
|
||||
}),
|
||||
@ -2992,8 +2932,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::user_token_a_holding_swap_2(),
|
||||
}),
|
||||
@ -3005,8 +2944,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::user_token_b_holding_swap_2(),
|
||||
}),
|
||||
@ -3018,8 +2956,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::vault_a_balance_add(),
|
||||
}),
|
||||
@ -3031,8 +2968,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::vault_b_balance_add(),
|
||||
}),
|
||||
@ -3064,8 +3000,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::user_token_a_holding_add(),
|
||||
}),
|
||||
@ -3077,8 +3012,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::user_token_b_holding_add(),
|
||||
}),
|
||||
@ -3090,8 +3024,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_lp_definition_id(),
|
||||
balance: BalanceForTests::user_token_lp_holding_add(),
|
||||
}),
|
||||
@ -3103,11 +3036,10 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenDefinition::into_data(TokenDefinition {
|
||||
account_type: 0u8,
|
||||
name: [1u8; 6],
|
||||
data: Data::from(&TokenDefinition::Fungible {
|
||||
name: String::from("LP Token"),
|
||||
total_supply: BalanceForTests::token_lp_supply_add(),
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
metadata_id: None,
|
||||
}),
|
||||
nonce: 0,
|
||||
}
|
||||
@ -3117,8 +3049,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::vault_a_balance_remove(),
|
||||
}),
|
||||
@ -3130,8 +3061,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::vault_b_balance_remove(),
|
||||
}),
|
||||
@ -3163,8 +3093,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::user_token_a_holding_remove(),
|
||||
}),
|
||||
@ -3176,8 +3105,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::user_token_b_holding_remove(),
|
||||
}),
|
||||
@ -3189,8 +3117,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_lp_definition_id(),
|
||||
balance: BalanceForTests::user_token_lp_holding_remove(),
|
||||
}),
|
||||
@ -3202,11 +3129,10 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenDefinition::into_data(TokenDefinition {
|
||||
account_type: 0u8,
|
||||
name: [1u8; 6],
|
||||
data: Data::from(&TokenDefinition::Fungible {
|
||||
name: String::from("LP Token"),
|
||||
total_supply: BalanceForTests::token_lp_supply_remove(),
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
metadata_id: None,
|
||||
}),
|
||||
nonce: 0,
|
||||
}
|
||||
@ -3216,11 +3142,10 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenDefinition::into_data(TokenDefinition {
|
||||
account_type: 0u8,
|
||||
name: [1u8; 6],
|
||||
data: Data::from(&TokenDefinition::Fungible {
|
||||
name: String::from("LP Token"),
|
||||
total_supply: 0,
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
metadata_id: None,
|
||||
}),
|
||||
nonce: 0,
|
||||
}
|
||||
@ -3230,8 +3155,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: 0,
|
||||
}),
|
||||
@ -3243,8 +3167,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: 0,
|
||||
}),
|
||||
@ -3276,8 +3199,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_a_definition_id(),
|
||||
balance: BalanceForTests::user_token_a_holding_new_definition(),
|
||||
}),
|
||||
@ -3289,8 +3211,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_b_definition_id(),
|
||||
balance: BalanceForTests::user_token_b_holding_new_definition(),
|
||||
}),
|
||||
@ -3302,8 +3223,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_lp_definition_id(),
|
||||
balance: BalanceForTests::user_token_a_holding_new_definition(),
|
||||
}),
|
||||
@ -3315,11 +3235,10 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenDefinition::into_data(TokenDefinition {
|
||||
account_type: 0u8,
|
||||
name: [1u8; 6],
|
||||
data: Data::from(&TokenDefinition::Fungible {
|
||||
name: String::from("LP Token"),
|
||||
total_supply: BalanceForTests::vault_a_balance_init(),
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
metadata_id: None,
|
||||
}),
|
||||
nonce: 0,
|
||||
}
|
||||
@ -3349,8 +3268,7 @@ pub mod tests {
|
||||
Account {
|
||||
program_owner: Program::token().id(),
|
||||
balance: 0u128,
|
||||
data: TokenHolding::into_data(TokenHolding {
|
||||
account_type: 1u8,
|
||||
data: Data::from(&TokenHolding::Fungible {
|
||||
definition_id: IdForTests::token_lp_definition_id(),
|
||||
balance: 0,
|
||||
}),
|
||||
@ -4115,13 +4033,13 @@ pub mod tests {
|
||||
let pinata_token_holding_id = AccountId::from((&pinata_token.id(), &PdaSeed::new([0; 32])));
|
||||
let winner_token_holding_id = AccountId::new([3; 32]);
|
||||
|
||||
let mut expected_winner_account_data = [0; 49];
|
||||
expected_winner_account_data[0] = 1;
|
||||
expected_winner_account_data[1..33].copy_from_slice(pinata_token_definition_id.value());
|
||||
expected_winner_account_data[33..].copy_from_slice(&150u128.to_le_bytes());
|
||||
let expected_winner_account_holding = token_core::TokenHolding::Fungible {
|
||||
definition_id: pinata_token_definition_id,
|
||||
balance: 150,
|
||||
};
|
||||
let expected_winner_token_holding_post = Account {
|
||||
program_owner: token.id(),
|
||||
data: expected_winner_account_data.to_vec().try_into().unwrap(),
|
||||
data: Data::from(&expected_winner_account_holding),
|
||||
..Account::default()
|
||||
};
|
||||
|
||||
@ -4131,10 +4049,10 @@ pub mod tests {
|
||||
// Execution of the token program to create new token for the pinata token
|
||||
// definition and supply accounts
|
||||
let total_supply: u128 = 10_000_000;
|
||||
// instruction: [0x00 || total_supply (little-endian 16 bytes) || name (6 bytes)]
|
||||
let mut instruction = vec![0; 23];
|
||||
instruction[1..17].copy_from_slice(&total_supply.to_le_bytes());
|
||||
instruction[17..].copy_from_slice(b"PINATA");
|
||||
let instruction = token_core::Instruction::NewFungibleDefinition {
|
||||
name: String::from("PINATA"),
|
||||
total_supply,
|
||||
};
|
||||
let message = public_transaction::Message::try_new(
|
||||
token.id(),
|
||||
vec![pinata_token_definition_id, pinata_token_holding_id],
|
||||
@ -4146,9 +4064,8 @@ pub mod tests {
|
||||
let tx = PublicTransaction::new(message, witness_set);
|
||||
state.transition_from_public_transaction(&tx).unwrap();
|
||||
|
||||
// Execution of the token program transfer just to initialize the winner token account
|
||||
let mut instruction = vec![0; 23];
|
||||
instruction[0] = 2;
|
||||
// Execution of winner's token holding account initialization
|
||||
let instruction = token_core::Instruction::InitializeAccount;
|
||||
let message = public_transaction::Message::try_new(
|
||||
token.id(),
|
||||
vec![pinata_token_definition_id, winner_token_holding_id],
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "program_methods"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
risc0-build.workspace = true
|
||||
|
||||
@ -2,9 +2,11 @@
|
||||
name = "programs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa_core.workspace = true
|
||||
|
||||
token_core.workspace = true
|
||||
token_program.workspace = true
|
||||
risc0-zkvm.workspace = true
|
||||
serde = { workspace = true, default-features = false }
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -5,10 +5,7 @@ use nssa_core::{
|
||||
write_nssa_outputs_with_chained_call,
|
||||
},
|
||||
};
|
||||
use risc0_zkvm::{
|
||||
serde::to_vec,
|
||||
sha::{Impl, Sha256},
|
||||
};
|
||||
use risc0_zkvm::sha::{Impl, Sha256};
|
||||
|
||||
const PRIZE: u128 = 150;
|
||||
|
||||
@ -82,23 +79,21 @@ fn main() {
|
||||
let winner_token_holding_post = winner_token_holding.account.clone();
|
||||
pinata_definition_post.data = data.next_data();
|
||||
|
||||
let mut instruction_data = vec![0; 23];
|
||||
instruction_data[0] = 1;
|
||||
instruction_data[1..17].copy_from_slice(&PRIZE.to_le_bytes());
|
||||
|
||||
// Flip authorization to true for chained call
|
||||
let mut pinata_token_holding_for_chain_call = pinata_token_holding.clone();
|
||||
pinata_token_holding_for_chain_call.is_authorized = true;
|
||||
|
||||
let chained_calls = vec![ChainedCall {
|
||||
program_id: pinata_token_holding_post.program_owner,
|
||||
instruction_data: to_vec(&instruction_data).unwrap(),
|
||||
pre_states: vec![
|
||||
let chained_call = ChainedCall::new(
|
||||
pinata_token_holding_post.program_owner,
|
||||
vec![
|
||||
pinata_token_holding_for_chain_call,
|
||||
winner_token_holding.clone(),
|
||||
],
|
||||
pda_seeds: vec![PdaSeed::new([0; 32])],
|
||||
}];
|
||||
&token_core::Instruction::Transfer {
|
||||
amount_to_transfer: PRIZE,
|
||||
},
|
||||
)
|
||||
.with_pda_seeds(vec![PdaSeed::new([0; 32])]);
|
||||
|
||||
write_nssa_outputs_with_chained_call(
|
||||
instruction_words,
|
||||
@ -112,6 +107,6 @@ fn main() {
|
||||
AccountPostState::new(pinata_token_holding_post),
|
||||
AccountPostState::new(winner_token_holding_post),
|
||||
],
|
||||
chained_calls,
|
||||
vec![chained_call],
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
9
programs/token/Cargo.toml
Normal file
9
programs/token/Cargo.toml
Normal file
@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "token_program"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa_core.workspace = true
|
||||
token_core.workspace = true
|
||||
10
programs/token/core/Cargo.toml
Normal file
10
programs/token/core/Cargo.toml
Normal file
@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "token_core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa_core.workspace = true
|
||||
serde.workspace = true
|
||||
borsh.workspace = true
|
||||
241
programs/token/core/src/lib.rs
Normal file
241
programs/token/core/src/lib.rs
Normal file
@ -0,0 +1,241 @@
|
||||
//! This crate contains core data structures and utilities for the Token Program.
|
||||
|
||||
use borsh::{BorshDeserialize, BorshSerialize};
|
||||
use nssa_core::account::{AccountId, Data};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Token Program Instruction.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub enum Instruction {
|
||||
/// Transfer tokens from sender to recipient.
|
||||
///
|
||||
/// Required accounts:
|
||||
/// - Sender's Token Holding account (authorized),
|
||||
/// - Recipient's Token Holding account.
|
||||
Transfer { amount_to_transfer: u128 },
|
||||
|
||||
/// Create a new fungible token definition without metadata.
|
||||
///
|
||||
/// Required accounts:
|
||||
/// - Token Definition account (uninitialized),
|
||||
/// - Token Holding account (uninitialized).
|
||||
NewFungibleDefinition { name: String, total_supply: u128 },
|
||||
|
||||
/// Create a new fungible or non-fungible token definition with metadata.
|
||||
///
|
||||
/// Required accounts:
|
||||
/// - Token Definition account (uninitialized),
|
||||
/// - Token Holding account (uninitialized),
|
||||
/// - Token Metadata account (uninitialized).
|
||||
NewDefinitionWithMetadata {
|
||||
new_definition: NewTokenDefinition,
|
||||
/// Boxed to avoid large enum variant size
|
||||
metadata: Box<NewTokenMetadata>,
|
||||
},
|
||||
|
||||
/// Initialize a token holding account for a given token definition.
|
||||
///
|
||||
/// Required accounts:
|
||||
/// - Token Definition account (initialized),
|
||||
/// - Token Holding account (uninitialized),
|
||||
InitializeAccount,
|
||||
|
||||
/// Burn tokens from the holder's account.
|
||||
///
|
||||
/// Required accounts:
|
||||
/// - Token Definition account (initialized),
|
||||
/// - Token Holding account (authorized).
|
||||
Burn { amount_to_burn: u128 },
|
||||
|
||||
/// Mint new tokens to the holder's account.
|
||||
///
|
||||
/// Required accounts:
|
||||
/// - Token Definition account (authorized),
|
||||
/// - Token Holding account (uninitialized or initialized).
|
||||
Mint { amount_to_mint: u128 },
|
||||
|
||||
/// Print a new NFT from the master copy.
|
||||
///
|
||||
/// Required accounts:
|
||||
/// - NFT Master Token Holding account (authorized),
|
||||
/// - NFT Printed Copy Token Holding account (uninitialized).
|
||||
PrintNft,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub enum NewTokenDefinition {
|
||||
Fungible {
|
||||
name: String,
|
||||
total_supply: u128,
|
||||
},
|
||||
NonFungible {
|
||||
name: String,
|
||||
printable_supply: u128,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
|
||||
pub enum TokenDefinition {
|
||||
Fungible {
|
||||
name: String,
|
||||
total_supply: u128,
|
||||
metadata_id: Option<AccountId>,
|
||||
},
|
||||
NonFungible {
|
||||
name: String,
|
||||
printable_supply: u128,
|
||||
metadata_id: AccountId,
|
||||
},
|
||||
}
|
||||
|
||||
impl TryFrom<&Data> for TokenDefinition {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(data: &Data) -> Result<Self, Self::Error> {
|
||||
TokenDefinition::try_from_slice(data.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&TokenDefinition> for Data {
|
||||
fn from(definition: &TokenDefinition) -> Self {
|
||||
// Using size_of_val as size hint for Vec allocation
|
||||
let mut data = Vec::with_capacity(std::mem::size_of_val(definition));
|
||||
|
||||
BorshSerialize::serialize(definition, &mut data)
|
||||
.expect("Serialization to Vec should not fail");
|
||||
|
||||
Data::try_from(data).expect("Token definition encoded data should fit into Data")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
|
||||
pub enum TokenHolding {
|
||||
Fungible {
|
||||
definition_id: AccountId,
|
||||
balance: u128,
|
||||
},
|
||||
NftMaster {
|
||||
definition_id: AccountId,
|
||||
/// The amount of printed copies left - 1 (1 reserved for master copy itself).
|
||||
print_balance: u128,
|
||||
},
|
||||
NftPrintedCopy {
|
||||
definition_id: AccountId,
|
||||
/// Whether nft is owned by the holder.
|
||||
owned: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl TokenHolding {
|
||||
pub fn zeroized_clone_from(other: &Self) -> Self {
|
||||
match other {
|
||||
TokenHolding::Fungible { definition_id, .. } => TokenHolding::Fungible {
|
||||
definition_id: *definition_id,
|
||||
balance: 0,
|
||||
},
|
||||
TokenHolding::NftMaster { definition_id, .. } => TokenHolding::NftMaster {
|
||||
definition_id: *definition_id,
|
||||
print_balance: 0,
|
||||
},
|
||||
TokenHolding::NftPrintedCopy { definition_id, .. } => TokenHolding::NftPrintedCopy {
|
||||
definition_id: *definition_id,
|
||||
owned: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn zeroized_from_definition(
|
||||
definition_id: AccountId,
|
||||
definition: &TokenDefinition,
|
||||
) -> Self {
|
||||
match definition {
|
||||
TokenDefinition::Fungible { .. } => TokenHolding::Fungible {
|
||||
definition_id,
|
||||
balance: 0,
|
||||
},
|
||||
TokenDefinition::NonFungible { .. } => TokenHolding::NftPrintedCopy {
|
||||
definition_id,
|
||||
owned: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn definition_id(&self) -> AccountId {
|
||||
match self {
|
||||
TokenHolding::Fungible { definition_id, .. } => *definition_id,
|
||||
TokenHolding::NftMaster { definition_id, .. } => *definition_id,
|
||||
TokenHolding::NftPrintedCopy { definition_id, .. } => *definition_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&Data> for TokenHolding {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(data: &Data) -> Result<Self, Self::Error> {
|
||||
TokenHolding::try_from_slice(data.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&TokenHolding> for Data {
|
||||
fn from(holding: &TokenHolding) -> Self {
|
||||
// Using size_of_val as size hint for Vec allocation
|
||||
let mut data = Vec::with_capacity(std::mem::size_of_val(holding));
|
||||
|
||||
BorshSerialize::serialize(holding, &mut data)
|
||||
.expect("Serialization to Vec should not fail");
|
||||
|
||||
Data::try_from(data).expect("Token holding encoded data should fit into Data")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct NewTokenMetadata {
|
||||
/// Metadata standard.
|
||||
pub standard: MetadataStandard,
|
||||
/// Pointer to off-chain metadata
|
||||
pub uri: String,
|
||||
/// Creators of the token.
|
||||
pub creators: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
|
||||
pub struct TokenMetadata {
|
||||
/// Token Definition account id.
|
||||
pub definition_id: AccountId,
|
||||
/// Metadata standard .
|
||||
pub standard: MetadataStandard,
|
||||
/// Pointer to off-chain metadata.
|
||||
pub uri: String,
|
||||
/// Creators of the token.
|
||||
pub creators: String,
|
||||
/// Block id of primary sale.
|
||||
pub primary_sale_date: u64,
|
||||
}
|
||||
|
||||
/// Metadata standard defining the expected format of JSON located off-chain.
|
||||
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
|
||||
pub enum MetadataStandard {
|
||||
Simple,
|
||||
Expanded,
|
||||
}
|
||||
|
||||
impl TryFrom<&Data> for TokenMetadata {
|
||||
type Error = std::io::Error;
|
||||
|
||||
fn try_from(data: &Data) -> Result<Self, Self::Error> {
|
||||
TokenMetadata::try_from_slice(data.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&TokenMetadata> for Data {
|
||||
fn from(metadata: &TokenMetadata) -> Self {
|
||||
// Using size_of_val as size hint for Vec allocation
|
||||
let mut data = Vec::with_capacity(std::mem::size_of_val(metadata));
|
||||
|
||||
BorshSerialize::serialize(metadata, &mut data)
|
||||
.expect("Serialization to Vec should not fail");
|
||||
|
||||
Data::try_from(data).expect("Token metadata encoded data should fit into Data")
|
||||
}
|
||||
}
|
||||
104
programs/token/src/burn.rs
Normal file
104
programs/token/src/burn.rs
Normal file
@ -0,0 +1,104 @@
|
||||
use nssa_core::{
|
||||
account::{AccountWithMetadata, Data},
|
||||
program::AccountPostState,
|
||||
};
|
||||
use token_core::{TokenDefinition, TokenHolding};
|
||||
|
||||
pub fn burn(
|
||||
definition_account: AccountWithMetadata,
|
||||
user_holding_account: AccountWithMetadata,
|
||||
amount_to_burn: u128,
|
||||
) -> Vec<AccountPostState> {
|
||||
assert!(
|
||||
user_holding_account.is_authorized,
|
||||
"Authorization is missing"
|
||||
);
|
||||
|
||||
let mut definition = TokenDefinition::try_from(&definition_account.account.data)
|
||||
.expect("Token Definition account must be valid");
|
||||
let mut holding = TokenHolding::try_from(&user_holding_account.account.data)
|
||||
.expect("Token Holding account must be valid");
|
||||
|
||||
assert_eq!(
|
||||
definition_account.account_id,
|
||||
holding.definition_id(),
|
||||
"Mismatch Token Definition and Token Holding"
|
||||
);
|
||||
|
||||
match (&mut definition, &mut holding) {
|
||||
(
|
||||
TokenDefinition::Fungible {
|
||||
name: _,
|
||||
metadata_id: _,
|
||||
total_supply,
|
||||
},
|
||||
TokenHolding::Fungible {
|
||||
definition_id: _,
|
||||
balance,
|
||||
},
|
||||
) => {
|
||||
*balance = balance
|
||||
.checked_sub(amount_to_burn)
|
||||
.expect("Insufficient balance to burn");
|
||||
|
||||
*total_supply = total_supply
|
||||
.checked_sub(amount_to_burn)
|
||||
.expect("Total supply underflow");
|
||||
}
|
||||
(
|
||||
TokenDefinition::NonFungible {
|
||||
name: _,
|
||||
printable_supply,
|
||||
metadata_id: _,
|
||||
},
|
||||
TokenHolding::NftMaster {
|
||||
definition_id: _,
|
||||
print_balance,
|
||||
},
|
||||
) => {
|
||||
*printable_supply = printable_supply
|
||||
.checked_sub(amount_to_burn)
|
||||
.expect("Printable supply underflow");
|
||||
|
||||
*print_balance = print_balance
|
||||
.checked_sub(amount_to_burn)
|
||||
.expect("Insufficient balance to burn");
|
||||
}
|
||||
(
|
||||
TokenDefinition::NonFungible {
|
||||
name: _,
|
||||
printable_supply,
|
||||
metadata_id: _,
|
||||
},
|
||||
TokenHolding::NftPrintedCopy {
|
||||
definition_id: _,
|
||||
owned,
|
||||
},
|
||||
) => {
|
||||
assert_eq!(
|
||||
amount_to_burn, 1,
|
||||
"Invalid balance to burn for NFT Printed Copy"
|
||||
);
|
||||
|
||||
assert!(*owned, "Cannot burn unowned NFT Printed Copy");
|
||||
|
||||
*printable_supply = printable_supply
|
||||
.checked_sub(1)
|
||||
.expect("Printable supply underflow");
|
||||
|
||||
*owned = false;
|
||||
}
|
||||
_ => panic!("Mismatched Token Definition and Token Holding types"),
|
||||
}
|
||||
|
||||
let mut definition_post = definition_account.account;
|
||||
definition_post.data = Data::from(&definition);
|
||||
|
||||
let mut holding_post = user_holding_account.account;
|
||||
holding_post.data = Data::from(&holding);
|
||||
|
||||
vec![
|
||||
AccountPostState::new(definition_post),
|
||||
AccountPostState::new(holding_post),
|
||||
]
|
||||
}
|
||||
34
programs/token/src/initialize.rs
Normal file
34
programs/token/src/initialize.rs
Normal file
@ -0,0 +1,34 @@
|
||||
use nssa_core::{
|
||||
account::{Account, AccountWithMetadata, Data},
|
||||
program::AccountPostState,
|
||||
};
|
||||
use token_core::{TokenDefinition, TokenHolding};
|
||||
|
||||
pub fn initialize_account(
|
||||
definition_account: AccountWithMetadata,
|
||||
account_to_initialize: AccountWithMetadata,
|
||||
) -> Vec<AccountPostState> {
|
||||
assert_eq!(
|
||||
account_to_initialize.account,
|
||||
Account::default(),
|
||||
"Only Uninitialized accounts can be initialized"
|
||||
);
|
||||
|
||||
// TODO: #212 We should check that this is an account owned by the token program.
|
||||
// This check can't be done here since the ID of the program is known only after compiling it
|
||||
//
|
||||
// Check definition account is valid
|
||||
let definition = TokenDefinition::try_from(&definition_account.account.data)
|
||||
.expect("Definition account must be valid");
|
||||
let holding =
|
||||
TokenHolding::zeroized_from_definition(definition_account.account_id, &definition);
|
||||
|
||||
let definition_post = definition_account.account;
|
||||
let mut account_to_initialize = account_to_initialize.account;
|
||||
account_to_initialize.data = Data::from(&holding);
|
||||
|
||||
vec![
|
||||
AccountPostState::new(definition_post),
|
||||
AccountPostState::new_claimed(account_to_initialize),
|
||||
]
|
||||
}
|
||||
12
programs/token/src/lib.rs
Normal file
12
programs/token/src/lib.rs
Normal file
@ -0,0 +1,12 @@
|
||||
//! The Token Program implementation.
|
||||
|
||||
pub use token_core as core;
|
||||
|
||||
pub mod burn;
|
||||
pub mod initialize;
|
||||
pub mod mint;
|
||||
pub mod new_definition;
|
||||
pub mod print_nft;
|
||||
pub mod transfer;
|
||||
|
||||
mod tests;
|
||||
71
programs/token/src/mint.rs
Normal file
71
programs/token/src/mint.rs
Normal file
@ -0,0 +1,71 @@
|
||||
use nssa_core::{
|
||||
account::{Account, AccountWithMetadata, Data},
|
||||
program::AccountPostState,
|
||||
};
|
||||
use token_core::{TokenDefinition, TokenHolding};
|
||||
|
||||
pub fn mint(
|
||||
definition_account: AccountWithMetadata,
|
||||
user_holding_account: AccountWithMetadata,
|
||||
amount_to_mint: u128,
|
||||
) -> Vec<AccountPostState> {
|
||||
assert!(
|
||||
definition_account.is_authorized,
|
||||
"Definition authorization is missing"
|
||||
);
|
||||
|
||||
let mut definition = TokenDefinition::try_from(&definition_account.account.data)
|
||||
.expect("Token Definition account must be valid");
|
||||
let mut holding = if user_holding_account.account == Account::default() {
|
||||
TokenHolding::zeroized_from_definition(definition_account.account_id, &definition)
|
||||
} else {
|
||||
TokenHolding::try_from(&user_holding_account.account.data)
|
||||
.expect("Token Holding account must be valid")
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
definition_account.account_id,
|
||||
holding.definition_id(),
|
||||
"Mismatch Token Definition and Token Holding"
|
||||
);
|
||||
|
||||
match (&mut definition, &mut holding) {
|
||||
(
|
||||
TokenDefinition::Fungible {
|
||||
name: _,
|
||||
metadata_id: _,
|
||||
total_supply,
|
||||
},
|
||||
TokenHolding::Fungible {
|
||||
definition_id: _,
|
||||
balance,
|
||||
},
|
||||
) => {
|
||||
*balance = balance
|
||||
.checked_add(amount_to_mint)
|
||||
.expect("Balance overflow on minting");
|
||||
|
||||
*total_supply = total_supply
|
||||
.checked_add(amount_to_mint)
|
||||
.expect("Total supply overflow");
|
||||
}
|
||||
(
|
||||
TokenDefinition::NonFungible { .. },
|
||||
TokenHolding::NftMaster { .. } | TokenHolding::NftPrintedCopy { .. },
|
||||
) => {
|
||||
panic!("Cannot mint additional supply for Non-Fungible Tokens");
|
||||
}
|
||||
_ => panic!("Mismatched Token Definition and Token Holding types"),
|
||||
}
|
||||
|
||||
let mut definition_post = definition_account.account;
|
||||
definition_post.data = Data::from(&definition);
|
||||
|
||||
let mut holding_post = user_holding_account.account;
|
||||
holding_post.data = Data::from(&holding);
|
||||
|
||||
vec![
|
||||
AccountPostState::new(definition_post),
|
||||
AccountPostState::new_claimed_if_default(holding_post),
|
||||
]
|
||||
}
|
||||
124
programs/token/src/new_definition.rs
Normal file
124
programs/token/src/new_definition.rs
Normal file
@ -0,0 +1,124 @@
|
||||
use nssa_core::{
|
||||
account::{Account, AccountWithMetadata, Data},
|
||||
program::AccountPostState,
|
||||
};
|
||||
use token_core::{
|
||||
NewTokenDefinition, NewTokenMetadata, TokenDefinition, TokenHolding, TokenMetadata,
|
||||
};
|
||||
|
||||
pub fn new_fungible_definition(
|
||||
definition_target_account: AccountWithMetadata,
|
||||
holding_target_account: AccountWithMetadata,
|
||||
name: String,
|
||||
total_supply: u128,
|
||||
) -> Vec<AccountPostState> {
|
||||
assert_eq!(
|
||||
definition_target_account.account,
|
||||
Account::default(),
|
||||
"Definition target account must have default values"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
holding_target_account.account,
|
||||
Account::default(),
|
||||
"Holding target account must have default values"
|
||||
);
|
||||
|
||||
let token_definition = TokenDefinition::Fungible {
|
||||
name,
|
||||
total_supply,
|
||||
metadata_id: None,
|
||||
};
|
||||
let token_holding = TokenHolding::Fungible {
|
||||
definition_id: definition_target_account.account_id,
|
||||
balance: total_supply,
|
||||
};
|
||||
|
||||
let mut definition_target_account_post = definition_target_account.account;
|
||||
definition_target_account_post.data = Data::from(&token_definition);
|
||||
|
||||
let mut holding_target_account_post = holding_target_account.account;
|
||||
holding_target_account_post.data = Data::from(&token_holding);
|
||||
|
||||
vec![
|
||||
AccountPostState::new_claimed(definition_target_account_post),
|
||||
AccountPostState::new_claimed(holding_target_account_post),
|
||||
]
|
||||
}
|
||||
|
||||
pub fn new_definition_with_metadata(
|
||||
definition_target_account: AccountWithMetadata,
|
||||
holding_target_account: AccountWithMetadata,
|
||||
metadata_target_account: AccountWithMetadata,
|
||||
new_definition: NewTokenDefinition,
|
||||
metadata: NewTokenMetadata,
|
||||
) -> Vec<AccountPostState> {
|
||||
assert_eq!(
|
||||
definition_target_account.account,
|
||||
Account::default(),
|
||||
"Definition target account must have default values"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
holding_target_account.account,
|
||||
Account::default(),
|
||||
"Holding target account must have default values"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
metadata_target_account.account,
|
||||
Account::default(),
|
||||
"Metadata target account must have default values"
|
||||
);
|
||||
|
||||
let (token_definition, token_holding) = match new_definition {
|
||||
NewTokenDefinition::Fungible { name, total_supply } => (
|
||||
TokenDefinition::Fungible {
|
||||
name,
|
||||
total_supply,
|
||||
metadata_id: Some(metadata_target_account.account_id),
|
||||
},
|
||||
TokenHolding::Fungible {
|
||||
definition_id: definition_target_account.account_id,
|
||||
balance: total_supply,
|
||||
},
|
||||
),
|
||||
NewTokenDefinition::NonFungible {
|
||||
name,
|
||||
printable_supply,
|
||||
} => (
|
||||
TokenDefinition::NonFungible {
|
||||
name,
|
||||
printable_supply,
|
||||
metadata_id: metadata_target_account.account_id,
|
||||
},
|
||||
TokenHolding::NftMaster {
|
||||
definition_id: definition_target_account.account_id,
|
||||
print_balance: printable_supply,
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
let token_metadata = TokenMetadata {
|
||||
definition_id: definition_target_account.account_id,
|
||||
standard: metadata.standard,
|
||||
uri: metadata.uri,
|
||||
creators: metadata.creators,
|
||||
primary_sale_date: 0u64, // TODO #261: future works to implement this
|
||||
};
|
||||
|
||||
let mut definition_target_account_post = definition_target_account.account.clone();
|
||||
definition_target_account_post.data = Data::from(&token_definition);
|
||||
|
||||
let mut holding_target_account_post = holding_target_account.account.clone();
|
||||
holding_target_account_post.data = Data::from(&token_holding);
|
||||
|
||||
let mut metadata_target_account_post = metadata_target_account.account.clone();
|
||||
metadata_target_account_post.data = Data::from(&token_metadata);
|
||||
|
||||
vec![
|
||||
AccountPostState::new_claimed(definition_target_account_post),
|
||||
AccountPostState::new_claimed(holding_target_account_post),
|
||||
AccountPostState::new_claimed(metadata_target_account_post),
|
||||
]
|
||||
}
|
||||
54
programs/token/src/print_nft.rs
Normal file
54
programs/token/src/print_nft.rs
Normal file
@ -0,0 +1,54 @@
|
||||
use nssa_core::{
|
||||
account::{Account, AccountWithMetadata, Data},
|
||||
program::AccountPostState,
|
||||
};
|
||||
use token_core::TokenHolding;
|
||||
|
||||
pub fn print_nft(
|
||||
master_account: AccountWithMetadata,
|
||||
printed_account: AccountWithMetadata,
|
||||
) -> Vec<AccountPostState> {
|
||||
assert!(
|
||||
master_account.is_authorized,
|
||||
"Master NFT Account must be authorized"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
printed_account.account,
|
||||
Account::default(),
|
||||
"Printed Account must be uninitialized"
|
||||
);
|
||||
|
||||
let mut master_account_data =
|
||||
TokenHolding::try_from(&master_account.account.data).expect("Invalid Token Holding data");
|
||||
|
||||
let TokenHolding::NftMaster {
|
||||
definition_id,
|
||||
print_balance,
|
||||
} = &mut master_account_data
|
||||
else {
|
||||
panic!("Invalid Token Holding provided as NFT Master Account");
|
||||
};
|
||||
|
||||
let definition_id = *definition_id;
|
||||
|
||||
assert!(
|
||||
*print_balance > 1,
|
||||
"Insufficient balance to print another NFT copy"
|
||||
);
|
||||
*print_balance -= 1;
|
||||
|
||||
let mut master_account_post = master_account.account;
|
||||
master_account_post.data = Data::from(&master_account_data);
|
||||
|
||||
let mut printed_account_post = printed_account.account;
|
||||
printed_account_post.data = Data::from(&TokenHolding::NftPrintedCopy {
|
||||
definition_id,
|
||||
owned: true,
|
||||
});
|
||||
|
||||
vec![
|
||||
AccountPostState::new(master_account_post),
|
||||
AccountPostState::new_claimed(printed_account_post),
|
||||
]
|
||||
}
|
||||
1040
programs/token/src/tests.rs
Normal file
1040
programs/token/src/tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
110
programs/token/src/transfer.rs
Normal file
110
programs/token/src/transfer.rs
Normal file
@ -0,0 +1,110 @@
|
||||
use nssa_core::{
|
||||
account::{Account, AccountWithMetadata, Data},
|
||||
program::AccountPostState,
|
||||
};
|
||||
use token_core::TokenHolding;
|
||||
|
||||
pub fn transfer(
|
||||
sender: AccountWithMetadata,
|
||||
recipient: AccountWithMetadata,
|
||||
balance_to_move: u128,
|
||||
) -> Vec<AccountPostState> {
|
||||
assert!(sender.is_authorized, "Sender authorization is missing");
|
||||
|
||||
let mut sender_holding =
|
||||
TokenHolding::try_from(&sender.account.data).expect("Invalid sender data");
|
||||
|
||||
let mut recipient_holding = if recipient.account == Account::default() {
|
||||
TokenHolding::zeroized_clone_from(&sender_holding)
|
||||
} else {
|
||||
TokenHolding::try_from(&recipient.account.data).expect("Invalid recipient data")
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
sender_holding.definition_id(),
|
||||
recipient_holding.definition_id(),
|
||||
"Sender and recipient definition id mismatch"
|
||||
);
|
||||
|
||||
match (&mut sender_holding, &mut recipient_holding) {
|
||||
(
|
||||
TokenHolding::Fungible {
|
||||
definition_id: _,
|
||||
balance: sender_balance,
|
||||
},
|
||||
TokenHolding::Fungible {
|
||||
definition_id: _,
|
||||
balance: recipient_balance,
|
||||
},
|
||||
) => {
|
||||
*sender_balance = sender_balance
|
||||
.checked_sub(balance_to_move)
|
||||
.expect("Insufficient balance");
|
||||
|
||||
*recipient_balance = recipient_balance
|
||||
.checked_add(balance_to_move)
|
||||
.expect("Recipient balance overflow");
|
||||
}
|
||||
(
|
||||
TokenHolding::NftMaster {
|
||||
definition_id: _,
|
||||
print_balance: sender_print_balance,
|
||||
},
|
||||
TokenHolding::NftMaster {
|
||||
definition_id: _,
|
||||
print_balance: recipient_print_balance,
|
||||
},
|
||||
) => {
|
||||
assert_eq!(
|
||||
*recipient_print_balance, 0,
|
||||
"Invalid balance in recipient account for NFT transfer"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
*sender_print_balance, balance_to_move,
|
||||
"Invalid balance for NFT Master transfer"
|
||||
);
|
||||
|
||||
std::mem::swap(sender_print_balance, recipient_print_balance);
|
||||
}
|
||||
(
|
||||
TokenHolding::NftPrintedCopy {
|
||||
definition_id: _,
|
||||
owned: sender_owned,
|
||||
},
|
||||
TokenHolding::NftPrintedCopy {
|
||||
definition_id: _,
|
||||
owned: recipient_owned,
|
||||
},
|
||||
) => {
|
||||
assert_eq!(
|
||||
balance_to_move, 1,
|
||||
"Invalid balance for NFT Printed Copy transfer"
|
||||
);
|
||||
|
||||
assert!(*sender_owned, "Sender does not own the NFT Printed Copy");
|
||||
|
||||
assert!(
|
||||
!*recipient_owned,
|
||||
"Recipient already owns the NFT Printed Copy"
|
||||
);
|
||||
|
||||
*sender_owned = false;
|
||||
*recipient_owned = true;
|
||||
}
|
||||
_ => {
|
||||
panic!("Mismatched token holding types for transfer");
|
||||
}
|
||||
};
|
||||
|
||||
let mut sender_post = sender.account;
|
||||
sender_post.data = Data::from(&sender_holding);
|
||||
|
||||
let mut recipient_post = recipient.account;
|
||||
recipient_post.data = Data::from(&recipient_holding);
|
||||
|
||||
vec![
|
||||
AccountPostState::new(sender_post),
|
||||
AccountPostState::new_claimed_if_default(recipient_post),
|
||||
]
|
||||
}
|
||||
@ -2,6 +2,7 @@
|
||||
name = "sequencer_core"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "sequencer_rpc"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "sequencer_runner"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
common.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "storage"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
common.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "test_program_methods"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[build-dependencies]
|
||||
risc0-build.workspace = true
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
name = "test_programs"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa_core.workspace = true
|
||||
|
||||
@ -2,15 +2,20 @@
|
||||
name = "wallet-ffi"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = { workspace = true }
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "staticlib"]
|
||||
crate-type = ["rlib", "cdylib", "staticlib"]
|
||||
|
||||
[dependencies]
|
||||
wallet.workspace = true
|
||||
nssa.workspace = true
|
||||
common.workspace = true
|
||||
nssa_core.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
[build-dependencies]
|
||||
cbindgen = "0.26"
|
||||
cbindgen = "0.29"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
@ -7,9 +7,7 @@ use nssa::AccountId;
|
||||
use crate::{
|
||||
block_on,
|
||||
error::{print_error, WalletFfiError},
|
||||
types::{
|
||||
FfiAccount, FfiAccountList, FfiAccountListEntry, FfiBytes32, FfiProgramId, WalletHandle,
|
||||
},
|
||||
types::{FfiAccount, FfiAccountList, FfiAccountListEntry, FfiBytes32, WalletHandle},
|
||||
wallet::get_wallet,
|
||||
};
|
||||
|
||||
@ -349,26 +347,8 @@ pub unsafe extern "C" fn wallet_ffi_get_account_public(
|
||||
Err(e) => return e,
|
||||
};
|
||||
|
||||
// Convert account data to FFI type
|
||||
let data_vec: Vec<u8> = account.data.into();
|
||||
let data_len = data_vec.len();
|
||||
let data_ptr = if data_len > 0 {
|
||||
let data_boxed = data_vec.into_boxed_slice();
|
||||
Box::into_raw(data_boxed) as *const u8
|
||||
} else {
|
||||
ptr::null()
|
||||
};
|
||||
|
||||
let program_owner = FfiProgramId {
|
||||
data: account.program_owner,
|
||||
};
|
||||
|
||||
unsafe {
|
||||
(*out_account).program_owner = program_owner;
|
||||
(*out_account).balance = account.balance.to_le_bytes();
|
||||
(*out_account).nonce = account.nonce.to_le_bytes();
|
||||
(*out_account).data = data_ptr;
|
||||
(*out_account).data_len = data_len;
|
||||
*out_account = account.into();
|
||||
}
|
||||
|
||||
WalletFfiError::Success
|
||||
|
||||
@ -36,6 +36,10 @@ pub enum WalletFfiError {
|
||||
SyncError = 13,
|
||||
/// Serialization/deserialization error
|
||||
SerializationError = 14,
|
||||
/// Invalid conversion from FFI types to NSSA types
|
||||
InvalidTypeConversion = 15,
|
||||
/// Invalid Key value
|
||||
InvalidKeyValue = 16,
|
||||
/// Internal error (catch-all)
|
||||
InternalError = 99,
|
||||
}
|
||||
|
||||
@ -65,7 +65,7 @@ pub unsafe extern "C" fn wallet_ffi_get_public_account_key(
|
||||
let public_key = PublicKey::new_from_private_key(private_key);
|
||||
|
||||
unsafe {
|
||||
(*out_public_key).public_key.data = *public_key.value();
|
||||
*out_public_key = public_key.into();
|
||||
}
|
||||
|
||||
WalletFfiError::Success
|
||||
|
||||
@ -1,6 +1,12 @@
|
||||
//! C-compatible type definitions for the FFI layer.
|
||||
|
||||
use std::ffi::c_char;
|
||||
use core::slice;
|
||||
use std::{ffi::c_char, ptr};
|
||||
|
||||
use nssa::{Account, Data};
|
||||
use nssa_core::encryption::shared_key_derivation::Secp256k1Point;
|
||||
|
||||
use crate::error::WalletFfiError;
|
||||
|
||||
/// Opaque pointer to the Wallet instance.
|
||||
///
|
||||
@ -25,6 +31,13 @@ pub struct FfiProgramId {
|
||||
pub data: [u32; 8],
|
||||
}
|
||||
|
||||
/// U128 - 16 bytes little endian
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Default)]
|
||||
pub struct FfiU128 {
|
||||
pub data: [u8; 16],
|
||||
}
|
||||
|
||||
/// Account data structure - C-compatible version of nssa Account.
|
||||
///
|
||||
/// Note: `balance` and `nonce` are u128 values represented as little-endian
|
||||
@ -33,23 +46,23 @@ pub struct FfiProgramId {
|
||||
pub struct FfiAccount {
|
||||
pub program_owner: FfiProgramId,
|
||||
/// Balance as little-endian [u8; 16]
|
||||
pub balance: [u8; 16],
|
||||
pub balance: FfiU128,
|
||||
/// Pointer to account data bytes
|
||||
pub data: *const u8,
|
||||
/// Length of account data
|
||||
pub data_len: usize,
|
||||
/// Nonce as little-endian [u8; 16]
|
||||
pub nonce: [u8; 16],
|
||||
pub nonce: FfiU128,
|
||||
}
|
||||
|
||||
impl Default for FfiAccount {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
program_owner: FfiProgramId::default(),
|
||||
balance: [0u8; 16],
|
||||
balance: FfiU128::default(),
|
||||
data: std::ptr::null(),
|
||||
data_len: 0,
|
||||
nonce: [0u8; 16],
|
||||
nonce: FfiU128::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -138,6 +151,40 @@ impl FfiBytes32 {
|
||||
}
|
||||
}
|
||||
|
||||
impl FfiPrivateAccountKeys {
|
||||
pub fn npk(&self) -> nssa_core::NullifierPublicKey {
|
||||
nssa_core::NullifierPublicKey(self.nullifier_public_key.data)
|
||||
}
|
||||
|
||||
pub fn ivk(&self) -> Result<nssa_core::encryption::IncomingViewingPublicKey, WalletFfiError> {
|
||||
if self.incoming_viewing_public_key_len == 33 {
|
||||
let slice = unsafe {
|
||||
slice::from_raw_parts(
|
||||
self.incoming_viewing_public_key,
|
||||
self.incoming_viewing_public_key_len,
|
||||
)
|
||||
};
|
||||
Ok(Secp256k1Point(slice.to_vec()))
|
||||
} else {
|
||||
Err(WalletFfiError::InvalidKeyValue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u128> for FfiU128 {
|
||||
fn from(value: u128) -> Self {
|
||||
Self {
|
||||
data: value.to_le_bytes(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<FfiU128> for u128 {
|
||||
fn from(value: FfiU128) -> Self {
|
||||
u128::from_le_bytes(value.data)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&nssa::AccountId> for FfiBytes32 {
|
||||
fn from(id: &nssa::AccountId) -> Self {
|
||||
Self::from_account_id(id)
|
||||
@ -149,3 +196,67 @@ impl From<FfiBytes32> for nssa::AccountId {
|
||||
nssa::AccountId::new(bytes.data)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<nssa::Account> for FfiAccount {
|
||||
fn from(value: nssa::Account) -> Self {
|
||||
// Convert account data to FFI type
|
||||
let data_vec: Vec<u8> = value.data.into();
|
||||
let data_len = data_vec.len();
|
||||
let data = if data_len > 0 {
|
||||
let data_boxed = data_vec.into_boxed_slice();
|
||||
Box::into_raw(data_boxed) as *const u8
|
||||
} else {
|
||||
ptr::null()
|
||||
};
|
||||
|
||||
let program_owner = FfiProgramId {
|
||||
data: value.program_owner,
|
||||
};
|
||||
FfiAccount {
|
||||
program_owner,
|
||||
balance: value.balance.into(),
|
||||
data,
|
||||
data_len,
|
||||
nonce: value.nonce.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&FfiAccount> for nssa::Account {
|
||||
type Error = WalletFfiError;
|
||||
|
||||
fn try_from(value: &FfiAccount) -> Result<Self, Self::Error> {
|
||||
let data = if value.data_len > 0 {
|
||||
unsafe {
|
||||
let slice = slice::from_raw_parts(value.data, value.data_len);
|
||||
Data::try_from(slice.to_vec()).map_err(|_| WalletFfiError::InvalidTypeConversion)?
|
||||
}
|
||||
} else {
|
||||
Data::default()
|
||||
};
|
||||
Ok(Account {
|
||||
program_owner: value.program_owner.data,
|
||||
balance: value.balance.into(),
|
||||
data,
|
||||
nonce: value.nonce.into(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<nssa::PublicKey> for FfiPublicAccountKey {
|
||||
fn from(value: nssa::PublicKey) -> Self {
|
||||
Self {
|
||||
public_key: FfiBytes32::from_bytes(*value.value()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&FfiPublicAccountKey> for nssa::PublicKey {
|
||||
type Error = WalletFfiError;
|
||||
|
||||
fn try_from(value: &FfiPublicAccountKey) -> Result<Self, Self::Error> {
|
||||
let public_key = nssa::PublicKey::try_new(value.public_key.data)
|
||||
.map_err(|_| WalletFfiError::InvalidTypeConversion)?;
|
||||
Ok(public_key)
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,12 +2,14 @@
|
||||
name = "wallet"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license = { workspace = true }
|
||||
|
||||
[dependencies]
|
||||
nssa_core.workspace = true
|
||||
nssa.workspace = true
|
||||
common.workspace = true
|
||||
key_protocol.workspace = true
|
||||
token_core.workspace = true
|
||||
|
||||
anyhow.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
@ -4,10 +4,10 @@ use clap::Subcommand;
|
||||
use itertools::Itertools as _;
|
||||
use key_protocol::key_management::key_tree::chain_index::ChainIndex;
|
||||
use nssa::{Account, PublicKey, program::Program};
|
||||
use serde::Serialize;
|
||||
use token_core::{TokenDefinition, TokenHolding};
|
||||
|
||||
use crate::{
|
||||
TokenDefinition, TokenHolding, WalletCore,
|
||||
WalletCore,
|
||||
cli::{SubcommandReturnValue, WalletSubcommand},
|
||||
config::Label,
|
||||
helperfunctions::{AccountPrivacyKind, HumanReadableAccount, parse_addr_with_privacy_prefix},
|
||||
@ -121,83 +121,26 @@ impl WalletSubcommand for NewSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct AuthenticatedTransferAccountView {
|
||||
pub balance: u128,
|
||||
}
|
||||
|
||||
impl From<nssa::Account> for AuthenticatedTransferAccountView {
|
||||
fn from(value: nssa::Account) -> Self {
|
||||
Self {
|
||||
balance: value.balance,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct TokedDefinitionAccountView {
|
||||
pub account_type: String,
|
||||
pub name: String,
|
||||
pub total_supply: u128,
|
||||
}
|
||||
|
||||
impl From<TokenDefinition> for TokedDefinitionAccountView {
|
||||
fn from(value: TokenDefinition) -> Self {
|
||||
Self {
|
||||
account_type: "Token definition".to_string(),
|
||||
name: {
|
||||
// Assuming, that name does not have UTF-8 NULL and all zeroes are padding.
|
||||
let name_trimmed: Vec<_> =
|
||||
value.name.into_iter().take_while(|ch| *ch != 0).collect();
|
||||
String::from_utf8(name_trimmed).unwrap_or(hex::encode(value.name))
|
||||
},
|
||||
total_supply: value.total_supply,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct TokedHoldingAccountView {
|
||||
pub account_type: String,
|
||||
pub definition_id: String,
|
||||
pub balance: u128,
|
||||
}
|
||||
|
||||
impl From<TokenHolding> for TokedHoldingAccountView {
|
||||
fn from(value: TokenHolding) -> Self {
|
||||
Self {
|
||||
account_type: "Token holding".to_string(),
|
||||
definition_id: value.definition_id.to_string(),
|
||||
balance: value.balance,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Formats account details for display, returning (description, json_view)
|
||||
fn format_account_details(account: &Account) -> (String, String) {
|
||||
let auth_tr_prog_id = Program::authenticated_transfer_program().id();
|
||||
let token_prog_id = Program::token().id();
|
||||
|
||||
match &account.program_owner {
|
||||
_ if account.program_owner == auth_tr_prog_id => {
|
||||
let acc_view: AuthenticatedTransferAccountView = account.clone().into();
|
||||
(
|
||||
"Account owned by authenticated transfer program".to_string(),
|
||||
serde_json::to_string(&acc_view).unwrap(),
|
||||
)
|
||||
}
|
||||
_ if account.program_owner == token_prog_id => {
|
||||
if let Some(token_def) = TokenDefinition::parse(&account.data) {
|
||||
let acc_view: TokedDefinitionAccountView = token_def.into();
|
||||
o if *o == auth_tr_prog_id => (
|
||||
"Account owned by authenticated transfer program".to_string(),
|
||||
serde_json::to_string(&account).unwrap(),
|
||||
),
|
||||
o if *o == token_prog_id => {
|
||||
if let Ok(token_def) = TokenDefinition::try_from(&account.data) {
|
||||
(
|
||||
"Definition account owned by token program".to_string(),
|
||||
serde_json::to_string(&acc_view).unwrap(),
|
||||
serde_json::to_string(&token_def).unwrap(),
|
||||
)
|
||||
} else if let Some(token_hold) = TokenHolding::parse(&account.data) {
|
||||
let acc_view: TokedHoldingAccountView = token_hold.into();
|
||||
} else if let Ok(token_hold) = TokenHolding::try_from(&account.data) {
|
||||
(
|
||||
"Holding account owned by token program".to_string(),
|
||||
serde_json::to_string(&acc_view).unwrap(),
|
||||
serde_json::to_string(&token_hold).unwrap(),
|
||||
)
|
||||
} else {
|
||||
let account_hr: HumanReadableAccount = account.clone().into();
|
||||
@ -456,52 +399,3 @@ impl WalletSubcommand for AccountSubcommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use nssa::AccountId;
|
||||
|
||||
use crate::cli::account::{TokedDefinitionAccountView, TokenDefinition};
|
||||
|
||||
#[test]
|
||||
fn test_invalid_utf_8_name_of_token() {
|
||||
let token_def = TokenDefinition {
|
||||
account_type: 1,
|
||||
name: [137, 12, 14, 3, 5, 4],
|
||||
total_supply: 100,
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
};
|
||||
|
||||
let token_def_view: TokedDefinitionAccountView = token_def.into();
|
||||
|
||||
assert_eq!(token_def_view.name, "890c0e030504");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_valid_utf_8_name_of_token_all_bytes() {
|
||||
let token_def = TokenDefinition {
|
||||
account_type: 1,
|
||||
name: [240, 159, 146, 150, 66, 66],
|
||||
total_supply: 100,
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
};
|
||||
|
||||
let token_def_view: TokedDefinitionAccountView = token_def.into();
|
||||
|
||||
assert_eq!(token_def_view.name, "💖BB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_valid_utf_8_name_of_token_less_bytes() {
|
||||
let token_def = TokenDefinition {
|
||||
account_type: 1,
|
||||
name: [78, 65, 77, 69, 0, 0],
|
||||
total_supply: 100,
|
||||
metadata_id: AccountId::new([0; 32]),
|
||||
};
|
||||
|
||||
let token_def_view: TokedDefinitionAccountView = token_def.into();
|
||||
|
||||
assert_eq!(token_def_view.name, "NAME");
|
||||
}
|
||||
}
|
||||
|
||||
@ -1258,14 +1258,6 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
name,
|
||||
total_supply,
|
||||
} => {
|
||||
let name = name.as_bytes();
|
||||
if name.len() > 6 {
|
||||
// TODO: return error
|
||||
panic!("Name length mismatch");
|
||||
}
|
||||
let mut name_bytes = [0; 6];
|
||||
name_bytes[..name.len()].copy_from_slice(name);
|
||||
|
||||
let definition_account_id: AccountId = definition_account_id.parse().unwrap();
|
||||
let supply_account_id: AccountId = supply_account_id.parse().unwrap();
|
||||
|
||||
@ -1273,7 +1265,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
.send_new_definition_private_owned_definiton_and_supply(
|
||||
definition_account_id,
|
||||
supply_account_id,
|
||||
name_bytes,
|
||||
name,
|
||||
total_supply,
|
||||
)
|
||||
.await?;
|
||||
@ -1307,14 +1299,6 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
name,
|
||||
total_supply,
|
||||
} => {
|
||||
let name = name.as_bytes();
|
||||
if name.len() > 6 {
|
||||
// TODO: return error
|
||||
panic!("Name length mismatch");
|
||||
}
|
||||
let mut name_bytes = [0; 6];
|
||||
name_bytes[..name.len()].copy_from_slice(name);
|
||||
|
||||
let definition_account_id: AccountId = definition_account_id.parse().unwrap();
|
||||
let supply_account_id: AccountId = supply_account_id.parse().unwrap();
|
||||
|
||||
@ -1322,7 +1306,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
.send_new_definition_private_owned_definiton(
|
||||
definition_account_id,
|
||||
supply_account_id,
|
||||
name_bytes,
|
||||
name,
|
||||
total_supply,
|
||||
)
|
||||
.await?;
|
||||
@ -1353,14 +1337,6 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
name,
|
||||
total_supply,
|
||||
} => {
|
||||
let name = name.as_bytes();
|
||||
if name.len() > 6 {
|
||||
// TODO: return error
|
||||
panic!("Name length mismatch");
|
||||
}
|
||||
let mut name_bytes = [0; 6];
|
||||
name_bytes[..name.len()].copy_from_slice(name);
|
||||
|
||||
let definition_account_id: AccountId = definition_account_id.parse().unwrap();
|
||||
let supply_account_id: AccountId = supply_account_id.parse().unwrap();
|
||||
|
||||
@ -1368,7 +1344,7 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
.send_new_definition_private_owned_supply(
|
||||
definition_account_id,
|
||||
supply_account_id,
|
||||
name_bytes,
|
||||
name,
|
||||
total_supply,
|
||||
)
|
||||
.await?;
|
||||
@ -1399,18 +1375,11 @@ impl WalletSubcommand for CreateNewTokenProgramSubcommand {
|
||||
name,
|
||||
total_supply,
|
||||
} => {
|
||||
let name = name.as_bytes();
|
||||
if name.len() > 6 {
|
||||
// TODO: return error
|
||||
panic!();
|
||||
}
|
||||
let mut name_bytes = [0; 6];
|
||||
name_bytes[..name.len()].copy_from_slice(name);
|
||||
Token(wallet_core)
|
||||
.send_new_definition(
|
||||
definition_account_id.parse().unwrap(),
|
||||
supply_account_id.parse().unwrap(),
|
||||
name_bytes,
|
||||
name,
|
||||
total_supply,
|
||||
)
|
||||
.await?;
|
||||
|
||||
@ -175,7 +175,7 @@ pub struct GasConfig {
|
||||
pub gas_limit_runtime: u64,
|
||||
}
|
||||
|
||||
#[optfield::optfield(pub WalletConfigOverrides, rewrap, attrs = (derive(Debug, Default)))]
|
||||
#[optfield::optfield(pub WalletConfigOverrides, rewrap, attrs = (derive(Debug, Default, Clone)))]
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct WalletConfig {
|
||||
/// Override rust log (env var logging level)
|
||||
|
||||
@ -18,9 +18,7 @@ use nssa::{
|
||||
circuit::ProgramWithDependencies, message::EncryptedAccountData,
|
||||
},
|
||||
};
|
||||
use nssa_core::{
|
||||
Commitment, MembershipProof, SharedSecretKey, account::Data, program::InstructionData,
|
||||
};
|
||||
use nssa_core::{Commitment, MembershipProof, SharedSecretKey, program::InstructionData};
|
||||
pub use privacy_preserving_tx::PrivacyPreservingAccount;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use url::Url;
|
||||
@ -46,84 +44,9 @@ pub enum AccDecodeData {
|
||||
Decode(nssa_core::SharedSecretKey, AccountId),
|
||||
}
|
||||
|
||||
const TOKEN_DEFINITION_DATA_SIZE: usize = 55;
|
||||
|
||||
const TOKEN_HOLDING_TYPE: u8 = 1;
|
||||
const TOKEN_HOLDING_DATA_SIZE: usize = 49;
|
||||
const TOKEN_STANDARD_FUNGIBLE_TOKEN: u8 = 0;
|
||||
const TOKEN_STANDARD_NONFUNGIBLE: u8 = 2;
|
||||
|
||||
struct TokenDefinition {
|
||||
#[allow(unused)]
|
||||
account_type: u8,
|
||||
name: [u8; 6],
|
||||
total_supply: u128,
|
||||
#[allow(unused)]
|
||||
metadata_id: AccountId,
|
||||
}
|
||||
|
||||
struct TokenHolding {
|
||||
#[allow(unused)]
|
||||
account_type: u8,
|
||||
definition_id: AccountId,
|
||||
balance: u128,
|
||||
}
|
||||
|
||||
impl TokenDefinition {
|
||||
fn parse(data: &Data) -> Option<Self> {
|
||||
let data = Vec::<u8>::from(data.clone());
|
||||
|
||||
if data.len() != TOKEN_DEFINITION_DATA_SIZE {
|
||||
None
|
||||
} else {
|
||||
let account_type = data[0];
|
||||
let name = data[1..7].try_into().expect("Name must be a 6 bytes");
|
||||
let total_supply = u128::from_le_bytes(
|
||||
data[7..23]
|
||||
.try_into()
|
||||
.expect("Total supply must be 16 bytes little-endian"),
|
||||
);
|
||||
let metadata_id = AccountId::new(
|
||||
data[23..TOKEN_DEFINITION_DATA_SIZE]
|
||||
.try_into()
|
||||
.expect("Token Program expects valid Account Id for Metadata"),
|
||||
);
|
||||
|
||||
let this = Some(Self {
|
||||
account_type,
|
||||
name,
|
||||
total_supply,
|
||||
metadata_id,
|
||||
});
|
||||
|
||||
match account_type {
|
||||
TOKEN_STANDARD_NONFUNGIBLE if total_supply != 1 => None,
|
||||
TOKEN_STANDARD_FUNGIBLE_TOKEN if metadata_id != AccountId::new([0; 32]) => None,
|
||||
_ => this,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenHolding {
|
||||
fn parse(data: &[u8]) -> Option<Self> {
|
||||
if data.len() != TOKEN_HOLDING_DATA_SIZE || data[0] != TOKEN_HOLDING_TYPE {
|
||||
None
|
||||
} else {
|
||||
let account_type = data[0];
|
||||
let definition_id = AccountId::new(data[1..33].try_into().unwrap());
|
||||
let balance = u128::from_le_bytes(data[33..].try_into().unwrap());
|
||||
Some(Self {
|
||||
definition_id,
|
||||
balance,
|
||||
account_type,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WalletCore {
|
||||
config_path: PathBuf,
|
||||
config_overrides: Option<WalletConfigOverrides>,
|
||||
storage: WalletChainStore,
|
||||
storage_path: PathBuf,
|
||||
poller: TxPoller,
|
||||
@ -186,7 +109,7 @@ impl WalletCore {
|
||||
) -> Result<Self> {
|
||||
let mut config = WalletConfig::from_path_or_initialize_default(&config_path)
|
||||
.with_context(|| format!("Failed to deserialize wallet config at {config_path:#?}"))?;
|
||||
if let Some(config_overrides) = config_overrides {
|
||||
if let Some(config_overrides) = config_overrides.clone() {
|
||||
config.apply_overrides(config_overrides);
|
||||
}
|
||||
|
||||
@ -205,6 +128,7 @@ impl WalletCore {
|
||||
poller: tx_poller,
|
||||
sequencer_client,
|
||||
last_synced_block,
|
||||
config_overrides,
|
||||
})
|
||||
}
|
||||
|
||||
@ -543,4 +467,16 @@ impl WalletCore {
|
||||
.insert_private_account_data(affected_account_id, new_acc);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn config_path(&self) -> &PathBuf {
|
||||
&self.config_path
|
||||
}
|
||||
|
||||
pub fn storage_path(&self) -> &PathBuf {
|
||||
&self.storage_path
|
||||
}
|
||||
|
||||
pub fn config_overrides(&self) -> &Option<WalletConfigOverrides> {
|
||||
&self.config_overrides
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,8 +1,9 @@
|
||||
use common::{error::ExecutionFailureKind, rpc_primitives::requests::SendTxResponse};
|
||||
use nssa::{AccountId, ProgramId, program::Program};
|
||||
use nssa_core::program::PdaSeed;
|
||||
use token_core::TokenHolding;
|
||||
|
||||
use crate::{TokenHolding, WalletCore};
|
||||
use crate::WalletCore;
|
||||
|
||||
fn compute_pool_pda(
|
||||
amm_program_id: ProgramId,
|
||||
@ -123,12 +124,12 @@ impl Amm<'_> {
|
||||
.await
|
||||
.map_err(|_| ExecutionFailureKind::SequencerError)?;
|
||||
|
||||
let definition_token_a_id = TokenHolding::parse(&user_a_acc.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id;
|
||||
let definition_token_b_id = TokenHolding::parse(&user_b_acc.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id;
|
||||
let definition_token_a_id = TokenHolding::try_from(&user_a_acc.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id();
|
||||
let definition_token_b_id = TokenHolding::try_from(&user_b_acc.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_b))?
|
||||
.definition_id();
|
||||
|
||||
let amm_pool =
|
||||
compute_pool_pda(amm_program_id, definition_token_a_id, definition_token_b_id);
|
||||
@ -208,12 +209,12 @@ impl Amm<'_> {
|
||||
.await
|
||||
.map_err(|_| ExecutionFailureKind::SequencerError)?;
|
||||
|
||||
let definition_token_a_id = TokenHolding::parse(&user_a_acc.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id;
|
||||
let definition_token_b_id = TokenHolding::parse(&user_b_acc.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_b))?
|
||||
.definition_id;
|
||||
let definition_token_a_id = TokenHolding::try_from(&user_a_acc.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id();
|
||||
let definition_token_b_id = TokenHolding::try_from(&user_b_acc.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_b))?
|
||||
.definition_id();
|
||||
|
||||
let amm_pool =
|
||||
compute_pool_pda(amm_program_id, definition_token_a_id, definition_token_b_id);
|
||||
@ -242,14 +243,14 @@ impl Amm<'_> {
|
||||
.await
|
||||
.map_err(|_| ExecutionFailureKind::SequencerError)?;
|
||||
|
||||
let token_holder_a = TokenHolding::parse(&token_holder_acc_a.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_a))?;
|
||||
let token_holder_b = TokenHolding::parse(&token_holder_acc_b.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_b))?;
|
||||
let token_holder_a = TokenHolding::try_from(&token_holder_acc_a.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_a))?;
|
||||
let token_holder_b = TokenHolding::try_from(&token_holder_acc_b.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_b))?;
|
||||
|
||||
if token_holder_a.definition_id == token_definition_id {
|
||||
if token_holder_a.definition_id() == token_definition_id {
|
||||
account_id_auth = user_holding_a;
|
||||
} else if token_holder_b.definition_id == token_definition_id {
|
||||
} else if token_holder_b.definition_id() == token_definition_id {
|
||||
account_id_auth = user_holding_b;
|
||||
} else {
|
||||
return Err(ExecutionFailureKind::AccountDataError(token_definition_id));
|
||||
@ -309,12 +310,12 @@ impl Amm<'_> {
|
||||
.await
|
||||
.map_err(|_| ExecutionFailureKind::SequencerError)?;
|
||||
|
||||
let definition_token_a_id = TokenHolding::parse(&user_a_acc.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id;
|
||||
let definition_token_b_id = TokenHolding::parse(&user_b_acc.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id;
|
||||
let definition_token_a_id = TokenHolding::try_from(&user_a_acc.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id();
|
||||
let definition_token_b_id = TokenHolding::try_from(&user_b_acc.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_b))?
|
||||
.definition_id();
|
||||
|
||||
let amm_pool =
|
||||
compute_pool_pda(amm_program_id, definition_token_a_id, definition_token_b_id);
|
||||
@ -395,12 +396,12 @@ impl Amm<'_> {
|
||||
.await
|
||||
.map_err(|_| ExecutionFailureKind::SequencerError)?;
|
||||
|
||||
let definition_token_a_id = TokenHolding::parse(&user_a_acc.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id;
|
||||
let definition_token_b_id = TokenHolding::parse(&user_b_acc.data)
|
||||
.ok_or(ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id;
|
||||
let definition_token_a_id = TokenHolding::try_from(&user_a_acc.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_a))?
|
||||
.definition_id();
|
||||
let definition_token_b_id = TokenHolding::try_from(&user_b_acc.data)
|
||||
.map_err(|_| ExecutionFailureKind::AccountDataError(user_holding_b))?
|
||||
.definition_id();
|
||||
|
||||
let amm_pool =
|
||||
compute_pool_pda(amm_program_id, definition_token_a_id, definition_token_b_id);
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
use common::{error::ExecutionFailureKind, rpc_primitives::requests::SendTxResponse};
|
||||
use nssa::{AccountId, program::Program};
|
||||
use nssa_core::{NullifierPublicKey, SharedSecretKey, encryption::IncomingViewingPublicKey};
|
||||
use token_core::Instruction;
|
||||
|
||||
use crate::{PrivacyPreservingAccount, WalletCore};
|
||||
|
||||
@ -11,15 +12,12 @@ impl Token<'_> {
|
||||
&self,
|
||||
definition_account_id: AccountId,
|
||||
supply_account_id: AccountId,
|
||||
name: [u8; 6],
|
||||
name: String,
|
||||
total_supply: u128,
|
||||
) -> Result<SendTxResponse, ExecutionFailureKind> {
|
||||
let account_ids = vec![definition_account_id, supply_account_id];
|
||||
let program_id = nssa::program::Program::token().id();
|
||||
// Instruction must be: [0x00 || total_supply (little-endian 16 bytes) || name (6 bytes)]
|
||||
let mut instruction = vec![0u8; 23];
|
||||
instruction[1..17].copy_from_slice(&total_supply.to_le_bytes());
|
||||
instruction[17..].copy_from_slice(&name);
|
||||
let instruction = Instruction::NewFungibleDefinition { name, total_supply };
|
||||
let message = nssa::public_transaction::Message::try_new(
|
||||
program_id,
|
||||
account_ids,
|
||||
@ -39,10 +37,10 @@ impl Token<'_> {
|
||||
&self,
|
||||
definition_account_id: AccountId,
|
||||
supply_account_id: AccountId,
|
||||
name: [u8; 6],
|
||||
name: String,
|
||||
total_supply: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_definition(name, total_supply);
|
||||
let instruction = Instruction::NewFungibleDefinition { name, total_supply };
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -69,10 +67,10 @@ impl Token<'_> {
|
||||
&self,
|
||||
definition_account_id: AccountId,
|
||||
supply_account_id: AccountId,
|
||||
name: [u8; 6],
|
||||
name: String,
|
||||
total_supply: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_definition(name, total_supply);
|
||||
let instruction = Instruction::NewFungibleDefinition { name, total_supply };
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -99,10 +97,10 @@ impl Token<'_> {
|
||||
&self,
|
||||
definition_account_id: AccountId,
|
||||
supply_account_id: AccountId,
|
||||
name: [u8; 6],
|
||||
name: String,
|
||||
total_supply: u128,
|
||||
) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_definition(name, total_supply);
|
||||
let instruction = Instruction::NewFungibleDefinition { name, total_supply };
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -132,11 +130,9 @@ impl Token<'_> {
|
||||
) -> Result<SendTxResponse, ExecutionFailureKind> {
|
||||
let account_ids = vec![sender_account_id, recipient_account_id];
|
||||
let program_id = nssa::program::Program::token().id();
|
||||
// Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 ||
|
||||
// 0x00 || 0x00 || 0x00].
|
||||
let mut instruction = vec![0u8; 23];
|
||||
instruction[0] = 0x01;
|
||||
instruction[1..17].copy_from_slice(&amount.to_le_bytes());
|
||||
let instruction = Instruction::Transfer {
|
||||
amount_to_transfer: amount,
|
||||
};
|
||||
let Ok(nonces) = self.0.get_accounts_nonces(vec![sender_account_id]).await else {
|
||||
return Err(ExecutionFailureKind::SequencerError);
|
||||
};
|
||||
@ -170,7 +166,9 @@ impl Token<'_> {
|
||||
recipient_account_id: AccountId,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_transfer(amount);
|
||||
let instruction = Instruction::Transfer {
|
||||
amount_to_transfer: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -199,7 +197,9 @@ impl Token<'_> {
|
||||
recipient_ipk: IncomingViewingPublicKey,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_transfer(amount);
|
||||
let instruction = Instruction::Transfer {
|
||||
amount_to_transfer: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -230,7 +230,9 @@ impl Token<'_> {
|
||||
recipient_account_id: AccountId,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_transfer(amount);
|
||||
let instruction = Instruction::Transfer {
|
||||
amount_to_transfer: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -259,7 +261,9 @@ impl Token<'_> {
|
||||
recipient_account_id: AccountId,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_transfer(amount);
|
||||
let instruction = Instruction::Transfer {
|
||||
amount_to_transfer: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -289,7 +293,9 @@ impl Token<'_> {
|
||||
recipient_ipk: IncomingViewingPublicKey,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_transfer(amount);
|
||||
let instruction = Instruction::Transfer {
|
||||
amount_to_transfer: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -322,7 +328,9 @@ impl Token<'_> {
|
||||
amount: u128,
|
||||
) -> Result<SendTxResponse, ExecutionFailureKind> {
|
||||
let account_ids = vec![definition_account_id, holder_account_id];
|
||||
let instruction = token_program_preparation_burn(amount);
|
||||
let instruction = Instruction::Burn {
|
||||
amount_to_burn: amount,
|
||||
};
|
||||
|
||||
let Ok(nonces) = self.0.get_accounts_nonces(vec![holder_account_id]).await else {
|
||||
return Err(ExecutionFailureKind::SequencerError);
|
||||
@ -355,7 +363,9 @@ impl Token<'_> {
|
||||
holder_account_id: AccountId,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_burn(amount);
|
||||
let instruction = Instruction::Burn {
|
||||
amount_to_burn: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -383,7 +393,9 @@ impl Token<'_> {
|
||||
holder_account_id: AccountId,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_burn(amount);
|
||||
let instruction = Instruction::Burn {
|
||||
amount_to_burn: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -412,7 +424,9 @@ impl Token<'_> {
|
||||
holder_account_id: AccountId,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_burn(amount);
|
||||
let instruction = Instruction::Burn {
|
||||
amount_to_burn: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -442,7 +456,9 @@ impl Token<'_> {
|
||||
amount: u128,
|
||||
) -> Result<SendTxResponse, ExecutionFailureKind> {
|
||||
let account_ids = vec![definition_account_id, holder_account_id];
|
||||
let instruction = token_program_preparation_mint(amount);
|
||||
let instruction = Instruction::Mint {
|
||||
amount_to_mint: amount,
|
||||
};
|
||||
|
||||
let Ok(nonces) = self
|
||||
.0
|
||||
@ -481,7 +497,9 @@ impl Token<'_> {
|
||||
holder_account_id: AccountId,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_mint(amount);
|
||||
let instruction = Instruction::Mint {
|
||||
amount_to_mint: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -510,7 +528,9 @@ impl Token<'_> {
|
||||
holder_ipk: IncomingViewingPublicKey,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, [SharedSecretKey; 2]), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_mint(amount);
|
||||
let instruction = Instruction::Mint {
|
||||
amount_to_mint: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -541,7 +561,9 @@ impl Token<'_> {
|
||||
holder_account_id: AccountId,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_mint(amount);
|
||||
let instruction = Instruction::Mint {
|
||||
amount_to_mint: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -570,7 +592,9 @@ impl Token<'_> {
|
||||
holder_account_id: AccountId,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_mint(amount);
|
||||
let instruction = Instruction::Mint {
|
||||
amount_to_mint: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -600,7 +624,9 @@ impl Token<'_> {
|
||||
holder_ipk: IncomingViewingPublicKey,
|
||||
amount: u128,
|
||||
) -> Result<(SendTxResponse, SharedSecretKey), ExecutionFailureKind> {
|
||||
let instruction = token_program_preparation_mint(amount);
|
||||
let instruction = Instruction::Mint {
|
||||
amount_to_mint: amount,
|
||||
};
|
||||
let instruction_data =
|
||||
Program::serialize_instruction(instruction).expect("Instruction should serialize");
|
||||
|
||||
@ -626,42 +652,3 @@ impl Token<'_> {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn token_program_preparation_transfer(amount: u128) -> Vec<u8> {
|
||||
// Instruction must be: [0x01 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 ||
|
||||
// 0x00 || 0x00 || 0x00].
|
||||
let mut instruction = vec![0u8; 23];
|
||||
instruction[0] = 0x01;
|
||||
instruction[1..17].copy_from_slice(&amount.to_le_bytes());
|
||||
|
||||
instruction
|
||||
}
|
||||
|
||||
fn token_program_preparation_definition(name: [u8; 6], total_supply: u128) -> Vec<u8> {
|
||||
// Instruction must be: [0x00 || total_supply (little-endian 16 bytes) || name (6 bytes)]
|
||||
let mut instruction = vec![0u8; 23];
|
||||
instruction[1..17].copy_from_slice(&total_supply.to_le_bytes());
|
||||
instruction[17..].copy_from_slice(&name);
|
||||
|
||||
instruction
|
||||
}
|
||||
|
||||
fn token_program_preparation_burn(amount: u128) -> Vec<u8> {
|
||||
// Instruction must be: [0x03 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 ||
|
||||
// 0x00 || 0x00 || 0x00].
|
||||
let mut instruction = vec![0; 23];
|
||||
instruction[0] = 0x03;
|
||||
instruction[1..17].copy_from_slice(&amount.to_le_bytes());
|
||||
|
||||
instruction
|
||||
}
|
||||
|
||||
fn token_program_preparation_mint(amount: u128) -> Vec<u8> {
|
||||
// Instruction must be: [0x04 || amount (little-endian 16 bytes) || 0x00 || 0x00 || 0x00 ||
|
||||
// 0x00 || 0x00 || 0x00].
|
||||
let mut instruction = vec![0; 23];
|
||||
instruction[0] = 0x04;
|
||||
instruction[1..17].copy_from_slice(&amount.to_le_bytes());
|
||||
|
||||
instruction
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user