templar_registry_contract/
lib.rs

1#![allow(clippy::needless_pass_by_value)]
2
3mod state;
4
5use std::ops::{Deref, DerefMut};
6
7use near_sdk::{
8    assert_one_yocto, env,
9    json_types::{Base58CryptoHash, Base64VecU8},
10    near, require, AccountId, CryptoHash, Gas, NearToken, PanicOnDefault, Promise, PromiseOrValue,
11};
12use near_sdk_contract_tools::{owner::Owner, Owner};
13use templar_common::{
14    contract::list,
15    registry::{
16        Deployment, RegistryEntryView, RegistryEvent, VersionAvailability, VersionInfo,
17        VersionSource,
18    },
19    self_ext,
20    upgrade::{UpgradeSource, MIGRATE_METHOD},
21    versioned_state::{impl_versioned_state, StateVersion, VersionedState},
22};
23
24type State = state::V1;
25
26#[derive(Debug, Clone)]
27#[near(serializers = [json, borsh])]
28pub enum VersionEntry {
29    Code {
30        hash: CryptoHash,
31        code: Option<Vec<u8>>,
32    },
33    GlobalHash(CryptoHash),
34}
35
36impl VersionEntry {
37    pub fn code_hash(&self) -> CryptoHash {
38        match self {
39            Self::Code { hash, .. } | Self::GlobalHash(hash) => *hash,
40        }
41    }
42
43    fn availability(&self) -> VersionAvailability {
44        match self {
45            Self::Code {
46                code: Some(code), ..
47            } => VersionAvailability::Stored {
48                // Unreachable: a stored value cannot exceed the 4 MiB storage-value limit.
49                code_len: u32::try_from(code.len()).unwrap_or(u32::MAX),
50            },
51            Self::Code { code: None, .. } => VersionAvailability::Removed,
52            Self::GlobalHash(_) => VersionAvailability::Global,
53        }
54    }
55
56    fn info(&self) -> VersionInfo {
57        VersionInfo {
58            code_hash: self.code_hash().into(),
59            availability: self.availability(),
60        }
61    }
62}
63
64#[derive(Debug, Clone)]
65#[near(serializers = [borsh])]
66pub enum RegistryEntry {
67    Reserved,
68    Deployed(Deployment),
69}
70
71impl RegistryEntry {
72    fn view(&self) -> RegistryEntryView {
73        match self {
74            Self::Reserved => RegistryEntryView::Reserved,
75            Self::Deployed(deployment) => RegistryEntryView::Deployed(deployment.clone()),
76        }
77    }
78}
79
80#[derive(PanicOnDefault, Owner)]
81#[near(contract_state)]
82pub struct Contract {
83    pub state: VersionedState<State>,
84}
85
86// Generates the private `migrate()` entrypoint plus the `get_stored_state_version` /
87// `get_target_state_version` / `needs_migration` views.
88impl_versioned_state!(Contract, State, crate::state::Migration);
89
90// `versions` and `registry` live on `State`; deref so the methods below keep reaching them
91// directly.
92impl Deref for Contract {
93    type Target = State;
94
95    fn deref(&self) -> &Self::Target {
96        &self.state
97    }
98}
99
100impl DerefMut for Contract {
101    fn deref_mut(&mut self) -> &mut Self::Target {
102        &mut self.state
103    }
104}
105
106#[near]
107impl Contract {
108    /// Gas reserved for the batched `migrate` in [`Self::upgrade`].
109    pub const GAS_FOR_MIGRATE: Gas = Gas::from_tgas(250);
110
111    /// Most a single [`Self::get_version_code_chunk`] will return.
112    ///
113    /// A view's return value reaches the caller as a JSON array of one integer per byte, so the
114    /// response body runs several times the payload; this keeps it inside what RPC providers serve.
115    pub const MAX_CODE_CHUNK_LEN: u32 = 128 * 1024;
116
117    #[init]
118    pub fn new() -> Self {
119        let mut self_ = Self {
120            state: State::new(()),
121        };
122
123        self_.init(&env::predecessor_account_id());
124
125        self_
126    }
127
128    /// Atomically deploy new code and run its `migrate` in one receipt, so a failed migration
129    /// reverts the deploy with it. `migrate_args` names the `state::Migration` chain to run, and is
130    /// empty when the stored state version is already the new code's.
131    ///
132    /// The only way to replace the code of a registry whose full-access keys have been removed.
133    #[payable]
134    pub fn upgrade(&mut self, code: UpgradeSource, migrate_args: Base64VecU8) -> Promise {
135        assert_one_yocto();
136        self.assert_owner();
137
138        require!(!code.is_empty_code(), "Upgrade code must not be empty");
139
140        near_sdk::log!("Upgrading registry to {:?}", code.summary());
141
142        code.deploy_and_migrate(MIGRATE_METHOD, migrate_args, Self::GAS_FOR_MIGRATE)
143    }
144
145    pub fn list_versions(&self, count: Option<u32>, offset: Option<u32>) -> Vec<&String> {
146        list(self.versions.keys(), offset, count)
147    }
148
149    pub fn get_version_code_hash(&self, version_key: String) -> Option<Base58CryptoHash> {
150        self.versions
151            .get(&version_key)
152            .map(VersionEntry::code_hash)
153            .map(Into::into)
154    }
155
156    /// A registered version's hash and whether [`Self::deploy`] can still use it.
157    ///
158    /// `list_versions` keeps listing a version whose code `remove_version` cleared, and
159    /// `get_version_code_hash` keeps answering for it, so membership alone cannot tell a
160    /// deployable version from one that will panic partway through a deploy.
161    pub fn get_version(&self, version_key: String) -> Option<VersionInfo> {
162        self.versions.get(&version_key).map(VersionEntry::info)
163    }
164
165    /// Whether a name is taken, and by what.
166    ///
167    /// [`Self::deploy`] refuses any name already present, so a `Reserved` name is as unusable as a
168    /// deployed one — a state [`Self::get_deployment`] reports as absent.
169    pub fn get_registry_entry(&self, account_id: AccountId) -> Option<RegistryEntryView> {
170        self.registry.get(&account_id).map(RegistryEntry::view)
171    }
172
173    /// Bytes `[offset, offset + len)` of a version's stored code, or `None` if it has none.
174    ///
175    /// Borsh-serialized and chunked: the JSON encoding would base64 the blob and the RPC would
176    /// then re-expand it to one integer per byte. Reading a whole contract back is the last
177    /// resort anyway — [`Self::get_version`] reports the hash, which usually resolves against a
178    /// released artifact without touching this at all.
179    ///
180    /// An `offset` past the end reads empty, so a caller can loop until it stops making progress.
181    #[result_serializer(borsh)]
182    pub fn get_version_code_chunk(
183        &self,
184        version_key: String,
185        offset: u32,
186        len: u32,
187    ) -> Option<Vec<u8>> {
188        require!(
189            len <= Self::MAX_CODE_CHUNK_LEN,
190            format!("len exceeds maximum of {}", Self::MAX_CODE_CHUNK_LEN),
191        );
192
193        let code = match self.versions.get(&version_key)? {
194            VersionEntry::Code { code, .. } => code.as_ref()?,
195            VersionEntry::GlobalHash(_) => return None,
196        };
197
198        let start = (offset as usize).min(code.len());
199        let end = start.saturating_add(len as usize).min(code.len());
200
201        Some(code[start..end].to_vec())
202    }
203
204    pub fn list_deployments(&self, count: Option<u32>, offset: Option<u32>) -> Vec<&AccountId> {
205        list(
206            self.registry
207                .iter()
208                .filter(|(_, e)| matches!(e, RegistryEntry::Deployed(_)))
209                .map(|(a, _)| a),
210            offset,
211            count,
212        )
213    }
214
215    pub fn get_deployment(&self, account_id: AccountId) -> Option<&Deployment> {
216        self.registry.get(&account_id).and_then(|e| match e {
217            RegistryEntry::Reserved => None,
218            RegistryEntry::Deployed(deployment) => Some(deployment),
219        })
220    }
221
222    /// Open a throwaway sub-account funded by the attached deposit, for a caller to act on and
223    /// then `delete_account` back into the registry.
224    ///
225    /// `prefix` separates the publish and probe accounts so a probe cannot land on an in-flight
226    /// publish.
227    fn scratch_account(prefix: &str) -> Promise {
228        let account_id: AccountId = format!("{prefix}.{}", env::current_account_id())
229            .parse()
230            .unwrap_or_else(|_| {
231                templar_common::panic_with_message("Failed to construct scratch account ID.")
232            });
233
234        Promise::new(account_id)
235            .create_account()
236            .transfer(env::attached_deposit())
237    }
238
239    #[payable]
240    pub fn add_version(
241        &mut self,
242        #[serializer(borsh)] version_key: String,
243        #[serializer(borsh)] source: VersionSource,
244    ) -> PromiseOrValue<()> {
245        self.assert_owner();
246        require!(
247            !self.versions.contains_key(&version_key),
248            "Version key already exists",
249        );
250
251        match source {
252            VersionSource::Stored(code) => {
253                assert_one_yocto();
254                let version_entry = VersionEntry::Code {
255                    hash: env::sha256_array(&code.0),
256                    code: Some(code.0),
257                };
258                RegistryEvent::VersionAdded {
259                    version_key: version_key.clone(),
260                    info: version_entry.info(),
261                }
262                .emit();
263                self.versions.insert(version_key, version_entry);
264                PromiseOrValue::Value(())
265            }
266            VersionSource::PublishGlobal(code) => {
267                require!(
268                    !env::attached_deposit().is_zero(),
269                    "Deposit required to pay for global contract deployment",
270                );
271                let version_entry = VersionEntry::GlobalHash(env::sha256_array(&code.0));
272                self.versions.insert(version_key.clone(), version_entry);
273                PromiseOrValue::Promise(
274                    Self::scratch_account("deploy")
275                        .deploy_global_contract(code.0)
276                        .delete_account(env::current_account_id())
277                        .then(self_ext!(Gas::from_tgas(6)).add_version_01_finalize(version_key)),
278                )
279            }
280            // The hash is verified, not trusted: a hash with no global contract behind it fails
281            // this receipt and `add_version_01_finalize` frees the key again. Without the probe an
282            // unverified typo would burn the key permanently, since `remove_version` panics on a
283            // `GlobalHash` entry.
284            VersionSource::ExistingGlobal(hash) => {
285                // One yocto, as for `Stored`: the probe account is created and deleted inside a
286                // single receipt, so it never has to satisfy a storage-staking minimum, and
287                // `use_global_contract` copies no code to stake for. The cost here is gas.
288                assert_one_yocto();
289                self.versions
290                    .insert(version_key.clone(), VersionEntry::GlobalHash(hash.into()));
291                PromiseOrValue::Promise(
292                    Self::scratch_account("probe")
293                        .use_global_contract(hash)
294                        .delete_account(env::current_account_id())
295                        .then(self_ext!(Gas::from_tgas(6)).add_version_01_finalize(version_key)),
296                )
297            }
298        }
299    }
300
301    #[private]
302    pub fn add_version_01_finalize(&mut self, version_key: String) -> PromiseOrValue<()> {
303        let result = env::promise_result_checked(0, 0x1000);
304        if result.is_ok() {
305            if let Some(info) = self.versions.get(&version_key).map(VersionEntry::info) {
306                RegistryEvent::VersionAdded { version_key, info }.emit();
307            }
308            PromiseOrValue::Value(())
309        } else {
310            self.versions.remove(&version_key);
311            PromiseOrValue::Promise(
312                self_ext!(Gas::from_tgas(1)).fail("Failed to deploy global contract".to_string()),
313            )
314        }
315    }
316
317    #[payable]
318    pub fn remove_version(&mut self, version_key: String) {
319        assert_one_yocto();
320        self.assert_owner();
321
322        match self.versions.get_mut(&version_key) {
323            None | Some(VersionEntry::Code { code: None, .. }) => {}
324            Some(VersionEntry::Code { hash, code }) => {
325                *code = None;
326                RegistryEvent::VersionRemoved {
327                    version_key,
328                    code_hash: (*hash).into(),
329                }
330                .emit();
331            }
332            Some(VersionEntry::GlobalHash(_)) => {
333                templar_common::panic_with_message("Global contract cannot be removed")
334            }
335        }
336    }
337
338    #[payable]
339    pub fn deploy(
340        &mut self,
341        name: String,
342        version_key: String,
343        init_args: Base64VecU8,
344        full_access_keys: Option<Vec<near_sdk::PublicKey>>,
345    ) -> Promise {
346        require!(!name.is_empty(), "Name must not be empty");
347        self.assert_owner();
348
349        // Through `Deref` every field access borrows the whole contract, so the read of `versions`
350        // held across the write to `registry` needs them named as the disjoint fields they are.
351        let state = &mut *self.state;
352
353        let Some(version) = state.versions.get(&version_key) else {
354            templar_common::panic_with_message("Version key does not exist");
355        };
356
357        let attached_deposit = env::attached_deposit();
358
359        let current_account_id = env::current_account_id();
360        let account_id: AccountId = format!("{name}.{current_account_id}")
361            .parse()
362            .unwrap_or_else(|_| {
363                templar_common::panic_with_message("Deployment name is not a valid account ID")
364            });
365
366        require!(
367            account_id.is_sub_account_of(&current_account_id),
368            "Deployment account cannot be created",
369        );
370
371        require!(
372            !state.registry.contains_key(&account_id),
373            // templar-backend's relayer matches this text verbatim until ENG-781.
374            "Market ID collision",
375        );
376
377        state
378            .registry
379            .insert(account_id.clone(), RegistryEntry::Reserved);
380
381        near_sdk::log!("Deploying {version_key} to {account_id}");
382
383        let mut promise = Promise::new(account_id.clone())
384            .create_account()
385            .transfer(env::attached_deposit());
386
387        match version {
388            VersionEntry::Code { code, .. } => {
389                let code = code.as_ref().unwrap_or_else(|| {
390                    templar_common::panic_with_message("Version code has been deleted")
391                });
392
393                let minimum_deposit = env::storage_byte_cost().saturating_mul(code.len() as u128);
394
395                require!(
396                    attached_deposit >= minimum_deposit,
397                    format!("Insufficient deposit to pay for storage (minimum: {minimum_deposit})"),
398                );
399
400                promise = promise.deploy_contract(code.clone());
401            }
402            VersionEntry::GlobalHash(hash) => promise = promise.use_global_contract(*hash),
403        }
404
405        for key in full_access_keys.unwrap_or_default() {
406            near_sdk::log!(
407                "WARNING: Deploying with full-access key {}",
408                String::from(&key),
409            );
410            promise = promise.add_full_access_key(key);
411        }
412
413        promise
414            .function_call_weight(
415                "new".to_string(),
416                init_args.0,
417                NearToken::from_near(0),
418                Gas::from_tgas(2),
419                near_sdk::GasWeight(20),
420            )
421            .then(
422                Self::ext(env::current_account_id())
423                    .with_unused_gas_weight(1)
424                    .with_static_gas(Gas::from_tgas(2))
425                    .deploy_01_finalize(
426                        Some(account_id),
427                        None,
428                        Deployment {
429                            version_key,
430                            code_hash: version.code_hash().into(),
431                            block_height: env::block_height().into(),
432                        },
433                    ),
434            )
435    }
436
437    #[private]
438    pub fn deploy_01_finalize(
439        &mut self,
440        account_id: Option<AccountId>,
441        // 2.0.0's name for `account_id`, so its callbacks still in flight across the upgrade land.
442        market_id: Option<AccountId>,
443        deployment: Deployment,
444    ) -> PromiseOrValue<AccountId> {
445        let Some(account_id) = account_id.or(market_id) else {
446            templar_common::panic_with_message("Missing deployment account ID");
447        };
448        let successful = env::promise_result_checked(0, 0x1000).is_ok();
449
450        if successful {
451            RegistryEvent::Deployed {
452                account_id: account_id.clone(),
453                deployment: deployment.clone(),
454            }
455            .emit();
456            self.registry
457                .insert(account_id.clone(), RegistryEntry::Deployed(deployment));
458
459            PromiseOrValue::Value(account_id)
460        } else {
461            self.registry.remove(&account_id);
462
463            PromiseOrValue::Promise(
464                Self::ext(env::current_account_id()).fail("Deployment failed".to_string()),
465            )
466        }
467    }
468
469    #[private]
470    pub fn fail(&self, message: String) {
471        templar_common::panic_with_message(&message);
472    }
473}
474
475#[cfg(test)]
476mod tests {
477    use near_sdk::{
478        mock::MockAction,
479        serde_json,
480        test_utils::{get_created_receipts, get_logs, VMContextBuilder},
481        testing_env, PromiseResult,
482    };
483    use rstest::rstest;
484
485    use super::*;
486
487    const STORED: &str = "market@1.5.0";
488    const REMOVED: &str = "market@1.0.0";
489    const GLOBAL: &str = "oracle@0.4.1";
490
491    fn contract() -> Contract {
492        testing_env!(VMContextBuilder::new().build());
493        let mut contract = Contract::new();
494        contract.versions.insert(
495            STORED.to_string(),
496            VersionEntry::Code {
497                hash: [1u8; 32],
498                code: Some(vec![0xau8; 300]),
499            },
500        );
501        contract.versions.insert(
502            REMOVED.to_string(),
503            VersionEntry::Code {
504                hash: [2u8; 32],
505                code: None,
506            },
507        );
508        contract
509            .versions
510            .insert(GLOBAL.to_string(), VersionEntry::GlobalHash([3u8; 32]));
511        contract
512    }
513
514    #[rstest]
515    #[case(STORED, Some(VersionAvailability::Stored { code_len: 300 }))]
516    #[case(REMOVED, Some(VersionAvailability::Removed))]
517    #[case(GLOBAL, Some(VersionAvailability::Global))]
518    #[case("nothing@0.0.0", None)]
519    fn get_version_separates_all_four_states(
520        #[case] key: &str,
521        #[case] expected: Option<VersionAvailability>,
522    ) {
523        let info = contract().get_version(key.to_string());
524        assert_eq!(info.map(|info| info.availability), expected);
525    }
526
527    /// `get_deployment` maps a reserved name to `None`, which reads as "free" — but `deploy`
528    /// refuses it just as firmly as a deployed one.
529    #[test]
530    fn get_registry_entry_reports_reserved_that_get_deployment_hides() {
531        let mut contract = contract();
532        let reserved: AccountId = "reserved.registry.near".parse().unwrap();
533        let deployed: AccountId = "deployed.registry.near".parse().unwrap();
534        let deployment = Deployment {
535            version_key: STORED.to_string(),
536            code_hash: [1u8; 32].into(),
537            block_height: 1.into(),
538        };
539        contract
540            .registry
541            .insert(reserved.clone(), RegistryEntry::Reserved);
542        contract.registry.insert(
543            deployed.clone(),
544            RegistryEntry::Deployed(deployment.clone()),
545        );
546
547        assert_eq!(contract.get_deployment(reserved.clone()), None);
548        assert_eq!(
549            contract.get_registry_entry(reserved),
550            Some(RegistryEntryView::Reserved),
551        );
552        assert_eq!(
553            contract.get_registry_entry(deployed),
554            Some(RegistryEntryView::Deployed(deployment)),
555        );
556        assert_eq!(
557            contract.get_registry_entry("free.registry.near".parse().unwrap()),
558            None,
559        );
560    }
561
562    /// A fresh receipt as the owner with one yocto attached, which also clears earlier logs.
563    fn next_receipt(promise_results: Vec<PromiseResult>) {
564        testing_env!(
565            VMContextBuilder::new()
566                .attached_deposit(NearToken::from_yoctonear(1))
567                .build(),
568            near_sdk::test_vm_config(),
569            near_sdk::RuntimeFeesConfig::test(),
570            std::collections::HashMap::default(),
571            promise_results,
572        );
573    }
574
575    fn emitted_events() -> Vec<serde_json::Value> {
576        get_logs()
577            .iter()
578            .filter_map(|log| log.strip_prefix("EVENT_JSON:"))
579            .map(|event| serde_json::from_str(event).unwrap())
580            .collect()
581    }
582
583    fn deployment() -> Deployment {
584        Deployment {
585            version_key: STORED.to_string(),
586            code_hash: [1u8; 32].into(),
587            block_height: 1.into(),
588        }
589    }
590
591    #[test]
592    fn adding_stored_code_emits_version_added() {
593        let mut contract = contract();
594        next_receipt(Vec::new());
595        let code = vec![0xbbu8; 10];
596
597        let _ = contract.add_version(
598            "new@1.0.0".to_string(),
599            VersionSource::Stored(Base64VecU8(code.clone())),
600        );
601
602        let expected = RegistryEvent::VersionAdded {
603            version_key: "new@1.0.0".to_string(),
604            info: VersionInfo {
605                code_hash: env::sha256_array(&code).into(),
606                availability: VersionAvailability::Stored { code_len: 10 },
607            },
608        };
609        assert_eq!(emitted_events(), vec![expected.to_json()]);
610    }
611
612    /// A global version is announced only once the publish or probe receipt succeeded; a failed one
613    /// is rolled back without ever having been visible.
614    #[rstest]
615    #[case::confirmed(PromiseResult::Successful(Vec::new()), true)]
616    #[case::rolled_back(PromiseResult::Failed, false)]
617    fn add_version_finalize_emits_only_on_success(
618        #[case] result: PromiseResult,
619        #[case] added: bool,
620    ) {
621        let mut contract = contract();
622        next_receipt(vec![result]);
623
624        let _ = contract.add_version_01_finalize(GLOBAL.to_string());
625
626        let expected = RegistryEvent::VersionAdded {
627            version_key: GLOBAL.to_string(),
628            info: VersionInfo {
629                code_hash: [3u8; 32].into(),
630                availability: VersionAvailability::Global,
631            },
632        };
633        assert_eq!(
634            emitted_events(),
635            if added {
636                vec![expected.to_json()]
637            } else {
638                Vec::new()
639            },
640        );
641        assert_eq!(contract.get_version(GLOBAL.to_string()).is_some(), added);
642    }
643
644    /// Only a removal that clears code is announced: repeating one, or naming an unknown key,
645    /// changes nothing.
646    #[rstest]
647    #[case::stored(STORED, true)]
648    #[case::already_removed(REMOVED, false)]
649    #[case::unknown("nothing@0.0.0", false)]
650    fn remove_version_emits_only_when_it_clears_code(#[case] key: &str, #[case] removed: bool) {
651        let mut contract = contract();
652        next_receipt(Vec::new());
653
654        contract.remove_version(key.to_string());
655
656        let expected = RegistryEvent::VersionRemoved {
657            version_key: key.to_string(),
658            code_hash: [1u8; 32].into(),
659        };
660        assert_eq!(
661            emitted_events(),
662            if removed {
663                vec![expected.to_json()]
664            } else {
665                Vec::new()
666            },
667        );
668    }
669
670    #[rstest]
671    #[case::initialized(PromiseResult::Successful(Vec::new()), true)]
672    #[case::released(PromiseResult::Failed, false)]
673    fn deploy_finalize_emits_only_on_success(
674        #[case] result: PromiseResult,
675        #[case] deployed: bool,
676    ) {
677        let mut contract = contract();
678        let account_id: AccountId = "one.registry.near".parse().unwrap();
679        contract
680            .registry
681            .insert(account_id.clone(), RegistryEntry::Reserved);
682        next_receipt(vec![result]);
683
684        let _ = contract.deploy_01_finalize(Some(account_id.clone()), None, deployment());
685
686        let expected = RegistryEvent::Deployed {
687            account_id: account_id.clone(),
688            deployment: deployment(),
689        };
690        assert_eq!(
691            emitted_events(),
692            if deployed {
693                vec![expected.to_json()]
694            } else {
695                Vec::new()
696            },
697        );
698        assert_eq!(
699            contract.get_registry_entry(account_id),
700            deployed.then(|| RegistryEntryView::Deployed(deployment())),
701        );
702    }
703
704    #[test]
705    #[should_panic(expected = "Missing deployment account ID")]
706    fn finalize_needs_the_account_under_either_name() {
707        let _ = contract().deploy_01_finalize(
708            None,
709            None,
710            Deployment {
711                version_key: STORED.to_string(),
712                code_hash: [1u8; 32].into(),
713                block_height: 1.into(),
714            },
715        );
716    }
717
718    #[rstest]
719    #[case::whole(0, 300, 300)]
720    #[case::prefix(0, 10, 10)]
721    #[case::tail(290, 64, 10)]
722    #[case::past_the_end_reads_empty(300, 64, 0)]
723    #[case::far_past_the_end_reads_empty(9_999, 64, 0)]
724    fn code_chunk_clamps_to_the_blob(
725        #[case] offset: u32,
726        #[case] len: u32,
727        #[case] expected: usize,
728    ) {
729        let chunk = contract()
730            .get_version_code_chunk(STORED.to_string(), offset, len)
731            .expect("a stored version yields bytes");
732        assert_eq!(chunk.len(), expected);
733        assert!(chunk.iter().all(|byte| *byte == 0xau8));
734    }
735
736    /// Reassembly is the point: chunks concatenated in order must equal the stored blob.
737    #[test]
738    fn code_chunks_reassemble_exactly() {
739        let contract = contract();
740        let mut reassembled = Vec::new();
741        let mut offset = 0;
742        loop {
743            let chunk = contract
744                .get_version_code_chunk(STORED.to_string(), offset, 128)
745                .expect("a stored version yields bytes");
746            if chunk.is_empty() {
747                break;
748            }
749            offset += u32::try_from(chunk.len()).unwrap();
750            reassembled.extend(chunk);
751        }
752        assert_eq!(reassembled, vec![0xau8; 300]);
753    }
754
755    /// Neither a global version nor one whose code was removed has bytes to read, so the caller
756    /// has to resolve those by hash instead.
757    #[rstest]
758    #[case(GLOBAL)]
759    #[case(REMOVED)]
760    #[case("nothing@0.0.0")]
761    fn code_chunk_is_absent_without_stored_code(#[case] key: &str) {
762        assert_eq!(
763            contract().get_version_code_chunk(key.to_string(), 0, 64),
764            None,
765        );
766    }
767
768    #[test]
769    #[should_panic(expected = "len exceeds maximum")]
770    fn code_chunk_refuses_an_oversized_read() {
771        contract().get_version_code_chunk(STORED.to_string(), 0, Contract::MAX_CODE_CHUNK_LEN + 1);
772    }
773
774    /// Deploy and `migrate` must share one receipt, which is what makes a failed migration revert
775    /// the code with it. Two receipts would leave the new code deployed over unmigrated state.
776    #[test]
777    fn upgrade_batches_deploy_then_migrate_into_one_self_receipt() {
778        testing_env!(VMContextBuilder::new()
779            .current_account_id("registry.near".parse().unwrap())
780            .predecessor_account_id("registry.near".parse().unwrap())
781            .attached_deposit(NearToken::from_yoctonear(1))
782            .build());
783        let mut contract = Contract::new();
784        let code = vec![0xde, 0xad, 0xbe, 0xef];
785        let migrate_args = br#"[{"from_version":"v1"}]"#.to_vec();
786
787        contract
788            .upgrade(
789                UpgradeSource::Code(Base64VecU8(code.clone())),
790                Base64VecU8(migrate_args.clone()),
791            )
792            .detach();
793
794        let receipts = get_created_receipts();
795        assert_eq!(receipts.len(), 1, "the upgrade must not fan out");
796        let receipt = &receipts[0];
797        assert_eq!(receipt.receiver_id.as_str(), "registry.near");
798        assert_eq!(receipt.actions.len(), 2);
799
800        let receipt_index = match &receipt.actions[0] {
801            MockAction::DeployContract {
802                receipt_index,
803                code: deployed,
804            } => {
805                assert_eq!(deployed, &code);
806                *receipt_index
807            }
808            action => panic!("expected the deploy first, got {action:?}"),
809        };
810        match &receipt.actions[1] {
811            MockAction::FunctionCallWeight {
812                receipt_index: migrate_index,
813                method_name,
814                args,
815                prepaid_gas,
816                ..
817            } => {
818                assert_eq!(
819                    *migrate_index, receipt_index,
820                    "migrate must ride the deploy"
821                );
822                assert_eq!(method_name, b"migrate");
823                assert_eq!(args, &migrate_args);
824                assert_eq!(*prepaid_gas, Contract::GAS_FOR_MIGRATE);
825            }
826            action => panic!("expected the migrate second, got {action:?}"),
827        }
828    }
829
830    #[test]
831    #[should_panic(expected = "Requires attached deposit of exactly 1 yoctoNEAR")]
832    fn upgrade_requires_one_yocto() {
833        testing_env!(VMContextBuilder::new()
834            .current_account_id("registry.near".parse().unwrap())
835            .predecessor_account_id("registry.near".parse().unwrap())
836            .build());
837        let mut contract = Contract::new();
838        contract
839            .upgrade(
840                UpgradeSource::Code(Base64VecU8(vec![1, 2, 3])),
841                Base64VecU8(Vec::new()),
842            )
843            .detach();
844    }
845
846    #[test]
847    #[should_panic(expected = "Upgrade code must not be empty")]
848    fn upgrade_refuses_an_empty_blob() {
849        testing_env!(VMContextBuilder::new()
850            .current_account_id("registry.near".parse().unwrap())
851            .predecessor_account_id("registry.near".parse().unwrap())
852            .attached_deposit(NearToken::from_yoctonear(1))
853            .build());
854        let mut contract = Contract::new();
855        contract
856            .upgrade(
857                UpgradeSource::Code(Base64VecU8(Vec::new())),
858                Base64VecU8(Vec::new()),
859            )
860            .detach();
861    }
862}
863
864#[cfg(target_arch = "wasm32")]
865mod custom_getrandom {
866    #![allow(clippy::no_mangle_with_rust_abi)]
867
868    use getrandom::{register_custom_getrandom, Error};
869    use near_sdk::env;
870
871    register_custom_getrandom!(custom_getrandom);
872
873    #[allow(clippy::unnecessary_wraps)]
874    pub fn custom_getrandom(buf: &mut [u8]) -> Result<(), Error> {
875        buf.copy_from_slice(&env::random_seed_array());
876        Ok(())
877    }
878}