Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"scripts": {
"bindings:stellar": "tsx stellar/scripts/generate-bindings.ts",
"build:stellar": "pnpm bindings:stellar && cd stellar && cargo build --target wasm32-unknown-unknown --release",
"test:stellar-bindings": "vitest run stellar/scripts/stealth-batch-sender-bindings.test.ts stellar/scripts/bindings-portability.test.ts"
"test:stellar-bindings": "vitest run stellar/scripts/stealth-batch-sender-bindings.test.ts stellar/scripts/governance-bindings.test.ts"
},
"pnpm": {
"onlyBuiltDependencies": ["esbuild"]
Expand Down
2 changes: 1 addition & 1 deletion stellar/abi/update.sh
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ echo "Building contracts..."
cargo build --target wasm32-unknown-unknown --release

echo "Extracting ABI snapshots..."
for contract in stealth_announcer stealth_registry stealth_sender stealth_batch_sender wraith_names; do
for contract in stealth_announcer stealth_registry stealth_sender stealth_batch_sender wraith_names stealth_splitter stealth_vault wraith_asset_policy; do
stellar contract info interface \
--wasm "target/wasm32-unknown-unknown/release/${contract}.wasm" \
--output json-formatted > "abi/${contract}.json"
Expand Down
2 changes: 2 additions & 0 deletions stellar/bindings/typescript/governance/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
out/
54 changes: 54 additions & 0 deletions stellar/bindings/typescript/governance/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# governance JS

JS library for interacting with [Soroban](https://soroban.stellar.org/) smart contract `governance` via Soroban RPC.

This library was automatically generated by Soroban CLI using a command similar to:

```bash
soroban contract bindings ts \
--rpc-url INSERT_RPC_URL_HERE \
--network-passphrase "INSERT_NETWORK_PASSPHRASE_HERE" \
--contract-id INSERT_CONTRACT_ID_HERE \
--output-dir ./path/to/governance
```

The network passphrase and contract ID are exported from [index.ts](./src/index.ts) in the `networks` constant. If you are the one who generated this library and you know that this contract is also deployed to other networks, feel free to update `networks` with other valid options. This will help your contract consumers use this library more easily.

# To publish or not to publish

This library is suitable for publishing to NPM. You can publish it to NPM using the `npm publish` command.

But you don't need to publish this library to NPM to use it. You can add it to your project's `package.json` using a file path:

```json
"dependencies": {
"governance": "./path/to/this/folder"
}
```

However, we've actually encountered [frustration](https://github.com/stellar/soroban-example-dapp/pull/117#discussion_r1232873560) using local libraries with NPM in this way. Though it seems a bit messy, we suggest generating the library directly to your `node_modules` folder automatically after each install by using a `postinstall` script. We've had the least trouble with this approach. NPM will automatically remove what it sees as erroneous directories during the `install` step, and then regenerate them when it gets to your `postinstall` step, which will keep the library up-to-date with your contract.

```json
"scripts": {
"postinstall": "soroban contract bindings ts --rpc-url INSERT_RPC_URL_HERE --network-passphrase \"INSERT_NETWORK_PASSPHRASE_HERE\" --id INSERT_CONTRACT_ID_HERE --name governance"
}
```

Obviously you need to adjust the above command based on the actual command you used to generate the library.

# Use it

Now that you have your library up-to-date and added to your project, you can import it in a file and see inline documentation for all of its exported methods:

```js
import { Contract, networks } from "governance"

const contract = new Contract({
...networks.futurenet, // for example; check which networks this library exports
rpcUrl: '...', // use your own, or find one for testing at https://soroban.stellar.org/docs/reference/rpc#public-rpc-providers
})

contract.|
```

As long as your editor is configured to show JavaScript/TypeScript documentation, you can pause your typing at that `|` to get a list of all exports and inline-documentation for each. It exports a separate [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) function for each method in the smart contract, with documentation for each generated from the comments the contract's author included in the original source code.
17 changes: 17 additions & 0 deletions stellar/bindings/typescript/governance/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"version": "0.0.0",
"name": "governance",
"type": "module",
"exports": "./dist/index.js",
"typings": "dist/index.d.ts",
"scripts": {
"build": "tsc"
},
"dependencies": {
"@stellar/stellar-sdk": "^16.0.1",
"buffer": "6.0.3"
},
"devDependencies": {
"typescript": "^5.6.2"
}
}
179 changes: 179 additions & 0 deletions stellar/bindings/typescript/governance/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
import { Buffer } from "buffer";
import { Address } from "@stellar/stellar-sdk";
import {
AssembledTransaction,
Client as ContractClient,
ClientOptions as ContractClientOptions,
MethodOptions,
Result,
Spec as ContractSpec,
} from "@stellar/stellar-sdk/contract";
import type {
u32,
i32,
u64,
i64,
u128,
i128,
u256,
i256,
Option,
Timepoint,
Duration,
} from "@stellar/stellar-sdk/contract";
export * from "@stellar/stellar-sdk";
export * as contract from "@stellar/stellar-sdk/contract";
export * as rpc from "@stellar/stellar-sdk/rpc";

if (typeof window !== "undefined") {
//@ts-ignore Buffer exists
window.Buffer = window.Buffer || Buffer;
}

/**
* Governance configuration.
*/
export interface GovernanceConfig {
token: Buffer;
quorum: i128;
voting_period: u32;
timelock: u32;
}

/**
* Proposal state.
*/
export type ProposalState =
| {tag: "Active", values: void}
| {tag: "Succeeded", values: void}
| {tag: "Defeated", values: void}
| {tag: "Executed", values: void}
| {tag: "Canceled", values: void};

/**
* A governance proposal.
*/
export interface Proposal {
id: u32;
proposer: Buffer;
target: Buffer;
function: string;
args: Buffer;
description: string;
for_votes: i128;
against_votes: i128;
start_ledger: u32;
end_ledger: u32;
state: ProposalState;
}

/**
* Vote record.
*/
export interface Vote {
voter: Buffer;
support: boolean;
weight: i128;
}

/**
* Governance errors.
*/
export type GovernanceError =
| {tag: "AlreadyInitialized", values: void}
| {tag: "NotInitialized", values: void}
| {tag: "ProposalNotFound", values: void}
| {tag: "ProposalNotActive", values: void}
| {tag: "AlreadyVoted", values: void}
| {tag: "ProposalNotSucceeded", values: void}
| {tag: "TimelockNotExpired", values: void}
| {tag: "Unauthorized", values: void};

export class Client extends ContractClient {
public spec: ContractSpec;
public options: ContractClientOptions;

constructor(options: ContractClientOptions) {
super(options);

Check failure on line 97 in stellar/bindings/typescript/governance/src/index.ts

View workflow job for this annotation

GitHub Actions / stellar

stellar/scripts/stealth-batch-sender-bindings.test.ts > stellar bindings portability check > governance client exports are available

TypeError: Cannot read properties of undefined (reading 'server') ❯ new Client node_modules/.pnpm/@stellar+stellar-sdk@15.1.0/node_modules/@stellar/stellar-sdk/lib/contract/client.js:89:17 ❯ new Client stellar/bindings/typescript/governance/src/index.ts:97:5 ❯ stellar/scripts/stealth-batch-sender-bindings.test.ts:32:20

Check failure on line 97 in stellar/bindings/typescript/governance/src/index.ts

View workflow job for this annotation

GitHub Actions / stellar

stellar/scripts/governance-bindings.test.ts > governance generated client > assembles a typed get_config call

TypeError: Cannot read properties of undefined (reading 'server') ❯ new Client node_modules/.pnpm/@stellar+stellar-sdk@15.1.0/node_modules/@stellar/stellar-sdk/lib/contract/client.js:89:17 ❯ new Client stellar/bindings/typescript/governance/src/index.ts:97:5 ❯ stellar/scripts/governance-bindings.test.ts:7:20
this.options = options;
this.spec = new ContractSpec({
...this.options,
contractId: this.options.contractId,
});
}

/**
* Initialize the governance contract.
*/
public async init(args: {
admin: Buffer;
token: Buffer;
quorum: i128;
voting_period: u32;
timelock: u32;
}, options?: MethodOptions): Promise<AssembledTransaction<GovernanceError>> {
return this.call("init", args, options);
}

/**
* Get the current governance configuration.
*/
public async get_config(options?: MethodOptions): Promise<AssembledTransaction<GovernanceError>> {
return this.call("get_config", {}, options);
}

/**
* Create a new governance proposal.
*/
public async propose(args: {
proposer: Buffer;
target: Buffer;
function: string;
args: Buffer;
description: string;
}, options?: MethodOptions): Promise<AssembledTransaction<GovernanceError>> {
return this.call("propose", args, options);
}

/**
* Get a proposal by ID.
*/
public async get_proposal(args: { proposal_id: u32 }, options?: MethodOptions): Promise<AssembledTransaction<GovernanceError>> {
return this.call("get_proposal", args, options);
}

/**
* Cast a vote on an active proposal.
*/
public async vote(args: {
voter: Buffer;
proposal_id: u32;
support: boolean;
}, options?: MethodOptions): Promise<AssembledTransaction<GovernanceError>> {
return this.call("vote", args, options);
}

/**
* Get the vote record for a voter on a proposal.
*/
public async get_vote(args: {
proposal_id: u32;
voter: Buffer;
}, options?: MethodOptions): Promise<AssembledTransaction<GovernanceError>> {
return this.call("get_vote", args, options);
}

/**
* Execute a proposal that has passed.
*/
public async execute(args: { proposal_id: u32 }, options?: MethodOptions): Promise<AssembledTransaction<GovernanceError>> {
return this.call("execute", args, options);
}

/**
* Cancel a proposal.
*/
public async cancel(args: { proposal_id: u32 }, options?: MethodOptions): Promise<AssembledTransaction<GovernanceError>> {
return this.call("cancel", args, options);
}
}
98 changes: 98 additions & 0 deletions stellar/bindings/typescript/governance/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "ESNext", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "NodeNext", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
"moduleResolution": "nodenext", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
"declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
// "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
// "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
// "strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
},
"include": [
"src/*"
]
}
Loading
Loading