pub struct Contract(pub AccountId);
Expand description
Contract-related interactions with the NEAR Protocol
The Contract
struct provides methods to interact with NEAR contracts, including calling functions, querying storage, and deploying contracts.
§Examples
use near_api::*;
let abi = Contract("some_contract.testnet".parse()?).abi().fetch_from_testnet().await?;
println!("ABI: {:?}", abi);
Tuple Fields§
§0: AccountId
Implementations§
Source§impl Contract
impl Contract
Sourcepub fn call_function<Args>(
&self,
method_name: &str,
args: Args,
) -> Result<CallFunctionBuilder, BuilderError>where
Args: Serialize,
pub fn call_function<Args>(
&self,
method_name: &str,
args: Args,
) -> Result<CallFunctionBuilder, BuilderError>where
Args: Serialize,
Prepares a call to a contract function.
This will return a builder that can be used to prepare a query or a transaction.
§Calling view function get_number
use near_api::*;
let number: Data<u64> = Contract("some_contract.testnet".parse()?)
.call_function("get_number", ())?
.read_only()
.fetch_from_testnet()
.await?;
println!("Number: {:?}", number);
§Calling a state changing function set_number
use near_api::*;
use serde_json::json;
let signer = Signer::new(Signer::from_ledger())?;
let result: near_primitives::views::FinalExecutionOutcomeView = Contract("some_contract.testnet".parse()?)
.call_function("set_number", json!({ "number": 100 }))?
.transaction()
// Optional
.gas(NearGas::from_tgas(200))
.with_signer("alice.testnet".parse()?, signer)
.send_to_testnet()
.await?;
Sourcepub const fn deploy(contract: AccountId) -> DeployBuilder
pub const fn deploy(contract: AccountId) -> DeployBuilder
Prepares a transaction to deploy a contract to the provided account.
The code is the wasm bytecode of the contract. For more information on how to compile your contract, please refer to the NEAR documentation.
§Deploying the contract
use near_api::*;
let code = std::fs::read("path/to/your/contract.wasm")?;
let signer = Signer::new(Signer::from_ledger())?;
let result: near_primitives::views::FinalExecutionOutcomeView = Contract::deploy("contract.testnet".parse()?)
.use_code(code)
.without_init_call()
.with_signer(signer)
.send_to_testnet()
.await?;
§Deploying the contract with an init call
use near_api::*;
use serde_json::json;
let code = std::fs::read("path/to/your/contract.wasm")?;
let signer = Signer::new(Signer::from_ledger())?;
let result: near_primitives::views::FinalExecutionOutcomeView = Contract::deploy("contract.testnet".parse()?)
.use_code(code)
.with_init_call("init", json!({ "number": 100 }))?
// Optional
.gas(NearGas::from_tgas(200))
.with_signer(signer)
.send_to_testnet()
.await?;
Sourcepub const fn deploy_global_contract_code(code: Vec<u8>) -> GlobalDeployBuilder
pub const fn deploy_global_contract_code(code: Vec<u8>) -> GlobalDeployBuilder
Prepares a transaction to deploy a code to the global contract code storage.
This will allow other users to reference given code as hash or account-id and reduce the gas cost for deployment.
Please be aware that the deploy costs 10x more compared to the regular costs and the tokens are burnt with no way to get it back.
§Example deploying a contract to the global contract code storage as hash
use near_api::*;
let code = std::fs::read("path/to/your/contract.wasm")?;
let signer = Signer::new(Signer::from_ledger())?;
let result: near_primitives::views::FinalExecutionOutcomeView = Contract::deploy_global_contract_code(code)
.as_hash()
.with_signer("some-account.testnet".parse()?, signer)
.send_to_testnet()
.await?;
§Example deploying a contract to the global contract code storage as account-id
The difference between the hash and account-id version is that the account-id version upgradable and can be changed.
use near_api::*;
let code = std::fs::read("path/to/your/contract.wasm")?;
let signer = Signer::new(Signer::from_ledger())?;
let result: near_primitives::views::FinalExecutionOutcomeView = Contract::deploy_global_contract_code(code)
.as_account_id("nft-contract.testnet".parse()?)
.with_signer(signer)
.send_to_testnet()
.await?;
Sourcepub fn abi(
&self,
) -> QueryBuilder<PostprocessHandler<Option<AbiRoot>, CallResultHandler<Vec<u8>>>>
pub fn abi( &self, ) -> QueryBuilder<PostprocessHandler<Option<AbiRoot>, CallResultHandler<Vec<u8>>>>
Sourcepub fn wasm(&self) -> QueryBuilder<ViewCodeHandler>
pub fn wasm(&self) -> QueryBuilder<ViewCodeHandler>
Prepares a query to fetch the wasm code (Data<ContractCodeView>) of the contract.
§Example
use near_api::*;
let wasm = Contract("some_contract.testnet".parse()?).wasm().fetch_from_testnet().await?;
println!("WASM: {:?}", wasm.data.code.len());
Sourcepub fn view_storage_with_prefix(
&self,
prefix: Vec<u8>,
) -> QueryBuilder<ViewStateHandler>
pub fn view_storage_with_prefix( &self, prefix: Vec<u8>, ) -> QueryBuilder<ViewStateHandler>
Prepares a query to fetch the storage of the contract (Data<ViewStateResult>) using the given prefix as a filter.
It helpful if you are aware of the storage that you are looking for.
§Example
use near_api::*;
let storage = Contract("some_contract.testnet".parse()?)
.view_storage_with_prefix(b"se".to_vec())
.fetch_from_testnet()
.await?;
println!("Storage: {:?}", storage);
Sourcepub fn view_storage(&self) -> QueryBuilder<ViewStateHandler>
pub fn view_storage(&self) -> QueryBuilder<ViewStateHandler>
Prepares a query to fetch the storage of the contract (Data<ViewStateResult>).
Please be aware that large storage queries might fail.
§Example
use near_api::*;
let storage = Contract("some_contract.testnet".parse()?)
.view_storage()
.fetch_from_testnet()
.await?;
println!("Storage: {:?}", storage);
Sourcepub fn contract_source_metadata(
&self,
) -> QueryBuilder<CallResultHandler<ContractSourceMetadata>>
pub fn contract_source_metadata( &self, ) -> QueryBuilder<CallResultHandler<ContractSourceMetadata>>
Prepares a query to fetch the contract source metadata(Data<ContractSourceMetadata>) using NEP-330 standard.
The contract source metadata is a standard interface that allows auditing and viewing source code for a deployed smart contract. Implementation of this standard is purely optional but is recommended for developers whose contracts are open source.
§Examples
use near_api::*;
let source_metadata = Contract("some_contract.testnet".parse()?)
.contract_source_metadata()
.fetch_from_testnet()
.await?;
println!("Source metadata: {:?}", source_metadata);
A more verbose runnable example is present in examples/contract_source_metadata.rs
:
use near_api::*;
use std::str::FromStr;
#[tokio::main]
async fn main() {
for (account_name, expected_json_metadata) in [
("desolate-toad.testnet", FIRST_METADATA),
("fat-fabulous-toad.testnet", SECOND_METADATA),
] {
let source_metadata = Contract(AccountId::from_str(account_name).expect("no err"))
.contract_source_metadata()
.fetch_from_testnet()
.await
.expect("no network or rpc err");
assert_eq!(
expected_json_metadata,
serde_json::to_string_pretty(&source_metadata.data).expect("no ser err")
);
}
}
const FIRST_METADATA: &str = r#"{
"version": "0.1.0",
"link": "https://github.com/dj8yfo/quiet_glen",
"standards": [
{
"standard": "nep330",
"version": "1.2.0"
}
],
"build_info": null
}"#;
const SECOND_METADATA: &str = r#"{
"version": "0.1.0",
"link": "https://github.com/dj8yfo/quiet_glen/tree/8d8a8a0fe86a1d8eb3bce45f04ab1a65fecf5a1b",
"standards": [
{
"standard": "nep330",
"version": "1.2.0"
}
],
"build_info": {
"build_environment": "sourcescan/cargo-near:0.13.3-rust-1.84.0@sha256:722198ddb92d1b82cbfcd3a4a9f7fba6fd8715f4d0b5fb236d8725c4883f97de",
"build_command": [
"cargo",
"near",
"build",
"non-reproducible-wasm",
"--locked"
],
"contract_path": "",
"source_code_snapshot": "git+https://github.com/dj8yfo/quiet_glen?rev=8d8a8a0fe86a1d8eb3bce45f04ab1a65fecf5a1b",
"output_wasm_path": null
}
}"#;
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Contract
impl RefUnwindSafe for Contract
impl Send for Contract
impl Sync for Contract
impl Unpin for Contract
impl UnwindSafe for Contract
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self
to use its Display
implementation when
Debug
-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self
, then passes self.as_ref()
into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self
, then passes self.as_mut()
into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self
, then passes self.deref()
into the pipe function.Source§impl<T> PolicyExt for Twhere
T: ?Sized,
impl<T> PolicyExt for Twhere
T: ?Sized,
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B>
of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B>
of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R>
view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R>
view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref()
only in debug builds, and is erased in release
builds.