├── commands.txt ├── .vscode └── settings.json ├── assets ├── claimed-ft.png ├── claimed-nft.png ├── claimed-fc-nft.png ├── claimed-linkdrop.png └── CODE_OF_CONDUCT.md ├── flowcharts ├── creating-multiple-linkdrops.png ├── creating-single-linkdrops.png ├── adding-nfts-and-fts-to-linkdrops.png ├── claiming-ft-linkdrops-with-new-accounts.png ├── claiming-nft-linkdrops-with-new-accounts.png └── claiming-function-call-linkdrops-with-new-accounts.png ├── contract ├── Cargo.toml ├── src │ ├── function_call.rs │ ├── helpers.rs │ ├── ext_traits.rs │ ├── nft.rs │ ├── views.rs │ ├── lib.rs │ ├── ft.rs │ ├── send.rs │ └── claim.rs └── Cargo.lock ├── .eslintrc.js ├── Cargo.toml ├── utils └── patch-config.js ├── .gitignore ├── package.json ├── test ├── config.js ├── near-utils.js ├── api.test.js └── test-utils.js ├── deploy ├── simple.js ├── recursive-fc.js ├── ft.js ├── function-call.js └── nft.js ├── README.md └── LICENSE /commands.txt: -------------------------------------------------------------------------------- 1 | near call $DEV new '{"linkdrop_contract": "testnet"}' --accountId $DEV -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "unscalable" 4 | ] 5 | } -------------------------------------------------------------------------------- /assets/claimed-ft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/assets/claimed-ft.png -------------------------------------------------------------------------------- /assets/claimed-nft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/assets/claimed-nft.png -------------------------------------------------------------------------------- /assets/claimed-fc-nft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/assets/claimed-fc-nft.png -------------------------------------------------------------------------------- /assets/claimed-linkdrop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/assets/claimed-linkdrop.png -------------------------------------------------------------------------------- /flowcharts/creating-multiple-linkdrops.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/flowcharts/creating-multiple-linkdrops.png -------------------------------------------------------------------------------- /flowcharts/creating-single-linkdrops.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/flowcharts/creating-single-linkdrops.png -------------------------------------------------------------------------------- /flowcharts/adding-nfts-and-fts-to-linkdrops.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/flowcharts/adding-nfts-and-fts-to-linkdrops.png -------------------------------------------------------------------------------- /flowcharts/claiming-ft-linkdrops-with-new-accounts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/flowcharts/claiming-ft-linkdrops-with-new-accounts.png -------------------------------------------------------------------------------- /flowcharts/claiming-nft-linkdrops-with-new-accounts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/flowcharts/claiming-nft-linkdrops-with-new-accounts.png -------------------------------------------------------------------------------- /flowcharts/claiming-function-call-linkdrops-with-new-accounts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/near-examples/linkdrop-proxy/HEAD/flowcharts/claiming-function-call-linkdrops-with-new-accounts.png -------------------------------------------------------------------------------- /contract/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "linkdrop-proxy" 3 | version = "1.0.0" 4 | authors = ["Ben Kurrek , Matt Lockyer "] 5 | edition = "2018" 6 | 7 | [lib] 8 | crate-type = ["cdylib"] 9 | 10 | [dependencies] 11 | near-sdk = "4.0.0" -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parserOptions: { 3 | ecmaVersion: 2020, 4 | sourceType: 'module', 5 | ecmaFeatures: { 6 | jsx: true, 7 | } 8 | }, 9 | rules: { 10 | semi: [2, 'always'], 11 | indent: [2, 'tab'], 12 | } 13 | }; 14 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | # [package] 2 | # name = "cross-contract-calls" 3 | # version = "0.0.0" 4 | # authors = ["Near Inc "] 5 | # edition = "2018" 6 | 7 | [workspace] 8 | members = [ 9 | "contract" 10 | ] 11 | 12 | [profile.release] 13 | codegen-units = 1 14 | opt-level = "z" 15 | lto = true 16 | debug = false 17 | panic = "abort" 18 | overflow-checks = true 19 | 20 | -------------------------------------------------------------------------------- /utils/patch-config.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const contractName = fs.readFileSync('./neardev/dev-account').toString() 3 | const path = './test/config.js' 4 | 5 | fs.readFile(path, 'utf-8', function(err, data) { 6 | if (err) throw err; 7 | 8 | data = data.replace(/.*const contractName.*/gim, `const contractName = '${contractName}';`); 9 | 10 | fs.writeFile(path, data, 'utf-8', function(err) { 11 | if (err) throw err; 12 | console.log('Done!'); 13 | }) 14 | }) 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | # Developer note: near.gitignore will be renamed to .gitignore upon project creation 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | /out 8 | /neardev 9 | 10 | #cache 11 | .cache 12 | .parcel-cache 13 | 14 | #contracts 15 | target 16 | out 17 | notes 18 | 19 | # testing 20 | /coverage 21 | 22 | # production 23 | /dist 24 | 25 | # misc 26 | .DS_Store 27 | .env.local 28 | .env.development.local 29 | .env.test.local 30 | .env.production.local 31 | 32 | npm-debug.log* 33 | yarn-debug.log* 34 | yarn-error.log* 35 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "near-proxy-linkdrop-contract", 3 | "version": "1.0.0", 4 | "license": "MIT", 5 | "author": "Ben Kurrek, Matt Lockyer", 6 | "scripts": { 7 | "fix": "eslint test/ --fix", 8 | "build-contract": "./build.sh", 9 | "patch-config": "node ./utils/patch-config.js", 10 | "dev-deploy": "yarn build-contract && rm -rf neardev && (near dev-deploy || exit 0) && yarn patch-config", 11 | "test-deploy": "yarn dev-deploy && mocha", 12 | "test": "mocha" 13 | }, 14 | "dependencies": { 15 | "mocha": "^9.0.1" 16 | }, 17 | "devDependencies": { 18 | "acquit": "^1.2.1", 19 | "acquit-markdown": "^0.1.0", 20 | "eslint": "^7.29.0", 21 | "near-api-js": "^0.44.2", 22 | "node-fetch": "^2.6.1" 23 | } 24 | } -------------------------------------------------------------------------------- /contract/src/function_call.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | 3 | /// Keep track of nft data 4 | #[near_bindgen] 5 | #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize, Serialize, Deserialize, Clone)] 6 | #[serde(crate = "near_sdk::serde")] 7 | pub struct FCData { 8 | // Contract that will be called 9 | pub receiver: AccountId, 10 | // Method to call on receiver contract 11 | pub method: String, 12 | // Arguments to pass in (stringified JSON) 13 | pub args: String, 14 | // Amount of yoctoNEAR to attach along with the call 15 | pub deposit: U128, 16 | // Should the refund that normally goes to the funder be attached alongside the deposit? 17 | pub refund_to_deposit: Option, 18 | // Specifies what field the claiming account should go in when calling the function 19 | pub claimed_account_field: Option, 20 | } -------------------------------------------------------------------------------- /test/config.js: -------------------------------------------------------------------------------- 1 | const contractName = 'dev-1652328951380-27200146164238'; 2 | 3 | module.exports = function getConfig(network = 'mainnet') { 4 | let config = { 5 | networkId: "testnet", 6 | nodeUrl: "https://rpc.testnet.near.org", 7 | walletUrl: "https://wallet.testnet.near.org", 8 | helperUrl: "https://helper.testnet.near.org", 9 | contractName, 10 | }; 11 | 12 | switch (network) { 13 | case 'testnet': 14 | config = { 15 | explorerUrl: "https://explorer.testnet.near.org", 16 | ...config, 17 | GAS: "200000000000000", 18 | gas: "200000000000000", 19 | NEW_ACCOUNT_AMOUNT: "5000000000000000000000000", 20 | DEFAULT_NEW_CONTRACT_AMOUNT: "5", 21 | GUESTS_ACCOUNT_SECRET: 22 | "7UVfzoKZL4WZGF98C3Ue7tmmA6QamHCiB1Wd5pkxVPAc7j6jf3HXz5Y9cR93Y68BfGDtMLQ9Q29Njw5ZtzGhPxv", 23 | 24 | contractMethods: { 25 | changeMethods: [ 26 | "new", 27 | ], 28 | viewMethods: [], 29 | }, 30 | 31 | contractId: contractName, 32 | marketId: "market." + contractName, 33 | fungibleId: "ft.hhft.testnet", 34 | }; 35 | break; 36 | case 'mainnet': 37 | config = { 38 | ...config, 39 | networkId: "mainnet", 40 | nodeUrl: "https://rpc.mainnet.near.org", 41 | walletUrl: "https://wallet.near.org", 42 | helperUrl: "https://helper.mainnet.near.org", 43 | contractName: "uhhmnft.near", 44 | contractId: "uhhmnft.near", 45 | marketId: "market.uhhmnft.near", 46 | fungibleId: "ft.hip-hop.near", 47 | ownerId: 'owner.uhhmnft.near', 48 | }; 49 | break; 50 | } 51 | 52 | return config; 53 | }; 54 | -------------------------------------------------------------------------------- /test/near-utils.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | const nearAPI = require("near-api-js"); 3 | const getConfig = require("./config"); 4 | const { nodeUrl, networkId, contractName, contractMethods } = getConfig('testnet'); 5 | 6 | const { 7 | keyStores: { InMemoryKeyStore }, 8 | Near, 9 | Account, 10 | Contract, 11 | KeyPair, 12 | utils: { 13 | format: { parseNearAmount }, 14 | }, 15 | } = nearAPI; 16 | 17 | const credPath = `./neardev/${networkId}/${contractName}.json`; 18 | console.log( 19 | "Loading Credentials:\n", 20 | credPath 21 | ); 22 | 23 | let credentials; 24 | try { 25 | credentials = JSON.parse( 26 | fs.readFileSync( 27 | credPath 28 | ) 29 | ); 30 | } catch(e) { 31 | console.warn('credentials not in /neardev'); 32 | /// attempt to load backup creds from local machine 33 | credentials = JSON.parse( 34 | fs.readFileSync( 35 | `${process.env.HOME}/.near-credentials/${networkId}/${contractName}.json` 36 | ) 37 | ); 38 | } 39 | const keyStore = new InMemoryKeyStore(); 40 | keyStore.setKey( 41 | networkId, 42 | contractName, 43 | KeyPair.fromString(credentials.private_key) 44 | ); 45 | const near = new Near({ 46 | networkId, 47 | nodeUrl, 48 | deps: { keyStore }, 49 | }); 50 | const { connection } = near; 51 | const contractAccount = new Account(connection, contractName); 52 | contractAccount.addAccessKey = (publicKey) => 53 | contractAccount.addKey( 54 | publicKey, 55 | contractName, 56 | contractMethods, 57 | parseNearAmount("0.1") 58 | ); 59 | const contract = new Contract(contractAccount, contractName, contractMethods); 60 | 61 | module.exports = { 62 | near, 63 | credentials, 64 | keyStore, 65 | connection, 66 | contract, 67 | contractName, 68 | contractAccount, 69 | contractMethods, 70 | }; 71 | -------------------------------------------------------------------------------- /contract/src/helpers.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | 3 | //used to generate a unique prefix in our storage collections (this is to avoid data collisions) 4 | pub(crate) fn hash_account_id(account_id: &AccountId) -> CryptoHash { 5 | env::sha256_array(account_id.as_bytes()) 6 | } 7 | 8 | impl LinkDropProxy { 9 | /// Asserts that the cross contract call was successful. Returns the success value 10 | pub(crate) fn assert_success(&mut self) -> bool { 11 | assert_eq!( 12 | env::predecessor_account_id(), 13 | env::current_account_id(), 14 | "predecessor != current" 15 | ); 16 | 17 | assert_eq!(env::promise_results_count(), 1, "no promise result"); 18 | matches!(env::promise_result(0), PromiseResult::Successful(_)) 19 | } 20 | 21 | //add a public key to the set of keys a funder has 22 | pub(crate) fn internal_add_key_to_funder( 23 | &mut self, 24 | account_id: &AccountId, 25 | pk: &PublicKey, 26 | ) { 27 | //get the set of keys for the given account 28 | let mut key_set = self.keys_for_funder.get(account_id).unwrap_or_else(|| { 29 | //if the account doesn't have any keys, we create a new unordered set 30 | UnorderedSet::new( 31 | StorageKey::KeysPerFunderInner { 32 | //we get a new unique prefix for the collection 33 | account_id_hash: hash_account_id(&account_id), 34 | } 35 | ) 36 | }); 37 | 38 | //we insert the public key into the set 39 | key_set.insert(pk); 40 | 41 | //we insert that set for the given account ID. 42 | self.keys_for_funder.insert(account_id, &key_set); 43 | } 44 | 45 | //remove a public key for a funder (internal method and can't be called directly via CLI). 46 | pub(crate) fn internal_remove_key_to_funder( 47 | &mut self, 48 | account_id: &AccountId, 49 | pk: &PublicKey, 50 | ) { 51 | //we get the set of keys that the funder has 52 | let mut key_set = self 53 | .keys_for_funder 54 | .get(account_id) 55 | //if there is no set of keys for the owner, we panic with the following message: 56 | .expect("No Keys found for the funder"); 57 | 58 | //we remove the the public key from the set of tokens 59 | key_set.remove(pk); 60 | 61 | //if the set is now empty, we remove the funder from the keys_for_funder collection 62 | if key_set.is_empty() { 63 | self.keys_for_funder.remove(account_id); 64 | } else { 65 | //if the key set is not empty, we simply insert it back for the funder ID. 66 | self.keys_for_funder.insert(account_id, &key_set); 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /assets/CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to make participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies within all project spaces, and it also applies when an individual is representing the project or its community in public spaces. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project maintainer using any of the private contact addresses. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.4, available at 44 | 45 | For answers to common questions about this code of conduct, see 46 | -------------------------------------------------------------------------------- /deploy/simple.js: -------------------------------------------------------------------------------- 1 | const { connect, KeyPair, keyStores, utils } = require("near-api-js"); 2 | const { parseNearAmount, formatNearAmount } = require("near-api-js/lib/utils/format"); 3 | const path = require("path"); 4 | const homedir = require("os").homedir(); 5 | 6 | let LINKDROP_PROXY_CONTRACT_ID = process.env.LINKDROP_PROXY_CONTRACT_ID; 7 | let FUNDING_ACCOUNT_ID = process.env.FUNDING_ACCOUNT_ID; 8 | let LINKDROP_NEAR_AMOUNT = process.env.LINKDROP_NEAR_AMOUNT; 9 | let SEND_MULTIPLE = process.env.SEND_MULTIPLE; 10 | 11 | let OFFSET = 0.1; 12 | 13 | let NETWORK_ID = "testnet"; 14 | let near; 15 | let config; 16 | let keyStore; 17 | 18 | // set up near 19 | const initiateNear = async () => { 20 | const CREDENTIALS_DIR = ".near-credentials"; 21 | 22 | const credentialsPath = (await path).join(homedir, CREDENTIALS_DIR); 23 | (await path).join; 24 | keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath); 25 | 26 | config = { 27 | networkId: NETWORK_ID, 28 | keyStore, 29 | nodeUrl: "https://rpc.testnet.near.org", 30 | walletUrl: "https://wallet.testnet.near.org", 31 | helperUrl: "https://helper.testnet.near.org", 32 | explorerUrl: "https://explorer.testnet.near.org", 33 | }; 34 | 35 | near = await connect(config); 36 | }; 37 | 38 | async function start() { 39 | //deployed linkdrop proxy contract 40 | await initiateNear(); 41 | 42 | if(!LINKDROP_PROXY_CONTRACT_ID || !FUNDING_ACCOUNT_ID || !LINKDROP_NEAR_AMOUNT || !SEND_MULTIPLE) { 43 | throw "must specify proxy contract ID, funding account ID, linkdrop $NEAR amount and whether to send multiple"; 44 | } 45 | 46 | const contractAccount = await near.account(LINKDROP_PROXY_CONTRACT_ID); 47 | const fundingAccount = await near.account(FUNDING_ACCOUNT_ID); 48 | 49 | console.log(`initializing contract for account ${LINKDROP_PROXY_CONTRACT_ID}`); 50 | try { 51 | await contractAccount.functionCall( 52 | LINKDROP_PROXY_CONTRACT_ID, 53 | 'new', 54 | { 55 | linkdrop_contract: "testnet", 56 | }, 57 | "300000000000000", 58 | ); 59 | } catch(e) { 60 | console.log('error initializing contract: ', e); 61 | } 62 | 63 | let keyPairs = []; 64 | let pubKeys = []; 65 | 66 | if(SEND_MULTIPLE != "false") { 67 | console.log("BATCH Creating keypairs"); 68 | for(var i = 0; i < 5; i++) { 69 | console.log('i: ', i); 70 | let keyPair = await KeyPair.fromRandom('ed25519'); 71 | keyPairs.push(keyPair); 72 | pubKeys.push(keyPair.publicKey.toString()); 73 | } 74 | console.log("Finished."); 75 | } else { 76 | let keyPair = await KeyPair.fromRandom('ed25519'); 77 | keyPairs.push(keyPair); 78 | pubKeys.push(keyPair.publicKey.toString()); 79 | } 80 | 81 | try { 82 | if(SEND_MULTIPLE != "false") { 83 | await fundingAccount.functionCall( 84 | LINKDROP_PROXY_CONTRACT_ID, 85 | 'send_multiple', 86 | { 87 | public_keys: pubKeys, 88 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT) 89 | }, 90 | "300000000000000", 91 | parseNearAmount(((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET) * pubKeys.length).toString()) 92 | ); 93 | } else { 94 | console.log("Sending one linkdrop"); 95 | await fundingAccount.functionCall( 96 | LINKDROP_PROXY_CONTRACT_ID, 97 | 'send', 98 | { 99 | public_key: pubKeys[0], 100 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT) 101 | }, 102 | "300000000000000", 103 | parseNearAmount((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET).toString()) 104 | ); 105 | } 106 | 107 | } catch(e) { 108 | console.log('error initializing contract: ', e); 109 | } 110 | 111 | for(var i = 0; i < keyPairs.length; i++) { 112 | console.log(`https://wallet.testnet.near.org/linkdrop/${LINKDROP_PROXY_CONTRACT_ID}/${keyPairs[i].secretKey}`); 113 | console.log("Pub Key: ", keyPairs[i].publicKey.toString()); 114 | } 115 | } 116 | 117 | 118 | start(); -------------------------------------------------------------------------------- /contract/src/ext_traits.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | 3 | /// external and self callbacks 4 | #[ext_contract(ext_linkdrop)] 5 | trait ExtLinkdrop { 6 | fn create_account(&mut self, new_account_id: AccountId, new_public_key: PublicKey) -> Promise; 7 | } 8 | 9 | /// NFT contract 10 | #[ext_contract(ext_nft_contract)] 11 | trait ExtNFTContract { 12 | fn nft_transfer( 13 | &mut self, 14 | receiver_id: AccountId, 15 | token_id: String, 16 | approval_id: Option, 17 | memo: Option, 18 | ); 19 | } 20 | 21 | /// FT contract 22 | #[ext_contract(ext_ft_contract)] 23 | trait ExtFTContract { 24 | fn ft_transfer( 25 | &mut self, 26 | receiver_id: AccountId, 27 | amount: U128, 28 | memo: Option, 29 | ); 30 | 31 | fn storage_balance_bounds( 32 | &self, 33 | ) -> StorageBalanceBounds; 34 | } 35 | 36 | #[ext_contract(ext_self)] 37 | trait ExtThis { 38 | /// self callback for simple linkdrops with no FTs, NFTs, or FCs. 39 | fn on_claim_simple( 40 | &mut self, 41 | // Account ID that sent the funds for the linkdrop 42 | funder_id: AccountId, 43 | // Balance contained within the linkdrop 44 | balance: U128, 45 | // How much storage was used up for the linkdrop 46 | storage_used: U128, 47 | ) -> bool; 48 | 49 | /// self callback for FT linkdrop 50 | fn on_claim_ft( 51 | &mut self, 52 | // Account ID that claimed the linkdrop 53 | account_id: AccountId, 54 | // Account ID that funded the linkdrop 55 | funder_id: AccountId, 56 | // Balance associated with the linkdrop 57 | balance: U128, 58 | // How much storage was used to store linkdrop info 59 | storage_used: U128, 60 | // Did the sender end up sending the FTs to the contract 61 | did_send_fts: bool, 62 | // Who sent the FTs? 63 | ft_sender: AccountId, 64 | // Where are the FTs stored 65 | ft_contract: AccountId, 66 | // How many FTs should we send 67 | ft_balance: U128, 68 | // How much storage does it cost to register the new account 69 | ft_storage: U128, 70 | ) -> bool; 71 | 72 | /// self callback for a linkdrop loaded with an NFT 73 | fn on_claim_nft(&mut self, 74 | // Account ID that claimed the linkdrop 75 | account_id: AccountId, 76 | // Account ID that funded the linkdrop 77 | funder_id: AccountId, 78 | // Balance associated with the linkdrop 79 | balance: U128, 80 | // How much storage was used to store linkdrop info 81 | storage_used: U128, 82 | // Did the sender end up sending the NFT to the contract 83 | did_send_nft: bool, 84 | // Sender of the NFT 85 | nft_sender: AccountId, 86 | // Contract where the NFT is stored 87 | nft_contract: AccountId, 88 | // Token ID for the NFT 89 | token_id: String, 90 | ) -> bool; 91 | 92 | /// self callback checks if account was created successfully or not. If yes, refunds excess storage, sends NFTs, FTs etc.. 93 | fn on_claim_fc(&mut self, 94 | // Account ID that claimed the linkdrop 95 | account_id: AccountId, 96 | // Account ID that funded the linkdrop 97 | funder_id: AccountId, 98 | // Balance associated with the linkdrop 99 | balance: U128, 100 | // How much storage was used to store linkdrop info 101 | storage_used: U128, 102 | // Receiver of the function call 103 | receiver: AccountId, 104 | // Method to call on the contract 105 | method: String, 106 | // What args to pass in 107 | args: String, 108 | // What deposit should we attach 109 | deposit: U128, 110 | // Should the refund be sent to the funder or attached to the deposit 111 | add_refund_to_deposit: Option, 112 | // Should we add the account ID as part of the args and what key should it live in 113 | claimed_account_field: Option, 114 | ) -> bool; 115 | 116 | fn nft_resolve_transfer( 117 | &mut self, 118 | token_id: String, 119 | token_sender: AccountId, 120 | token_contract: AccountId 121 | ); 122 | 123 | fn resolve_storage_check( 124 | &mut self, 125 | public_keys: Vec, 126 | funder_id: AccountId, 127 | balance: U128, 128 | required_storage: U128, 129 | cb_ids: Vec, 130 | ); 131 | } -------------------------------------------------------------------------------- /contract/src/nft.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | 3 | /// Keep track of nft data 4 | #[near_bindgen] 5 | #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize, Serialize, Deserialize, Clone)] 6 | #[serde(crate = "near_sdk::serde")] 7 | pub struct NFTData { 8 | pub nft_sender: AccountId, 9 | pub nft_contract: AccountId, 10 | pub nft_token_id: String, 11 | } 12 | 13 | #[near_bindgen] 14 | impl LinkDropProxy { 15 | pub fn nft_on_transfer( 16 | &mut self, 17 | token_id: String, 18 | sender_id: AccountId, 19 | msg: PublicKey, 20 | ) -> PromiseOrValue { 21 | assert!(token_id.len() <= 256, "Contract cannot accept token IDs of length greater than 256 bytes"); 22 | 23 | let contract_id = env::predecessor_account_id(); 24 | 25 | // No need to assert that the funder is the sender since we don't wanna enforce anything unnecessary. 26 | // All that matters is we've received the token and that the token belongs to some public key. 27 | let AccountData { 28 | funder_id, 29 | balance, 30 | storage_used, 31 | cb_id, 32 | cb_data_sent, 33 | } = self.data_for_pk 34 | .get(&msg) 35 | .expect("Missing public key"); 36 | 37 | // Ensure there's a callback ID (meaning the linkdrop is not a regular linkdrop) 38 | let callback_id = cb_id.expect("Callback ID must be set"); 39 | 40 | // Assert that the FTs have NOT been sent yet 41 | assert!(cb_data_sent == false, "NFT already sent. Cannot send more."); 42 | 43 | // Ensure that the linkdrop contains FT data already 44 | let NFTData { 45 | nft_sender, 46 | nft_contract, 47 | nft_token_id 48 | } = self.nft.get(&callback_id).expect("No NFT data found for the unique callback ID."); 49 | 50 | assert!(nft_sender == sender_id && nft_contract == contract_id && nft_token_id == token_id, "NFT data must match what was sent"); 51 | 52 | 53 | // Insert the account data back with the cb data sent set to true 54 | self.data_for_pk.insert( 55 | &msg, 56 | &AccountData{ 57 | funder_id, 58 | balance, 59 | storage_used, 60 | cb_id, 61 | cb_data_sent: true, 62 | }, 63 | ); 64 | 65 | // Everything went well and we don't need to return the token. 66 | PromiseOrValue::Value(false) 67 | } 68 | 69 | /// self callback checks if NFT was successfully transferred to the new account. If yes, do nothing. If no, refund original sender 70 | pub fn nft_resolve_transfer( 71 | &mut self, 72 | token_id: String, 73 | token_sender: AccountId, 74 | token_contract: AccountId 75 | ) -> bool { 76 | let mut used_gas = env::used_gas(); 77 | let mut prepaid_gas = env::prepaid_gas(); 78 | 79 | env::log_str(&format!("Beginning of resolve transfer used gas: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 80 | 81 | assert_eq!( 82 | env::predecessor_account_id(), 83 | env::current_account_id(), 84 | "predecessor != current" 85 | ); 86 | assert_eq!(env::promise_results_count(), 1, "no promise result"); 87 | let transfer_succeeded = matches!(env::promise_result(0), PromiseResult::Successful(_)); 88 | 89 | 90 | used_gas = env::used_gas(); 91 | prepaid_gas = env::prepaid_gas(); 92 | env::log_str(&format!("Before refunding token sender in resolve transfer: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 93 | 94 | // If not successful, the balance is added to the amount to refund since it was never transferred. 95 | if !transfer_succeeded { 96 | env::log_str("Attempt to transfer the new account was unsuccessful. Sending the NFT to the original sender."); 97 | ext_nft_contract::ext(token_contract) 98 | // Call nft transfer with the min GAS and 1 yoctoNEAR. all unspent GAS will be added on top 99 | .with_static_gas(MIN_GAS_FOR_SIMPLE_NFT_TRANSFER) 100 | .with_attached_deposit(1) 101 | .nft_transfer( 102 | token_sender, 103 | token_id, 104 | None, 105 | Some("Linkdropped NFT Refund".to_string()), 106 | ); 107 | } 108 | 109 | transfer_succeeded 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /deploy/recursive-fc.js: -------------------------------------------------------------------------------- 1 | const { connect, KeyPair, keyStores, utils } = require("near-api-js"); 2 | const { parseNearAmount, formatNearAmount } = require("near-api-js/lib/utils/format"); 3 | const path = require("path"); 4 | const homedir = require("os").homedir(); 5 | 6 | let LINKDROP_PROXY_CONTRACT_ID = process.env.LINKDROP_PROXY_CONTRACT_ID; 7 | let FUNDING_ACCOUNT_ID = process.env.FUNDING_ACCOUNT_ID; 8 | let LINKDROP_NEAR_AMOUNT = process.env.LINKDROP_NEAR_AMOUNT; 9 | 10 | let OFFSET = 0.1; 11 | let STORAGE = 0.038; 12 | 13 | let NETWORK_ID = "testnet"; 14 | let near; 15 | let config; 16 | let keyStore; 17 | 18 | // set up near 19 | const initiateNear = async () => { 20 | const CREDENTIALS_DIR = ".near-credentials"; 21 | 22 | const credentialsPath = (await path).join(homedir, CREDENTIALS_DIR); 23 | (await path).join; 24 | keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath); 25 | 26 | config = { 27 | networkId: NETWORK_ID, 28 | keyStore, 29 | nodeUrl: "https://rpc.testnet.near.org", 30 | walletUrl: "https://wallet.testnet.near.org", 31 | helperUrl: "https://helper.testnet.near.org", 32 | explorerUrl: "https://explorer.testnet.near.org", 33 | }; 34 | 35 | near = await connect(config); 36 | }; 37 | 38 | async function start() { 39 | //deployed linkdrop proxy contract 40 | await initiateNear(); 41 | 42 | if(!LINKDROP_PROXY_CONTRACT_ID || !FUNDING_ACCOUNT_ID || !LINKDROP_NEAR_AMOUNT) { 43 | throw "must specify proxy contract ID, funding account ID and linkdrop $NEAR amount"; 44 | } 45 | 46 | const contractAccount = await near.account(LINKDROP_PROXY_CONTRACT_ID); 47 | const fundingAccount = await near.account(FUNDING_ACCOUNT_ID); 48 | 49 | console.log(`initializing contract for account ${LINKDROP_PROXY_CONTRACT_ID}`); 50 | try { 51 | await contractAccount.functionCall( 52 | LINKDROP_PROXY_CONTRACT_ID, 53 | 'new', 54 | { 55 | linkdrop_contract: "testnet", 56 | }, 57 | "300000000000000", 58 | ); 59 | } catch(e) { 60 | console.log('error initializing contract: ', e); 61 | } 62 | 63 | let keyPairs = []; 64 | let pubKeys = []; 65 | console.log("Creating keypairs"); 66 | for(var i = 0; i < 5; i++) { 67 | let keyPair = await KeyPair.fromRandom('ed25519'); 68 | keyPairs.push(keyPair); 69 | pubKeys.push(keyPair.publicKey.toString()); 70 | } 71 | console.log("Finished."); 72 | 73 | console.log(`sending ${LINKDROP_NEAR_AMOUNT} $NEAR as ${FUNDING_ACCOUNT_ID}`); 74 | try { 75 | let fc_data_base = {}; 76 | let argsBase = JSON.stringify({ 77 | public_key: keyPairs[0].publicKey.toString(), 78 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT), 79 | }); 80 | fc_data_base["receiver"] = LINKDROP_PROXY_CONTRACT_ID; 81 | fc_data_base["method"] = "send"; 82 | fc_data_base["args"] = argsBase; 83 | fc_data_base["deposit"] = parseNearAmount((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET + STORAGE).toString()); 84 | console.log("Base case deposit: ", (parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET + STORAGE).toString()); 85 | 86 | let argsArray = []; 87 | argsArray.push(fc_data_base); 88 | console.log('argsArray: ', argsArray); 89 | 90 | let fc_data_final = {}; 91 | for(var i = 1; i < keyPairs.length-1; i++) { 92 | let args = JSON.stringify({ 93 | public_key: keyPairs[i].publicKey.toString(), 94 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT), 95 | fc_data: argsArray[i - 1], 96 | }); 97 | 98 | fc_data_final["receiver"] = LINKDROP_PROXY_CONTRACT_ID; 99 | fc_data_final["method"] = "send"; 100 | fc_data_final["args"] = args; 101 | fc_data_final["deposit"] = parseNearAmount(((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET + STORAGE) * (i+1)).toString()); 102 | console.log("deposit for iter: ", i, " : ", ((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET + STORAGE)) * (i+1).toString()); 103 | 104 | //console.log('fc_data_final: ', fc_data_final); 105 | console.log('args Length: ', args.length); 106 | 107 | argsArray.push(fc_data_final); 108 | } 109 | 110 | console.log('fc_data_final: ', fc_data_final); 111 | 112 | await fundingAccount.functionCall( 113 | LINKDROP_PROXY_CONTRACT_ID, 114 | 'send', 115 | { 116 | public_key: keyPairs[keyPairs.length - 1].publicKey.toString(), 117 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT), 118 | fc_data: fc_data_final, 119 | }, 120 | "300000000000000", 121 | parseNearAmount(((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET + STORAGE) * (keyPairs.length)).toString()) 122 | ); 123 | } catch(e) { 124 | console.log('error initializing contract: ', e); 125 | } 126 | 127 | for(var i = 0; i < keyPairs.length; i++) { 128 | console.log(`https://wallet.testnet.near.org/linkdrop/${LINKDROP_PROXY_CONTRACT_ID}/${keyPairs[i].secretKey}`); 129 | console.log("Pub Key: ", keyPairs[i].publicKey.toString()); 130 | } 131 | } 132 | 133 | 134 | start(); -------------------------------------------------------------------------------- /deploy/ft.js: -------------------------------------------------------------------------------- 1 | const { connect, KeyPair, keyStores, utils } = require("near-api-js"); 2 | const { parseNearAmount, formatNearAmount } = require("near-api-js/lib/utils/format"); 3 | const path = require("path"); 4 | const homedir = require("os").homedir(); 5 | 6 | let LINKDROP_PROXY_CONTRACT_ID = process.env.LINKDROP_PROXY_CONTRACT_ID; 7 | let FUNDING_ACCOUNT_ID = process.env.FUNDING_ACCOUNT_ID; 8 | let LINKDROP_NEAR_AMOUNT = process.env.LINKDROP_NEAR_AMOUNT; 9 | let FT_CONTRACT_ID = process.env.FT_CONTRACT_ID; 10 | let SEND_MULTIPLE = process.env.SEND_MULTIPLE; 11 | 12 | let OFFSET = 2; 13 | let NETWORK_ID = "testnet"; 14 | let near; 15 | let config; 16 | let keyStore; 17 | 18 | // set up near 19 | const initiateNear = async () => { 20 | const CREDENTIALS_DIR = ".near-credentials"; 21 | 22 | const credentialsPath = (await path).join(homedir, CREDENTIALS_DIR); 23 | (await path).join; 24 | keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath); 25 | 26 | config = { 27 | networkId: NETWORK_ID, 28 | keyStore, 29 | nodeUrl: "https://rpc.testnet.near.org", 30 | walletUrl: "https://wallet.testnet.near.org", 31 | helperUrl: "https://helper.testnet.near.org", 32 | explorerUrl: "https://explorer.testnet.near.org", 33 | }; 34 | 35 | near = await connect(config); 36 | }; 37 | 38 | async function start() { 39 | //deployed linkdrop proxy contract 40 | await initiateNear(); 41 | 42 | if(!LINKDROP_PROXY_CONTRACT_ID || !FUNDING_ACCOUNT_ID || !LINKDROP_NEAR_AMOUNT || !SEND_MULTIPLE) { 43 | throw "must specify proxy contract ID, funding account ID, linkdrop $NEAR amount and whether to send multiple"; 44 | } 45 | 46 | const contractAccount = await near.account(LINKDROP_PROXY_CONTRACT_ID); 47 | const fundingAccount = await near.account(FUNDING_ACCOUNT_ID); 48 | 49 | console.log(`initializing contract for account ${LINKDROP_PROXY_CONTRACT_ID}`); 50 | try { 51 | await contractAccount.functionCall( 52 | LINKDROP_PROXY_CONTRACT_ID, 53 | 'new', 54 | { 55 | linkdrop_contract: "testnet" 56 | }, 57 | "300000000000000", 58 | ); 59 | } catch(e) { 60 | console.log('error initializing contract: ', e); 61 | } 62 | 63 | let keyPairs = []; 64 | let pubKeys = []; 65 | 66 | if(SEND_MULTIPLE != "false") { 67 | console.log("BATCH Creating keypairs"); 68 | for(var i = 0; i < 5; i++) { 69 | console.log('i: ', i); 70 | let keyPair = await KeyPair.fromRandom('ed25519'); 71 | keyPairs.push(keyPair); 72 | pubKeys.push(keyPair.publicKey.toString()); 73 | } 74 | console.log("Finished."); 75 | } else { 76 | let keyPair = await KeyPair.fromRandom('ed25519'); 77 | keyPairs.push(keyPair); 78 | pubKeys.push(keyPair.publicKey.toString()); 79 | } 80 | 81 | console.log(`sending ${LINKDROP_NEAR_AMOUNT} $NEAR as ${FUNDING_ACCOUNT_ID}`); 82 | try { 83 | let ft_data = {}; 84 | ft_data["ft_contract"] = FT_CONTRACT_ID; 85 | ft_data["ft_sender"] = FUNDING_ACCOUNT_ID; 86 | ft_data["ft_balance"] = "25"; 87 | 88 | if(SEND_MULTIPLE != "false") { 89 | await fundingAccount.functionCall( 90 | LINKDROP_PROXY_CONTRACT_ID, 91 | 'send_multiple', 92 | { 93 | public_keys: pubKeys, 94 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT), 95 | ft_data 96 | }, 97 | "300000000000000", 98 | parseNearAmount(((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET) * pubKeys.length).toString()) 99 | ); 100 | } else { 101 | console.log("Sending one linkdrop"); 102 | await fundingAccount.functionCall( 103 | LINKDROP_PROXY_CONTRACT_ID, 104 | 'send', 105 | { 106 | public_key: pubKeys[0], 107 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT), 108 | ft_data 109 | }, 110 | "300000000000000", 111 | parseNearAmount((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET).toString()) 112 | ); 113 | } 114 | } catch(e) { 115 | console.log('error initializing contract: ', e); 116 | } 117 | 118 | try { 119 | for(var i = 0; i < pubKeys.length; i++) { 120 | console.log(`Paying for FT storage on contract: ${FT_CONTRACT_ID} for the proxy contract ID`); 121 | await fundingAccount.functionCall( 122 | FT_CONTRACT_ID, 123 | 'storage_deposit', 124 | { 125 | account_id: LINKDROP_PROXY_CONTRACT_ID, 126 | }, 127 | "300000000000000", 128 | parseNearAmount('1') 129 | ); 130 | 131 | console.log(`Transferring 25 FTs from ${FUNDING_ACCOUNT_ID} to ${LINKDROP_PROXY_CONTRACT_ID}`); 132 | await fundingAccount.functionCall( 133 | FT_CONTRACT_ID, 134 | 'ft_transfer_call', 135 | { 136 | receiver_id: LINKDROP_PROXY_CONTRACT_ID, 137 | amount: "25", 138 | msg: pubKeys[i], 139 | }, 140 | "300000000000000", 141 | '1' 142 | ); 143 | } 144 | } catch(e) { 145 | console.log('error sending FTs: ', e); 146 | } 147 | 148 | for(var i = 0; i < keyPairs.length; i++) { 149 | console.log(`https://wallet.testnet.near.org/linkdrop/${LINKDROP_PROXY_CONTRACT_ID}/${keyPairs[i].secretKey}`); 150 | console.log("Pub Key: ", keyPairs[i].publicKey.toString()); 151 | } 152 | } 153 | 154 | start(); -------------------------------------------------------------------------------- /deploy/function-call.js: -------------------------------------------------------------------------------- 1 | const { connect, KeyPair, keyStores, utils } = require("near-api-js"); 2 | const { parseNearAmount, formatNearAmount } = require("near-api-js/lib/utils/format"); 3 | const path = require("path"); 4 | const homedir = require("os").homedir(); 5 | 6 | let LINKDROP_PROXY_CONTRACT_ID = process.env.LINKDROP_PROXY_CONTRACT_ID; 7 | let FUNDING_ACCOUNT_ID = process.env.FUNDING_ACCOUNT_ID; 8 | let LINKDROP_NEAR_AMOUNT = process.env.LINKDROP_NEAR_AMOUNT; 9 | let SEND_MULTIPLE = process.env.SEND_MULTIPLE; 10 | 11 | let OFFSET = 2; 12 | 13 | let NETWORK_ID = "testnet"; 14 | let near; 15 | let config; 16 | let keyStore; 17 | 18 | const METADATA = { 19 | "title": "My Linkdrop Called This Function!", 20 | "description": "Linkdrop NFT that was lazy minted when the linkdrop was claimed", 21 | "media": "https://bafybeicek3skoaae4p5chsutjzytls5dmnj5fbz6iqsd2uej334sy46oge.ipfs.nftstorage.link/", 22 | "media_hash": null, 23 | "copies": 10000, 24 | "issued_at": null, 25 | "expires_at": null, 26 | "starts_at": null, 27 | "updated_at": null, 28 | "extra": null, 29 | "reference": null, 30 | "reference_hash": null 31 | }; 32 | 33 | // set up near 34 | const initiateNear = async () => { 35 | const CREDENTIALS_DIR = ".near-credentials"; 36 | 37 | const credentialsPath = (await path).join(homedir, CREDENTIALS_DIR); 38 | (await path).join; 39 | keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath); 40 | 41 | config = { 42 | networkId: NETWORK_ID, 43 | keyStore, 44 | nodeUrl: "https://rpc.testnet.near.org", 45 | walletUrl: "https://wallet.testnet.near.org", 46 | helperUrl: "https://helper.testnet.near.org", 47 | explorerUrl: "https://explorer.testnet.near.org", 48 | }; 49 | 50 | near = await connect(config); 51 | }; 52 | 53 | async function start() { 54 | //deployed linkdrop proxy contract 55 | await initiateNear(); 56 | 57 | if(!LINKDROP_PROXY_CONTRACT_ID || !FUNDING_ACCOUNT_ID || !LINKDROP_NEAR_AMOUNT || !SEND_MULTIPLE) { 58 | throw "must specify proxy contract ID, funding account ID, linkdrop $NEAR amount and whether to send multiple"; 59 | } 60 | 61 | const contractAccount = await near.account(LINKDROP_PROXY_CONTRACT_ID); 62 | const fundingAccount = await near.account(FUNDING_ACCOUNT_ID); 63 | 64 | console.log(`initializing contract for account ${LINKDROP_PROXY_CONTRACT_ID}`); 65 | try { 66 | await contractAccount.functionCall( 67 | LINKDROP_PROXY_CONTRACT_ID, 68 | 'new', 69 | { 70 | linkdrop_contract: "testnet", 71 | }, 72 | "300000000000000", 73 | ); 74 | } catch(e) { 75 | console.log('error initializing contract: ', e); 76 | } 77 | 78 | let keyPairs = []; 79 | let pubKeys = []; 80 | let fc_data = []; 81 | 82 | if(SEND_MULTIPLE != "false") { 83 | console.log("BATCH Creating keypairs"); 84 | for(var i = 0; i < 5; i++) { 85 | console.log('i: ', i); 86 | let keyPair = await KeyPair.fromRandom('ed25519'); 87 | keyPairs.push(keyPair); 88 | pubKeys.push(keyPair.publicKey.toString()); 89 | 90 | fc_data.push( 91 | { 92 | receiver: "example-nft.testnet", 93 | method: "nft_mint", 94 | args: JSON.stringify({ 95 | token_id: keyPair.publicKey.toString(), 96 | token_metadata: METADATA, 97 | }), 98 | deposit: parseNearAmount("1"), 99 | refund_to_deposit: true, 100 | claimed_account_field: "receiver_id" 101 | } 102 | ); 103 | } 104 | console.log("Finished."); 105 | } else { 106 | let keyPair = await KeyPair.fromRandom('ed25519'); 107 | keyPairs.push(keyPair); 108 | pubKeys.push(keyPair.publicKey.toString()); 109 | 110 | fc_data.push( 111 | { 112 | receiver: "example-nft.testnet", 113 | method: "nft_mint", 114 | args: JSON.stringify({ 115 | token_id: keyPair.publicKey.toString(), 116 | token_metadata: METADATA, 117 | }), 118 | deposit: parseNearAmount("1"), 119 | refund_to_deposit: true, 120 | claimed_account_field: "receiver_id" 121 | } 122 | ); 123 | } 124 | 125 | try { 126 | if(SEND_MULTIPLE != "false") { 127 | await fundingAccount.functionCall( 128 | LINKDROP_PROXY_CONTRACT_ID, 129 | 'send_multiple', 130 | { 131 | public_keys: pubKeys, 132 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT), 133 | fc_data 134 | }, 135 | "300000000000000", 136 | parseNearAmount(((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET) * pubKeys.length).toString()) 137 | ); 138 | } else { 139 | console.log("Sending one linkdrop"); 140 | await fundingAccount.functionCall( 141 | LINKDROP_PROXY_CONTRACT_ID, 142 | 'send', 143 | { 144 | public_key: pubKeys[0], 145 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT), 146 | fc_data: fc_data[0] 147 | }, 148 | "300000000000000", 149 | parseNearAmount((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET).toString()) 150 | ); 151 | } 152 | 153 | } catch(e) { 154 | console.log('error initializing contract: ', e); 155 | } 156 | 157 | for(var i = 0; i < keyPairs.length; i++) { 158 | console.log(`https://wallet.testnet.near.org/linkdrop/${LINKDROP_PROXY_CONTRACT_ID}/${keyPairs[i].secretKey}`); 159 | console.log("Pub Key: ", keyPairs[i].publicKey.toString()); 160 | } 161 | } 162 | 163 | 164 | start(); -------------------------------------------------------------------------------- /contract/src/views.rs: -------------------------------------------------------------------------------- 1 | use crate::*; 2 | 3 | #[near_bindgen] 4 | impl LinkDropProxy { 5 | /// Returns the balance associated with given key. This is used by the NEAR wallet to display the amount of the linkdrop 6 | pub fn get_key_balance(&self, key: PublicKey) -> U128 { 7 | let account_data = self.data_for_pk 8 | .get(&key) 9 | .expect("Key missing"); 10 | (account_data.balance.0).into() 11 | } 12 | 13 | /* 14 | CUSTOM 15 | */ 16 | 17 | /// Query for the total supply of linkdrops on the contract 18 | pub fn key_total_supply( 19 | &self 20 | ) -> U128 { 21 | //return the length of the data_for_pk set 22 | U128(self.data_for_pk.len() as u128) 23 | } 24 | 25 | /// Paginate through all active keys on the contract and return a vector of key info. 26 | pub fn get_keys( 27 | &self, 28 | from_index: Option, 29 | limit: Option 30 | ) -> Vec { 31 | //where to start pagination - if we have a from_index, we'll use that - otherwise start from 0 index 32 | let start = u128::from(from_index.unwrap_or(U128(0))); 33 | 34 | //iterate through each key using an iterator 35 | self.data_for_pk.keys() 36 | //skip to the index we specified in the start variable 37 | .skip(start as usize) 38 | //take the first "limit" elements in the vector. If we didn't specify a limit, use 50 39 | .take(limit.unwrap_or(50) as usize) 40 | //we'll map the public keys which are strings into KeyInfos 41 | .map(|pk| self.get_key_information(pk.clone())) 42 | //since we turned the keys into an iterator, we need to turn it back into a vector to return 43 | .collect() 44 | } 45 | 46 | 47 | /// Returns the total supply of active keys for a given funder 48 | pub fn key_supply_for_funder( 49 | &self, 50 | account_id: AccountId, 51 | ) -> U128 { 52 | //get the set of keys for the passed in funder 53 | let keys_for_owner = self.keys_for_funder.get(&account_id); 54 | 55 | //if there is some set of keys, we'll return the length as a U128 56 | if let Some(keys_for_owner) = keys_for_owner { 57 | U128(keys_for_owner.len() as u128) 58 | } else { 59 | //if there isn't a set of keys for the passed in account ID, we'll return 0 60 | U128(0) 61 | } 62 | } 63 | 64 | /// Paginate through active keys for a given funder and return the key info. 65 | pub fn keys_for_funder( 66 | &self, 67 | account_id: AccountId, 68 | from_index: Option, 69 | limit: Option 70 | ) -> Vec { 71 | //get the set of keys for the passed in funder 72 | let keys_for_owner = self.keys_for_funder.get(&account_id); 73 | 74 | //if there is some set of keys, we'll set the public_keys variable equal to that set 75 | let public_keys = if let Some(keys_for_owner) = keys_for_owner { 76 | keys_for_owner 77 | } else { 78 | //if there is no set of keys, we'll simply return an empty vector. 79 | return vec![]; 80 | }; 81 | 82 | //where to start pagination - if we have a from_index, we'll use that - otherwise start from 0 index 83 | let start = u128::from(from_index.unwrap_or(U128(0))); 84 | 85 | //iterate through the public keys 86 | public_keys.iter() 87 | //skip to the index we specified in the start variable 88 | .skip(start as usize) 89 | //take the first "limit" elements in the vector. If we didn't specify a limit, use 50 90 | .take(limit.unwrap_or(50) as usize) 91 | //we'll map the public keys which are strings into KeyInfos 92 | .map(|pk| self.get_key_information(pk.clone())) 93 | //since we turned the keys into an iterator, we need to turn it back into a vector to return 94 | .collect() 95 | } 96 | 97 | /// Returns the data corresponding to a specific key 98 | pub fn get_key_information( 99 | &self, 100 | key: PublicKey 101 | ) -> KeyInfo { 102 | // By default, every key should have account data 103 | let account_data = self.data_for_pk 104 | .get(&key); 105 | 106 | // If there's no account data, return none across the board. 107 | if account_data.is_none() { 108 | return KeyInfo { 109 | pk: None, 110 | account_data: None, 111 | fc_data: None, 112 | nft_data: None, 113 | ft_data: None 114 | } 115 | } 116 | 117 | // Default all callback data to None 118 | let mut key_info = KeyInfo { 119 | pk: Some(key), 120 | account_data: account_data.clone(), 121 | fc_data: None, 122 | nft_data: None, 123 | ft_data: None 124 | }; 125 | 126 | // If there's a Nonce, return all callback data related to that nonce. 127 | if let Some(nonce) = account_data.unwrap().cb_id { 128 | key_info.ft_data = self.ft.get(&nonce); 129 | key_info.nft_data = self.nft.get(&nonce); 130 | key_info.fc_data = self.fc.get(&nonce); 131 | } 132 | 133 | // Return the key info 134 | key_info 135 | } 136 | 137 | /// Returns the current nonce on the contract 138 | pub fn get_nonce(&self) -> u64 { 139 | self.nonce 140 | } 141 | } -------------------------------------------------------------------------------- /deploy/nft.js: -------------------------------------------------------------------------------- 1 | const { connect, KeyPair, keyStores, utils } = require("near-api-js"); 2 | const { parseNearAmount, formatNearAmount } = require("near-api-js/lib/utils/format"); 3 | const path = require("path"); 4 | const homedir = require("os").homedir(); 5 | 6 | let LINKDROP_PROXY_CONTRACT_ID = process.env.LINKDROP_PROXY_CONTRACT_ID; 7 | let FUNDING_ACCOUNT_ID = process.env.FUNDING_ACCOUNT_ID; 8 | let LINKDROP_NEAR_AMOUNT = process.env.LINKDROP_NEAR_AMOUNT; 9 | let SEND_MULTIPLE = process.env.SEND_MULTIPLE; 10 | 11 | let OFFSET = 2; 12 | 13 | let NETWORK_ID = "testnet"; 14 | let near; 15 | let config; 16 | let keyStore; 17 | 18 | /* 19 | Hard coding NFT contract and metadata. Change this if you want. 20 | */ 21 | let NFT_CONTRACT_ID = "example-nft.testnet"; 22 | const METADATA = { 23 | "title": "Linkdropped Go Team NFT", 24 | "description": "Testing Linkdrop NFT Go Team Token", 25 | "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif", 26 | "media_hash": null, 27 | "copies": 10000, 28 | "issued_at": null, 29 | "expires_at": null, 30 | "starts_at": null, 31 | "updated_at": null, 32 | "extra": null, 33 | "reference": null, 34 | "reference_hash": null 35 | }; 36 | 37 | // set up near 38 | const initiateNear = async () => { 39 | const CREDENTIALS_DIR = ".near-credentials"; 40 | 41 | const credentialsPath = (await path).join(homedir, CREDENTIALS_DIR); 42 | (await path).join; 43 | keyStore = new keyStores.UnencryptedFileSystemKeyStore(credentialsPath); 44 | 45 | config = { 46 | networkId: NETWORK_ID, 47 | keyStore, 48 | nodeUrl: "https://rpc.testnet.near.org", 49 | walletUrl: "https://wallet.testnet.near.org", 50 | helperUrl: "https://helper.testnet.near.org", 51 | explorerUrl: "https://explorer.testnet.near.org", 52 | }; 53 | 54 | near = await connect(config); 55 | }; 56 | 57 | async function start() { 58 | //deployed linkdrop proxy contract 59 | await initiateNear(); 60 | 61 | if(!LINKDROP_PROXY_CONTRACT_ID || !FUNDING_ACCOUNT_ID || !LINKDROP_NEAR_AMOUNT || !SEND_MULTIPLE) { 62 | throw "must specify proxy contract ID, funding account ID, linkdrop $NEAR amount and whether to send multiple"; 63 | } 64 | 65 | const contractAccount = await near.account(LINKDROP_PROXY_CONTRACT_ID); 66 | const fundingAccount = await near.account(FUNDING_ACCOUNT_ID); 67 | 68 | console.log(`initializing contract for account ${LINKDROP_PROXY_CONTRACT_ID}`); 69 | try { 70 | await contractAccount.functionCall( 71 | LINKDROP_PROXY_CONTRACT_ID, 72 | 'new', 73 | { 74 | linkdrop_contract: "testnet", 75 | }, 76 | "300000000000000", 77 | ); 78 | } catch(e) { 79 | console.log('error initializing contract: ', e); 80 | } 81 | 82 | let keyPairs = []; 83 | let pubKeys = []; 84 | let nft_data = []; 85 | 86 | if(SEND_MULTIPLE != "false") { 87 | console.log("BATCH Creating keypairs"); 88 | for(var i = 0; i < 5; i++) { 89 | console.log('i: ', i); 90 | let keyPair = await KeyPair.fromRandom('ed25519'); 91 | keyPairs.push(keyPair); 92 | pubKeys.push(keyPair.publicKey.toString()); 93 | 94 | nft_data.push({ 95 | nft_sender: FUNDING_ACCOUNT_ID, 96 | nft_contract: NFT_CONTRACT_ID, 97 | nft_token_id: keyPair.publicKey.toString() 98 | }); 99 | } 100 | console.log("Finished."); 101 | } else { 102 | let keyPair = await KeyPair.fromRandom('ed25519'); 103 | keyPairs.push(keyPair); 104 | pubKeys.push(keyPair.publicKey.toString()); 105 | 106 | nft_data.push({ 107 | nft_sender: FUNDING_ACCOUNT_ID, 108 | nft_contract: NFT_CONTRACT_ID, 109 | nft_token_id: keyPair.publicKey.toString() 110 | }); 111 | } 112 | 113 | try { 114 | if(SEND_MULTIPLE != "false") { 115 | await fundingAccount.functionCall( 116 | LINKDROP_PROXY_CONTRACT_ID, 117 | 'send_multiple', 118 | { 119 | public_keys: pubKeys, 120 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT), 121 | nft_data 122 | }, 123 | "300000000000000", 124 | parseNearAmount(((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET) * pubKeys.length).toString()) 125 | ); 126 | } else { 127 | console.log("Sending one linkdrop"); 128 | await fundingAccount.functionCall( 129 | LINKDROP_PROXY_CONTRACT_ID, 130 | 'send', 131 | { 132 | public_key: pubKeys[0], 133 | balance: parseNearAmount(LINKDROP_NEAR_AMOUNT), 134 | nft_data: nft_data[0] 135 | }, 136 | "300000000000000", 137 | parseNearAmount((parseFloat(LINKDROP_NEAR_AMOUNT) + OFFSET).toString()) 138 | ); 139 | } 140 | 141 | } catch(e) { 142 | console.log('error initializing contract: ', e); 143 | } 144 | 145 | try { 146 | for(var i = 0; i < pubKeys.length; i++) { 147 | console.log(`minting NFT with token ID ${nft_data[i].nft_token_id} on contract ${NFT_CONTRACT_ID} with receiver: ${FUNDING_ACCOUNT_ID}`); 148 | 149 | await fundingAccount.functionCall( 150 | NFT_CONTRACT_ID, 151 | 'nft_mint', 152 | { 153 | token_id: nft_data[i].nft_token_id, 154 | receiver_id: FUNDING_ACCOUNT_ID, 155 | token_metadata: METADATA, 156 | }, 157 | "300000000000000", 158 | parseNearAmount('1') 159 | ); 160 | 161 | console.log(`transferring NFT to linkdrop proxy contract with nft_transfer_call`); 162 | await fundingAccount.functionCall( 163 | NFT_CONTRACT_ID, 164 | 'nft_transfer_call', 165 | { 166 | token_id: nft_data[i].nft_token_id, 167 | receiver_id: LINKDROP_PROXY_CONTRACT_ID, 168 | msg: pubKeys[i], 169 | }, 170 | "300000000000000", 171 | '1' 172 | ); 173 | } 174 | } catch(e) { 175 | console.log('error minting and sending NFTs: ', e); 176 | } 177 | 178 | for(var i = 0; i < keyPairs.length; i++) { 179 | console.log(`https://wallet.testnet.near.org/linkdrop/${LINKDROP_PROXY_CONTRACT_ID}/${keyPairs[i].secretKey}`); 180 | console.log("Pub Key: ", keyPairs[i].publicKey.toString()); 181 | } 182 | } 183 | 184 | start(); -------------------------------------------------------------------------------- /test/api.test.js: -------------------------------------------------------------------------------- 1 | const assert = require('assert'); 2 | const { KeyPair, Account } = require('near-api-js'); 3 | const { parseNearAmount } = require('near-api-js/lib/utils/format'); 4 | const testUtils = require('./test-utils'); 5 | 6 | let { 7 | near, 8 | networkId, 9 | contractId, 10 | contractAccount, 11 | recordStart, 12 | recordStop, 13 | getAccount, 14 | } = testUtils; 15 | 16 | let linkdropAccount = contractAccount; 17 | /// contractAccount is the devAccount - testing against deployed contract on testnet 18 | const useDeployedLinkdrop = false; 19 | if (useDeployedLinkdrop) { 20 | contractId = 'linkdrop-wrapper.testnet'; 21 | linkdropAccount = new Account(near.connection, contractId); 22 | } 23 | 24 | // 85 Tgas is enough with callback check 25 | const gas = '85000000000000'; 26 | const gasMultiple = '200000000000000'; 27 | const attachedDeposit = parseNearAmount('0.03') 28 | const attachedDepositDouble = parseNearAmount('0.06') 29 | 30 | describe('Linkdrop Proxy', function () { 31 | this.timeout(60000); 32 | 33 | const aliceId = 'alice-test.' + contractId 34 | 35 | // linkdrop keypairs 36 | const keyPair1 = KeyPair.fromRandom('ed25519'); 37 | const keyPair2 = KeyPair.fromRandom('ed25519'); 38 | const public_key1 = keyPair1.publicKey.toString(); 39 | const public_key2 = keyPair2.publicKey.toString(); 40 | // the new account's keypair 41 | const keyPairNewAccount = KeyPair.fromRandom('ed25519'); 42 | const new_public_key = keyPairNewAccount.publicKey.toString(); 43 | 44 | it('accounts and contract deployed', async function() { 45 | 46 | alice = await getAccount(aliceId); 47 | // console.log(alice) 48 | 49 | const state = await linkdropAccount.state(); 50 | if (state.code_hash.indexOf('111111') === 0) { 51 | return assert(true) 52 | } 53 | try { 54 | await contractAccount.functionCall({ 55 | contractId, 56 | methodName: 'new', 57 | args: { 58 | linkdrop_contract: 'testnet', 59 | }, 60 | gas 61 | }); 62 | } catch (e) { 63 | if (!/contract has already been initialized/.test(e.toString())) { 64 | console.warn(e); 65 | } 66 | } 67 | 68 | assert.notStrictEqual(state.code_hash, '11111111111111111111111111111111'); 69 | }); 70 | 71 | // it('creation of linkdrop and wallet link for testing', async function() { 72 | 73 | // await alice.functionCall({ 74 | // contractId, 75 | // methodName: 'send', 76 | // args: { 77 | // public_key: public_key1 78 | // }, 79 | // gas, 80 | // // could be 0.02 N wallet needs to reduce gas from 100 Tgas to 50 Tgas 81 | // attachedDeposit 82 | // }); 83 | 84 | // console.log(`https://wallet.testnet.near.org/linkdrop/${contractId}/${keyPair1.secretKey}?redirectUrl=https://example.com`); 85 | 86 | // return true; 87 | // }); 88 | 89 | /// keyPair1 90 | 91 | it('creation of linkdrops', async function() { 92 | 93 | const EXTRA = 0 94 | const extraKeys = [] 95 | for (let i = 0; i < EXTRA; i++) { 96 | extraKeys.push(KeyPair.fromRandom('ed25519').publicKey.toString()) 97 | } 98 | 99 | await recordStart(contractId) 100 | 101 | const res = await alice.functionCall({ 102 | contractId, 103 | methodName: 'send_multiple', 104 | args: { 105 | public_keys: [public_key1, public_key2, ...extraKeys], 106 | balance: 0, 107 | }, 108 | gas: gasMultiple, 109 | attachedDeposit: parseNearAmount((0.03 * (EXTRA+2)).toString()) 110 | }); 111 | 112 | console.log(`https://wallet.testnet.near.org/linkdrop/${contractId}/${keyPair1.secretKey}?redirectUrl=https://example.com`); 113 | console.log(`https://wallet.testnet.near.org/linkdrop/${contractId}/${keyPair2.secretKey}?redirectUrl=https://example.com`); 114 | 115 | assert.strictEqual(res.status.SuccessValue, ''); 116 | }); 117 | 118 | // it('creation of account', async function() { 119 | // // WARNING tests after this with contractAccount will fail - signing key lost 120 | // // set key for contractAccount to linkdrop keyPair 121 | // near.connection.signer.keyStore.setKey(networkId, contractId, keyPair1); 122 | // const new_account_id = 'linkdrop-wrapper-' + Date.now().toString() + '.testnet'; 123 | 124 | // const res = await linkdropAccount.functionCall({ 125 | // contractId, 126 | // methodName: 'create_account_and_claim', 127 | // args: { 128 | // new_account_id, 129 | // new_public_key, 130 | // }, 131 | // gas, 132 | // }); 133 | 134 | // await recordStop(contractId) 135 | 136 | // console.log('created account', new_account_id) 137 | 138 | // try { 139 | // await (new Account(near.connection, new_account_id)).state() 140 | // assert(true) 141 | // } catch (e) { 142 | // assert(false) 143 | // } 144 | // }); 145 | 146 | /// keyPair2 147 | 148 | // it('creation of linkdrop', async function() { 149 | 150 | // await recordStart(contractId) 151 | 152 | // const res = await alice.functionCall({ 153 | // contractId, 154 | // methodName: 'send', 155 | // args: { 156 | // public_key: public_key2 157 | // }, 158 | // gas, 159 | // attachedDeposit 160 | // }); 161 | 162 | // assert.strictEqual(res.status.SuccessValue, ''); 163 | // }); 164 | 165 | // it('claim of linkdrop', async function() { 166 | // // WARNING tests after this with contractAccount will fail - signing key lost 167 | // // set key for contractAccount to linkdrop keyPair 168 | // near.connection.signer.keyStore.setKey(networkId, contractId, keyPair2); 169 | // const account_id = 'testnet'; 170 | 171 | // const res = await linkdropAccount.functionCall({ 172 | // contractId, 173 | // methodName: 'claim', 174 | // args: { 175 | // account_id, 176 | // }, 177 | // gas, 178 | // }); 179 | 180 | // await recordStop(contractId) 181 | 182 | // // console.log(res) 183 | 184 | // assert(true) 185 | // }); 186 | 187 | /// testing if promise fails (must edit contract->on_account_created to return false) 188 | // it('creation of account - FAIL', async function() { 189 | // near.connection.signer.keyStore.setKey(networkId, contractId, keyPair2); 190 | // const new_account_id = 'linkdrop-wrapper-' + Date.now().toString(); 191 | 192 | // try { 193 | // const res = await linkdropAccount.functionCall({ 194 | // contractId, 195 | // methodName: 'create_account_and_claim', 196 | // args: { 197 | // new_account_id, 198 | // new_public_key, 199 | // }, 200 | // gas, 201 | // }); 202 | 203 | // console.log(new_account_id); 204 | // console.log(Buffer.from(res.status.SuccessValue, 'base64').toString('utf-8')) 205 | 206 | // // console.log(res) 207 | // // true 208 | // assert.strictEqual(res.status.SuccessValue, 'dHJ1ZQ=='); 209 | // } catch(e) { 210 | // console.log('fail') 211 | // console.log(keyPair2.publicKey.toString()) 212 | // } 213 | 214 | // }); 215 | 216 | }); 217 | -------------------------------------------------------------------------------- /contract/src/lib.rs: -------------------------------------------------------------------------------- 1 | use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; 2 | use near_sdk::collections::{LookupMap, UnorderedMap, UnorderedSet}; 3 | use near_sdk::json_types::U128; 4 | use near_sdk::serde::{Deserialize, Serialize}; 5 | use near_sdk::serde_json::{json}; 6 | use near_sdk::{ 7 | env, ext_contract, near_bindgen, AccountId, BorshStorageKey, Gas, PanicOnDefault, 8 | Promise, PromiseResult, PublicKey, PromiseOrValue, promise_result_as_success, CryptoHash, 9 | }; 10 | 11 | /* 12 | minimum amount of storage required to store an access key on the contract 13 | 1_330_000_000_000_000_000_000 Simple linkdrop: 0.00133 $NEAR 14 | 2_420_000_000_000_000_000_000 NFT Linkdrop: 0.00242 $NEAR 15 | */ 16 | const ACCESS_KEY_STORAGE: u128 = 1_000_000_000_000_000_000_000; // 0.001 N 17 | 18 | 19 | /* 20 | allowance for the access key to cover GAS fees when the account is claimed. This amount is will not be "reserved" on the contract but must be 21 | available when GAS is burnt using the access key. The burnt GAS will not be refunded but any unburnt GAS that remains can be refunded. 22 | 23 | If this is lower, wallet will throw the following error: 24 | Access Key {account_id}:{public_key} does not have enough balance 0.01 for transaction costing 0.018742491841859367297184 25 | */ 26 | const ACCESS_KEY_ALLOWANCE: u128 = 20_000_000_000_000_000_000_000; // 0.02 N (200 TGas) 27 | 28 | /* 29 | minimum amount of NEAR that a new account (with longest possible name) must have when created 30 | If this is less, it will throw a lack balance for state error (assuming you have the same account ID length) 31 | */ 32 | const NEW_ACCOUNT_BASE: u128 = 2_840_000_000_000_000_000_000; // 0.00284 N 33 | 34 | /// Indicates there are no deposit for a callback for better readability. 35 | const NO_DEPOSIT: u128 = 0; 36 | 37 | // Defaulting burnt GAS to be 100 TGas (0.01 $NEAR) 38 | const BURNT_GAS: u128 = 10_000_000_000_000_000_000_000; 39 | 40 | /* 41 | GAS Constants (outlines the minimum to attach. Any unspent GAS will be added according to the weights) 42 | */ 43 | const MIN_GAS_FOR_ON_CLAIM: Gas = Gas(55_000_000_000_000); // 55 TGas 44 | 45 | // NFTs 46 | const MIN_GAS_FOR_SIMPLE_NFT_TRANSFER: Gas = Gas(10_000_000_000_000); // 10 TGas 47 | const MIN_GAS_FOR_RESOLVE_TRANSFER: Gas = Gas(15_000_000_000_000 + MIN_GAS_FOR_SIMPLE_NFT_TRANSFER.0); // 15 TGas + 10 TGas = 25 TGas 48 | 49 | // FTs 50 | // Actual amount of GAS to attach when querying the storage balance bounds. No unspent GAS will be attached on top of this (weight of 0) 51 | const GAS_FOR_STORAGE_BALANCE_BOUNDS: Gas = Gas(10_000_000_000_000); // 10 TGas 52 | const MIN_GAS_FOR_RESOLVE_STORAGE_CHECK: Gas = Gas(25_000_000_000_000); // 25 TGas 53 | const MIN_GAS_FOR_FT_TRANSFER: Gas = Gas(5_000_000_000_000); // 5 TGas 54 | const MIN_GAS_FOR_STORAGE_DEPOSIT: Gas = Gas(5_000_000_000_000); // 5 TGas 55 | const MIN_GAS_FOR_RESOLVE_BATCH: Gas = Gas(13_000_000_000_000 + MIN_GAS_FOR_FT_TRANSFER.0 + MIN_GAS_FOR_STORAGE_DEPOSIT.0); // 13 TGas + 5 TGas + 5 TGas = 23 TGas 56 | 57 | // Function Calls 58 | const MIN_GAS_FOR_CALLBACK_FUNCTION_CALL: Gas = Gas(30_000_000_000_000); // 30 TGas 59 | 60 | // Actual amount of GAS to attach when creating a new account. No unspent GAS will be attached on top of this (weight of 0) 61 | const GAS_FOR_CREATE_ACCOUNT: Gas = Gas(28_000_000_000_000); // 28 TGas 62 | 63 | // Utils 64 | const ONE_GIGGA_GAS: u64 = 1_000_000_000; 65 | 66 | /// Methods callable by the function call access key 67 | const ACCESS_KEY_METHOD_NAMES: &str = "claim,create_account_and_claim"; 68 | 69 | mod claim; 70 | mod send; 71 | mod ext_traits; 72 | mod nft; 73 | mod ft; 74 | mod function_call; 75 | mod views; 76 | mod helpers; 77 | 78 | use crate::ext_traits::*; 79 | use crate::nft::*; 80 | use crate::ft::*; 81 | use crate::function_call::*; 82 | 83 | pub(crate) fn yocto_to_near(yocto: u128) -> f64 { 84 | //10^20 yoctoNEAR (1 NEAR would be 10_000). This is to give a precision of 4 decimal places. 85 | let formatted_near = yocto / 100_000_000_000_000_000_000; 86 | let near = formatted_near as f64 / 10_000_f64; 87 | 88 | near 89 | } 90 | 91 | /// Keep track of specific data related to an access key. This allows us to optionally refund funders later. 92 | #[near_bindgen] 93 | #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize, Serialize, Clone)] 94 | #[serde(crate = "near_sdk::serde")] 95 | pub struct AccountData { 96 | pub funder_id: AccountId, 97 | pub balance: U128, 98 | pub storage_used: U128, 99 | 100 | /* 101 | EXTRA 102 | */ 103 | pub cb_id: Option, //nonce - if set, becomes lookup to all NFT, FT, CD 104 | pub cb_data_sent: bool, 105 | 106 | } 107 | 108 | /// Keep track of specific data related to an access key. This allows us to optionally refund funders later. 109 | #[near_bindgen] 110 | #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize, Serialize)] 111 | #[serde(crate = "near_sdk::serde")] 112 | pub struct KeyInfo { 113 | pub pk: Option, 114 | pub account_data: Option, 115 | pub ft_data: Option, 116 | pub nft_data: Option, 117 | pub fc_data: Option 118 | 119 | } 120 | 121 | #[derive(BorshSerialize, BorshStorageKey)] 122 | enum StorageKey { 123 | DataForPublicKey, 124 | KeysForFunder, 125 | KeysPerFunderInner { account_id_hash: CryptoHash }, 126 | NFTData, 127 | FTData, 128 | FCData, 129 | } 130 | 131 | #[near_bindgen] 132 | #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize)] 133 | pub struct LinkDropProxy { 134 | pub linkdrop_contract: AccountId, 135 | pub data_for_pk: UnorderedMap, 136 | pub keys_for_funder: LookupMap>, 137 | 138 | pub nonce: u64, 139 | 140 | /* 141 | EXTRA 142 | */ 143 | pub nft: LookupMap, 144 | pub ft: LookupMap, 145 | pub fc: LookupMap 146 | } 147 | 148 | #[near_bindgen] 149 | impl LinkDropProxy { 150 | /// Initialize proxy hub contract and pass in the desired deployed linkdrop contract (i.e testnet or near) 151 | #[init] 152 | pub fn new(linkdrop_contract: AccountId) -> Self { 153 | Self { 154 | linkdrop_contract, 155 | data_for_pk: UnorderedMap::new(StorageKey::DataForPublicKey), 156 | keys_for_funder: LookupMap::new(StorageKey::KeysForFunder), 157 | nft: LookupMap::new(StorageKey::NFTData), 158 | ft: LookupMap::new(StorageKey::FTData), 159 | fc: LookupMap::new(StorageKey::FCData), 160 | nonce: 0, 161 | } 162 | } 163 | 164 | /// Set the desired linkdrop contract to interact with 165 | pub fn set_contract(&mut self, linkdrop_contract: AccountId) { 166 | assert_eq!( 167 | env::predecessor_account_id(), 168 | env::current_account_id(), 169 | "predecessor != current" 170 | ); 171 | self.linkdrop_contract = linkdrop_contract; 172 | } 173 | } -------------------------------------------------------------------------------- /test/test-utils.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs"); 2 | const BN = require('bn.js'); 3 | const fetch = require('node-fetch'); 4 | const nearAPI = require('near-api-js'); 5 | const { KeyPair, Account, Contract, utils: { format: { parseNearAmount, formatNearAmount } } } = nearAPI; 6 | const { near, credentials, connection, keyStore, contract, contractAccount } = require('./near-utils'); 7 | const getConfig = require('./config'); 8 | const { 9 | networkId, contractName, contractMethods, gas, 10 | NEW_ACCOUNT_AMOUNT, 11 | DEFAULT_NEW_CONTRACT_AMOUNT, 12 | } = getConfig('testnet'); 13 | 14 | const format = (amount) => { 15 | const res = formatNearAmount(amount, 8) 16 | if (res.indexOf('-') > -1) { 17 | return '-' + res.replace('-', '') 18 | } 19 | return res 20 | } 21 | 22 | const TEST_HOST = 'http://localhost:3000'; 23 | /// exports 24 | async function initContract() { 25 | /// try to call new on contract, swallow e if already initialized 26 | try { 27 | const newArgs = { 28 | linkdrop_contract: contractId 29 | }; 30 | await contract.new(newArgs); 31 | } catch (e) { 32 | if (!/initialized/.test(e.toString())) { 33 | throw e; 34 | } 35 | } 36 | return { contract, contractName }; 37 | } 38 | 39 | const initAccount = async(accountId, secret) => { 40 | account = new nearAPI.Account(connection, accountId); 41 | const newKeyPair = KeyPair.fromString(secret); 42 | keyStore.setKey(networkId, accountId, newKeyPair); 43 | return account; 44 | }; 45 | 46 | const createOrInitAccount = async(accountId, secret, amount = DEFAULT_NEW_CONTRACT_AMOUNT) => { 47 | let account; 48 | try { 49 | account = await createAccount(accountId, amount, secret); 50 | } catch (e) { 51 | if (!/because it already exists/.test(e.toString())) { 52 | throw e; 53 | } 54 | account = initAccount(accountId, secret); 55 | } 56 | return account; 57 | }; 58 | 59 | const getAccount = async (accountId, fundingAmount = NEW_ACCOUNT_AMOUNT, secret) => { 60 | const account = new nearAPI.Account(connection, accountId); 61 | try { 62 | let secret; 63 | try { 64 | secret = JSON.parse(fs.readFileSync(process.env.HOME + `/.near-credentials/${networkId}/${accountId}.json`, 'utf-8')).private_key; 65 | } catch(e) { 66 | if (!/no such file|does not exist/.test(e.toString())) { 67 | throw e; 68 | } 69 | secret = fs.readFileSync(`./neardev/${accountId}`, 'utf-8'); 70 | } 71 | const newKeyPair = KeyPair.fromString(secret); 72 | keyStore.setKey(networkId, accountId, newKeyPair); 73 | await account.state(); 74 | return account; 75 | } catch(e) { 76 | if (!/no such file|does not exist/.test(e.toString())) { 77 | throw e; 78 | } 79 | } 80 | return await createAccount(accountId, fundingAmount, secret); 81 | }; 82 | 83 | 84 | async function getContract(account) { 85 | return new Contract(account || contractAccount, contractName, { 86 | ...contractMethods, 87 | signer: account || undefined 88 | }); 89 | } 90 | 91 | 92 | const createAccessKeyAccount = (key) => { 93 | connection.signer.keyStore.setKey(networkId, contractName, key); 94 | return new Account(connection, contractName); 95 | }; 96 | 97 | const postSignedJson = async ({ account, contractName, url, data = {} }) => { 98 | return await fetch(url, { 99 | method: 'POST', 100 | headers: { 'content-type': 'application/json' }, 101 | body: JSON.stringify({ 102 | ...data, 103 | accountId: account.accountId, 104 | contractName, 105 | ...(await getSignature(account)) 106 | }) 107 | }).then((res) => { 108 | // console.log(res) 109 | return res.json(); 110 | }); 111 | }; 112 | 113 | const postJson = async ({ url, data = {} }) => { 114 | return await fetch(url, { 115 | method: 'POST', 116 | headers: { 'content-type': 'application/json' }, 117 | body: JSON.stringify({ ...data }) 118 | }).then((res) => { 119 | console.log(res); 120 | return res.json(); 121 | }); 122 | }; 123 | 124 | function generateUniqueSubAccount() { 125 | return `t${Date.now()}.${contractName}`; 126 | } 127 | 128 | /// internal 129 | const createAccount = async (accountId, fundingAmount = NEW_ACCOUNT_AMOUNT, secret) => { 130 | const newKeyPair = secret ? KeyPair.fromString(secret) : KeyPair.fromRandom('ed25519'); 131 | fs.writeFileSync(`./neardev/${accountId}` , newKeyPair.toString(), 'utf-8'); 132 | await contractAccount.createAccount(accountId, newKeyPair.publicKey, fundingAmount); 133 | keyStore.setKey(networkId, accountId, newKeyPair); 134 | return new nearAPI.Account(connection, accountId); 135 | }; 136 | 137 | const getSignature = async (account) => { 138 | const { accountId } = account; 139 | const block = await account.connection.provider.block({ finality: 'final' }); 140 | const blockNumber = block.header.height.toString(); 141 | const signer = account.inMemorySigner || account.connection.signer; 142 | const signed = await signer.signMessage(Buffer.from(blockNumber), accountId, networkId); 143 | const blockNumberSignature = Buffer.from(signed.signature).toString('base64'); 144 | return { blockNumber, blockNumberSignature }; 145 | }; 146 | 147 | const loadCredentials = (accountId) => { 148 | const credPath = `./neardev/${networkId}/${accountId}.json`; 149 | console.log( 150 | "Loading Credentials:\n", 151 | credPath 152 | ); 153 | 154 | let credentials; 155 | try { 156 | credentials = JSON.parse( 157 | fs.readFileSync( 158 | credPath 159 | ) 160 | ); 161 | } catch(e) { 162 | console.warn('credentials not in /neardev'); 163 | /// attempt to load backup creds from local machine 164 | credentials = JSON.parse( 165 | fs.readFileSync( 166 | `${process.env.HOME}/.near-credentials/${networkId}/${accountId}.json` 167 | ) 168 | ); 169 | } 170 | 171 | return credentials; 172 | }; 173 | 174 | /// debugging 175 | 176 | const getAccountBalance = (accountId) => (new nearAPI.Account(connection, accountId)).getAccountBalance(); 177 | const getAccountState = (accountId) => (new nearAPI.Account(connection, accountId)).state(); 178 | const totalDiff = (balanceBefore, balanceAfter) => format(new BN(balanceAfter.total).sub(new BN(balanceBefore.total)).toString()); 179 | const availableDiff = (balanceBefore, balanceAfter) => format(new BN(balanceAfter.available).sub(new BN(balanceBefore.available)).toString()); 180 | const stateCost = (balanceBefore, balanceAfter) => format(new BN(balanceAfter.stateStaked).sub(new BN(balanceBefore.stateStaked)).toString()); 181 | const bytesUsed = (stateBefore, stateAfter) => parseInt(stateAfter.storage_usage, 10) - parseInt(stateBefore.storage_usage); 182 | 183 | /// analyzing 184 | 185 | let data = {}; 186 | const recordStart = async (accountId) => { 187 | data[accountId] = { 188 | balance: await getAccountBalance(accountId), 189 | state: await getAccountState(accountId), 190 | }; 191 | }; 192 | 193 | const recordStop = async (accountId) => { 194 | const before = data[accountId]; 195 | const after = { 196 | balance: await getAccountBalance(accountId), 197 | state: await getAccountState(accountId), 198 | }; 199 | 200 | console.log(format(before.balance.total), format(after.balance.total)) 201 | 202 | console.log( 203 | '\n', 'Analysis:', '\n', 204 | 'Total diff:', totalDiff(before.balance, after.balance), '\n', 205 | 'Avail diff:', availableDiff(before.balance, after.balance), '\n', 206 | 'State used:', stateCost(before.balance, after.balance), '\n', 207 | 'Bytes used:', bytesUsed(before.state, after.state), '\n', 208 | ); 209 | }; 210 | 211 | module.exports = { 212 | recordStart, 213 | recordStop, 214 | TEST_HOST, 215 | near, 216 | gas, 217 | connection, 218 | credentials, 219 | keyStore, 220 | getContract, 221 | getAccountBalance, 222 | contract, 223 | contractName, 224 | networkId, 225 | contractId: contractName, 226 | contractMethods, 227 | contractAccount, 228 | initAccount, 229 | createOrInitAccount, 230 | createAccessKeyAccount, 231 | initContract, getAccount, postSignedJson, postJson, 232 | loadCredentials, 233 | }; 234 | 235 | -------------------------------------------------------------------------------- /contract/src/ft.rs: -------------------------------------------------------------------------------- 1 | use near_sdk::GasWeight; 2 | 3 | use crate::*; 4 | 5 | 6 | /// Keep track fungible token data for an access key 7 | #[near_bindgen] 8 | #[derive(PanicOnDefault, BorshDeserialize, BorshSerialize, Serialize, Deserialize, Clone)] 9 | #[serde(crate = "near_sdk::serde")] 10 | pub struct FTData { 11 | pub ft_contract: AccountId, 12 | pub ft_sender: AccountId, 13 | pub ft_balance: U128, 14 | pub ft_storage: Option, 15 | } 16 | 17 | // Returned from the storage balance bounds cross contract call on the FT contract 18 | #[derive(Deserialize)] 19 | #[serde(crate = "near_sdk::serde")] 20 | pub struct StorageBalanceBounds { 21 | pub min: U128, 22 | pub max: Option, 23 | } 24 | 25 | #[near_bindgen] 26 | impl LinkDropProxy { 27 | /// Allows users to attach fungible tokens to the Linkdrops. Must have storage recorded by this point. You can only attach one set of FTs or NFT at a time. 28 | pub fn ft_on_transfer( 29 | &mut self, 30 | sender_id: AccountId, 31 | amount: U128, 32 | msg: PublicKey, 33 | ) -> PromiseOrValue { 34 | let contract_id = env::predecessor_account_id(); 35 | 36 | // No need to assert that the funder is the sender since we don't wanna enforce anything unnecessary. 37 | // All that matters is we've received the FTs and that they belongs to some public key. 38 | let AccountData { 39 | funder_id, 40 | balance, 41 | storage_used, 42 | cb_id, 43 | cb_data_sent, 44 | } = self.data_for_pk 45 | .get(&msg) 46 | .expect("Missing public key"); 47 | 48 | // Ensure there's a callback ID (meaning the linkdrop is not a regular linkdrop) 49 | let callback_id = cb_id.expect("Callback ID must be set"); 50 | 51 | // Assert that the FTs have NOT been sent yet 52 | assert!(cb_data_sent == false, "FTs already sent. Cannot send more."); 53 | 54 | // Ensure that the linkdrop contains FT data already 55 | let FTData { 56 | ft_contract, 57 | ft_sender, 58 | ft_balance, 59 | ft_storage: _ 60 | } = self.ft.get(&callback_id).expect("No FT data found for the unique callback ID."); 61 | 62 | assert!(ft_contract == contract_id && ft_sender == sender_id && ft_balance == amount, "FT data must match what was sent"); 63 | 64 | // Insert the account data back with the cb data sent set to true 65 | self.data_for_pk.insert( 66 | &msg, 67 | &AccountData{ 68 | funder_id, 69 | balance, 70 | storage_used, 71 | cb_id, 72 | cb_data_sent: true, 73 | }, 74 | ); 75 | 76 | // Everything went well and we don't need to return any tokens 77 | PromiseOrValue::Value(U128(0)) 78 | } 79 | 80 | /// Self callback checks if fungible tokens were successfully transferred to the new account. If yes, do nothing. If no, refund original sender 81 | pub fn ft_resolve_batch( 82 | &mut self, 83 | amount: U128, 84 | token_sender: AccountId, 85 | token_contract: AccountId 86 | ) -> bool { 87 | let mut used_gas = env::used_gas(); 88 | let mut prepaid_gas = env::prepaid_gas(); 89 | 90 | env::log_str(&format!("Beginning of resolve transfer used gas: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 91 | 92 | assert_eq!( 93 | env::predecessor_account_id(), 94 | env::current_account_id(), 95 | "predecessor != current" 96 | ); 97 | assert_eq!(env::promise_results_count(), 1, "no promise result"); 98 | let transfer_succeeded = matches!(env::promise_result(0), PromiseResult::Successful(_)); 99 | 100 | 101 | used_gas = env::used_gas(); 102 | prepaid_gas = env::prepaid_gas(); 103 | env::log_str(&format!("Before refunding token sender in resolve transfer: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 104 | 105 | if transfer_succeeded { 106 | return true 107 | } 108 | // Create a new batch promise to pay storage and refund the FTs to the original sender 109 | let batch_ft_promise_id = env::promise_batch_create(&token_contract); 110 | 111 | // Send the fungible tokens (after the storage deposit is finished since these run sequentially) 112 | // Call the function with the min GAS and then attach 1/2 of the unspent GAS to the call 113 | env::promise_batch_action_function_call_weight( 114 | batch_ft_promise_id, 115 | "storage_deposit", 116 | json!({ "account_id": token_sender }).to_string().as_bytes(), 117 | amount.0, 118 | MIN_GAS_FOR_STORAGE_DEPOSIT, 119 | GasWeight(1) 120 | ); 121 | 122 | // Send the fungible tokens (after the storage deposit is finished since these run sequentially) 123 | // Call the function with the min GAS and then attach 1/2 of the unspent GAS to the call 124 | env::promise_batch_action_function_call_weight( 125 | batch_ft_promise_id, 126 | "ft_transfer", 127 | json!({ "receiver_id": token_sender, "amount": amount, "memo": "Refunding Linkdropped FT Tokens" }).to_string().as_bytes(), 128 | 1, 129 | MIN_GAS_FOR_FT_TRANSFER, 130 | GasWeight(1) 131 | ); 132 | 133 | // Return the result of the batch as the return of the function 134 | env::promise_return(batch_ft_promise_id); 135 | 136 | false 137 | } 138 | 139 | #[payable] 140 | #[private] 141 | /// self callback gets the storage balance bounds and inserts that into account data for each public key passed in 142 | pub fn resolve_storage_check( 143 | &mut self, 144 | public_keys: Vec, 145 | funder_id: AccountId, 146 | balance: U128, 147 | required_storage: U128, 148 | cb_ids: Vec, 149 | ) -> bool { 150 | let attached_deposit = env::attached_deposit(); 151 | let len = public_keys.len() as u128; 152 | 153 | // Check promise result. 154 | let result = promise_result_as_success(); 155 | 156 | if result.is_none() || cb_ids.len() as u128 != len { 157 | // Refund the funder any excess $NEAR and panic which will cause generic $NEAR linkdrops to be used 158 | env::log_str("Unsuccessful query to get storage. Refunding funder excess $NEAR and generic $NEAR linkdrop will be used."); 159 | Promise::new(funder_id.clone()).transfer(attached_deposit - (ACCESS_KEY_STORAGE + required_storage.0 + ACCESS_KEY_ALLOWANCE + balance.0) * len); 160 | for cb_id in cb_ids { 161 | self.ft.remove(&cb_id); 162 | } 163 | return false; 164 | } 165 | 166 | // Try to get the storage balance bounds from the result of the promise 167 | if let Ok(StorageBalanceBounds{ min, max: _ }) = near_sdk::serde_json::from_slice::(&result.unwrap()) { 168 | // Ensure the user attached enough to cover the regular $NEAR linkdrops case PLUS the storage for the fungible token contract for each key 169 | 170 | if attached_deposit < attached_deposit - (ACCESS_KEY_STORAGE + required_storage.0 + ACCESS_KEY_ALLOWANCE + balance.0 + min.0) * len { 171 | env::log_str("Deposit must be large enough to cover desired balance, access key allowance, and contract storage"); 172 | for cb_id in cb_ids { 173 | self.ft.remove(&cb_id); 174 | } 175 | return false; 176 | } 177 | 178 | let mut index = 0; 179 | // Loop through each public key and insert them into the map with the new FT storage 180 | for _pk_ in public_keys { 181 | // Get current FT data excluding the storage 182 | let FTData { 183 | ft_contract, 184 | ft_sender, 185 | ft_balance, 186 | ft_storage: _ 187 | } = self.ft.get(&cb_ids[index]).expect("No FT data found for the unique callback ID."); 188 | 189 | // Insert the FT data including the new storage for the unique callback ID associated with the linkdrop 190 | self.ft.insert( 191 | &cb_ids[index], 192 | &FTData { 193 | ft_contract: ft_contract, 194 | ft_sender: ft_sender, 195 | ft_balance: ft_balance, 196 | ft_storage: Some(min), 197 | } 198 | ); 199 | index += 1; 200 | } 201 | 202 | // If the user overpaid for the desired linkdrop balance, refund them. 203 | if attached_deposit > (ACCESS_KEY_STORAGE + required_storage.0 + ACCESS_KEY_ALLOWANCE + balance.0 + min.0) * len { 204 | env::log_str(&format!("Refunding User for: {}", yocto_to_near(attached_deposit - (ACCESS_KEY_STORAGE + required_storage.0 + ACCESS_KEY_ALLOWANCE + balance.0 + min.0) * len))); 205 | Promise::new(funder_id).transfer(attached_deposit - (ACCESS_KEY_STORAGE + required_storage.0 + ACCESS_KEY_ALLOWANCE + balance.0 + min.0) * len); 206 | } 207 | 208 | // Everything went well and we return true 209 | return true 210 | } else { 211 | env::log_str("Unsuccessful query to get storage. Refunding funder excess $NEAR and generic $NEAR linkdrop will be used."); 212 | // Refund the funder any excess $NEAR and panic which will cause generic $NEAR linkdrops to be used 213 | Promise::new(funder_id.clone()).transfer(attached_deposit - (ACCESS_KEY_STORAGE + required_storage.0 + ACCESS_KEY_ALLOWANCE + balance.0) * len); 214 | for cb_id in cb_ids { 215 | self.ft.remove(&cb_id); 216 | } 217 | return false; 218 | } 219 | } 220 | } 221 | -------------------------------------------------------------------------------- /contract/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "Inflector" 7 | version = "0.11.4" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "fe438c63458706e03479442743baae6c88256498e6431708f6dfc520a26515d3" 10 | 11 | [[package]] 12 | name = "ahash" 13 | version = "0.4.7" 14 | source = "registry+https://github.com/rust-lang/crates.io-index" 15 | checksum = "739f4a8db6605981345c5654f3a85b056ce52f37a39d34da03f25bf2151ea16e" 16 | 17 | [[package]] 18 | name = "aho-corasick" 19 | version = "0.7.18" 20 | source = "registry+https://github.com/rust-lang/crates.io-index" 21 | checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" 22 | dependencies = [ 23 | "memchr", 24 | ] 25 | 26 | [[package]] 27 | name = "autocfg" 28 | version = "1.0.1" 29 | source = "registry+https://github.com/rust-lang/crates.io-index" 30 | checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" 31 | 32 | [[package]] 33 | name = "base64" 34 | version = "0.13.0" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" 37 | 38 | [[package]] 39 | name = "block-buffer" 40 | version = "0.9.0" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "4152116fd6e9dadb291ae18fc1ec3575ed6d84c29642d97890f4b4a3417297e4" 43 | dependencies = [ 44 | "block-padding", 45 | "generic-array", 46 | ] 47 | 48 | [[package]] 49 | name = "block-padding" 50 | version = "0.2.1" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | checksum = "8d696c370c750c948ada61c69a0ee2cbbb9c50b1019ddb86d9317157a99c2cae" 53 | 54 | [[package]] 55 | name = "borsh" 56 | version = "0.8.2" 57 | source = "registry+https://github.com/rust-lang/crates.io-index" 58 | checksum = "09a7111f797cc721407885a323fb071636aee57f750b1a4ddc27397eba168a74" 59 | dependencies = [ 60 | "borsh-derive", 61 | "hashbrown", 62 | ] 63 | 64 | [[package]] 65 | name = "borsh-derive" 66 | version = "0.8.2" 67 | source = "registry+https://github.com/rust-lang/crates.io-index" 68 | checksum = "307f3740906bac2c118a8122fe22681232b244f1369273e45f1156b45c43d2dd" 69 | dependencies = [ 70 | "borsh-derive-internal", 71 | "borsh-schema-derive-internal", 72 | "proc-macro-crate", 73 | "proc-macro2", 74 | "syn", 75 | ] 76 | 77 | [[package]] 78 | name = "borsh-derive-internal" 79 | version = "0.8.2" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | checksum = "d2104c73179359431cc98e016998f2f23bc7a05bc53e79741bcba705f30047bc" 82 | dependencies = [ 83 | "proc-macro2", 84 | "quote", 85 | "syn", 86 | ] 87 | 88 | [[package]] 89 | name = "borsh-schema-derive-internal" 90 | version = "0.8.2" 91 | source = "registry+https://github.com/rust-lang/crates.io-index" 92 | checksum = "ae29eb8418fcd46f723f8691a2ac06857d31179d33d2f2d91eb13967de97c728" 93 | dependencies = [ 94 | "proc-macro2", 95 | "quote", 96 | "syn", 97 | ] 98 | 99 | [[package]] 100 | name = "bs58" 101 | version = "0.4.0" 102 | source = "registry+https://github.com/rust-lang/crates.io-index" 103 | checksum = "771fe0050b883fcc3ea2359b1a96bcfbc090b7116eae7c3c512c7a083fdf23d3" 104 | 105 | [[package]] 106 | name = "byteorder" 107 | version = "1.4.3" 108 | source = "registry+https://github.com/rust-lang/crates.io-index" 109 | checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" 110 | 111 | [[package]] 112 | name = "cfg-if" 113 | version = "0.1.10" 114 | source = "registry+https://github.com/rust-lang/crates.io-index" 115 | checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 116 | 117 | [[package]] 118 | name = "cfg-if" 119 | version = "1.0.0" 120 | source = "registry+https://github.com/rust-lang/crates.io-index" 121 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 122 | 123 | [[package]] 124 | name = "convert_case" 125 | version = "0.4.0" 126 | source = "registry+https://github.com/rust-lang/crates.io-index" 127 | checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" 128 | 129 | [[package]] 130 | name = "cpufeatures" 131 | version = "0.1.4" 132 | source = "registry+https://github.com/rust-lang/crates.io-index" 133 | checksum = "ed00c67cb5d0a7d64a44f6ad2668db7e7530311dd53ea79bcd4fb022c64911c8" 134 | dependencies = [ 135 | "libc", 136 | ] 137 | 138 | [[package]] 139 | name = "derive_more" 140 | version = "0.99.14" 141 | source = "registry+https://github.com/rust-lang/crates.io-index" 142 | checksum = "5cc7b9cef1e351660e5443924e4f43ab25fbbed3e9a5f052df3677deb4d6b320" 143 | dependencies = [ 144 | "convert_case", 145 | "proc-macro2", 146 | "quote", 147 | "syn", 148 | ] 149 | 150 | [[package]] 151 | name = "digest" 152 | version = "0.9.0" 153 | source = "registry+https://github.com/rust-lang/crates.io-index" 154 | checksum = "d3dd60d1080a57a05ab032377049e0591415d2b31afd7028356dbf3cc6dcb066" 155 | dependencies = [ 156 | "generic-array", 157 | ] 158 | 159 | [[package]] 160 | name = "generic-array" 161 | version = "0.14.4" 162 | source = "registry+https://github.com/rust-lang/crates.io-index" 163 | checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" 164 | dependencies = [ 165 | "typenum", 166 | "version_check", 167 | ] 168 | 169 | [[package]] 170 | name = "hashbrown" 171 | version = "0.9.1" 172 | source = "registry+https://github.com/rust-lang/crates.io-index" 173 | checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04" 174 | dependencies = [ 175 | "ahash", 176 | ] 177 | 178 | [[package]] 179 | name = "hex" 180 | version = "0.4.3" 181 | source = "registry+https://github.com/rust-lang/crates.io-index" 182 | checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" 183 | 184 | [[package]] 185 | name = "indexmap" 186 | version = "1.6.2" 187 | source = "registry+https://github.com/rust-lang/crates.io-index" 188 | checksum = "824845a0bf897a9042383849b02c1bc219c2383772efcd5c6f9766fa4b81aef3" 189 | dependencies = [ 190 | "autocfg", 191 | "hashbrown", 192 | ] 193 | 194 | [[package]] 195 | name = "itoa" 196 | version = "0.4.7" 197 | source = "registry+https://github.com/rust-lang/crates.io-index" 198 | checksum = "dd25036021b0de88a0aff6b850051563c6516d0bf53f8638938edbb9de732736" 199 | 200 | [[package]] 201 | name = "keccak" 202 | version = "0.1.0" 203 | source = "registry+https://github.com/rust-lang/crates.io-index" 204 | checksum = "67c21572b4949434e4fc1e1978b99c5f77064153c59d998bf13ecd96fb5ecba7" 205 | 206 | [[package]] 207 | name = "lazy_static" 208 | version = "1.4.0" 209 | source = "registry+https://github.com/rust-lang/crates.io-index" 210 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 211 | 212 | [[package]] 213 | name = "libc" 214 | version = "0.2.96" 215 | source = "registry+https://github.com/rust-lang/crates.io-index" 216 | checksum = "5600b4e6efc5421841a2138a6b082e07fe12f9aaa12783d50e5d13325b26b4fc" 217 | 218 | [[package]] 219 | name = "linkdrop-proxy" 220 | version = "0.1.0" 221 | dependencies = [ 222 | "near-contract-standards", 223 | "near-sdk", 224 | ] 225 | 226 | [[package]] 227 | name = "memchr" 228 | version = "2.4.0" 229 | source = "registry+https://github.com/rust-lang/crates.io-index" 230 | checksum = "b16bd47d9e329435e309c58469fe0791c2d0d1ba96ec0954152a5ae2b04387dc" 231 | 232 | [[package]] 233 | name = "memory_units" 234 | version = "0.4.0" 235 | source = "registry+https://github.com/rust-lang/crates.io-index" 236 | checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" 237 | 238 | [[package]] 239 | name = "near-contract-standards" 240 | version = "4.0.0-pre.1" 241 | source = "registry+https://github.com/rust-lang/crates.io-index" 242 | checksum = "2b8a3ebf34da13a00a03ebb5c7b789787080e517c7b1689cd831ac119ac8f529" 243 | dependencies = [ 244 | "near-sdk", 245 | ] 246 | 247 | [[package]] 248 | name = "near-primitives-core" 249 | version = "0.4.0" 250 | source = "registry+https://github.com/rust-lang/crates.io-index" 251 | checksum = "c2b3fb5acf3a494aed4e848446ef2d6ebb47dbe91c681105d4d1786c2ee63e52" 252 | dependencies = [ 253 | "base64", 254 | "borsh", 255 | "bs58", 256 | "derive_more", 257 | "hex", 258 | "lazy_static", 259 | "num-rational", 260 | "serde", 261 | "serde_json", 262 | "sha2", 263 | ] 264 | 265 | [[package]] 266 | name = "near-rpc-error-core" 267 | version = "0.1.0" 268 | source = "registry+https://github.com/rust-lang/crates.io-index" 269 | checksum = "ffa8dbf8437a28ac40fcb85859ab0d0b8385013935b000c7a51ae79631dd74d9" 270 | dependencies = [ 271 | "proc-macro2", 272 | "quote", 273 | "serde", 274 | "serde_json", 275 | "syn", 276 | ] 277 | 278 | [[package]] 279 | name = "near-rpc-error-macro" 280 | version = "0.1.0" 281 | source = "registry+https://github.com/rust-lang/crates.io-index" 282 | checksum = "0c6111d713e90c7c551dee937f4a06cb9ea2672243455a4454cc7566387ba2d9" 283 | dependencies = [ 284 | "near-rpc-error-core", 285 | "proc-macro2", 286 | "quote", 287 | "serde", 288 | "serde_json", 289 | "syn", 290 | ] 291 | 292 | [[package]] 293 | name = "near-runtime-utils" 294 | version = "4.0.0-pre.1" 295 | source = "registry+https://github.com/rust-lang/crates.io-index" 296 | checksum = "a48d80c4ca1d4cf99bc16490e1e3d49826c150dfc4410ac498918e45c7d98e07" 297 | dependencies = [ 298 | "lazy_static", 299 | "regex", 300 | ] 301 | 302 | [[package]] 303 | name = "near-sdk" 304 | version = "4.0.0-pre.1" 305 | source = "registry+https://github.com/rust-lang/crates.io-index" 306 | checksum = "ce0d4d45e3cb86eb0aa25cbfe95a6f339d4c14509bc26cb259bcfa1031fff174" 307 | dependencies = [ 308 | "base64", 309 | "borsh", 310 | "bs58", 311 | "near-primitives-core", 312 | "near-sdk-macros", 313 | "near-vm-logic", 314 | "serde", 315 | "serde_json", 316 | "wee_alloc", 317 | ] 318 | 319 | [[package]] 320 | name = "near-sdk-macros" 321 | version = "4.0.0-pre.1" 322 | source = "registry+https://github.com/rust-lang/crates.io-index" 323 | checksum = "111ec624bb89a182c8302fde73862b5d0d88b15a87e3822e05bfa2edc08309fb" 324 | dependencies = [ 325 | "Inflector", 326 | "proc-macro2", 327 | "quote", 328 | "syn", 329 | ] 330 | 331 | [[package]] 332 | name = "near-vm-errors" 333 | version = "4.0.0-pre.1" 334 | source = "registry+https://github.com/rust-lang/crates.io-index" 335 | checksum = "e281d8730ed8cb0e3e69fb689acee6b93cdb43824cd69a8ffd7e1bfcbd1177d7" 336 | dependencies = [ 337 | "borsh", 338 | "hex", 339 | "near-rpc-error-macro", 340 | "serde", 341 | ] 342 | 343 | [[package]] 344 | name = "near-vm-logic" 345 | version = "4.0.0-pre.1" 346 | source = "registry+https://github.com/rust-lang/crates.io-index" 347 | checksum = "e11cb28a2d07f37680efdaf860f4c9802828c44fc50c08009e7884de75d982c5" 348 | dependencies = [ 349 | "base64", 350 | "borsh", 351 | "bs58", 352 | "byteorder", 353 | "near-primitives-core", 354 | "near-runtime-utils", 355 | "near-vm-errors", 356 | "serde", 357 | "sha2", 358 | "sha3", 359 | ] 360 | 361 | [[package]] 362 | name = "num-bigint" 363 | version = "0.3.2" 364 | source = "registry+https://github.com/rust-lang/crates.io-index" 365 | checksum = "7d0a3d5e207573f948a9e5376662aa743a2ea13f7c50a554d7af443a73fbfeba" 366 | dependencies = [ 367 | "autocfg", 368 | "num-integer", 369 | "num-traits", 370 | ] 371 | 372 | [[package]] 373 | name = "num-integer" 374 | version = "0.1.44" 375 | source = "registry+https://github.com/rust-lang/crates.io-index" 376 | checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" 377 | dependencies = [ 378 | "autocfg", 379 | "num-traits", 380 | ] 381 | 382 | [[package]] 383 | name = "num-rational" 384 | version = "0.3.2" 385 | source = "registry+https://github.com/rust-lang/crates.io-index" 386 | checksum = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07" 387 | dependencies = [ 388 | "autocfg", 389 | "num-bigint", 390 | "num-integer", 391 | "num-traits", 392 | "serde", 393 | ] 394 | 395 | [[package]] 396 | name = "num-traits" 397 | version = "0.2.14" 398 | source = "registry+https://github.com/rust-lang/crates.io-index" 399 | checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" 400 | dependencies = [ 401 | "autocfg", 402 | ] 403 | 404 | [[package]] 405 | name = "opaque-debug" 406 | version = "0.3.0" 407 | source = "registry+https://github.com/rust-lang/crates.io-index" 408 | checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" 409 | 410 | [[package]] 411 | name = "proc-macro-crate" 412 | version = "0.1.5" 413 | source = "registry+https://github.com/rust-lang/crates.io-index" 414 | checksum = "1d6ea3c4595b96363c13943497db34af4460fb474a95c43f4446ad341b8c9785" 415 | dependencies = [ 416 | "toml", 417 | ] 418 | 419 | [[package]] 420 | name = "proc-macro2" 421 | version = "1.0.27" 422 | source = "registry+https://github.com/rust-lang/crates.io-index" 423 | checksum = "f0d8caf72986c1a598726adc988bb5984792ef84f5ee5aa50209145ee8077038" 424 | dependencies = [ 425 | "unicode-xid", 426 | ] 427 | 428 | [[package]] 429 | name = "quote" 430 | version = "1.0.9" 431 | source = "registry+https://github.com/rust-lang/crates.io-index" 432 | checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" 433 | dependencies = [ 434 | "proc-macro2", 435 | ] 436 | 437 | [[package]] 438 | name = "regex" 439 | version = "1.5.4" 440 | source = "registry+https://github.com/rust-lang/crates.io-index" 441 | checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" 442 | dependencies = [ 443 | "aho-corasick", 444 | "memchr", 445 | "regex-syntax", 446 | ] 447 | 448 | [[package]] 449 | name = "regex-syntax" 450 | version = "0.6.25" 451 | source = "registry+https://github.com/rust-lang/crates.io-index" 452 | checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" 453 | 454 | [[package]] 455 | name = "ryu" 456 | version = "1.0.5" 457 | source = "registry+https://github.com/rust-lang/crates.io-index" 458 | checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" 459 | 460 | [[package]] 461 | name = "serde" 462 | version = "1.0.118" 463 | source = "registry+https://github.com/rust-lang/crates.io-index" 464 | checksum = "06c64263859d87aa2eb554587e2d23183398d617427327cf2b3d0ed8c69e4800" 465 | dependencies = [ 466 | "serde_derive", 467 | ] 468 | 469 | [[package]] 470 | name = "serde_derive" 471 | version = "1.0.118" 472 | source = "registry+https://github.com/rust-lang/crates.io-index" 473 | checksum = "c84d3526699cd55261af4b941e4e725444df67aa4f9e6a3564f18030d12672df" 474 | dependencies = [ 475 | "proc-macro2", 476 | "quote", 477 | "syn", 478 | ] 479 | 480 | [[package]] 481 | name = "serde_json" 482 | version = "1.0.64" 483 | source = "registry+https://github.com/rust-lang/crates.io-index" 484 | checksum = "799e97dc9fdae36a5c8b8f2cae9ce2ee9fdce2058c57a93e6099d919fd982f79" 485 | dependencies = [ 486 | "indexmap", 487 | "itoa", 488 | "ryu", 489 | "serde", 490 | ] 491 | 492 | [[package]] 493 | name = "sha2" 494 | version = "0.9.5" 495 | source = "registry+https://github.com/rust-lang/crates.io-index" 496 | checksum = "b362ae5752fd2137731f9fa25fd4d9058af34666ca1966fb969119cc35719f12" 497 | dependencies = [ 498 | "block-buffer", 499 | "cfg-if 1.0.0", 500 | "cpufeatures", 501 | "digest", 502 | "opaque-debug", 503 | ] 504 | 505 | [[package]] 506 | name = "sha3" 507 | version = "0.9.1" 508 | source = "registry+https://github.com/rust-lang/crates.io-index" 509 | checksum = "f81199417d4e5de3f04b1e871023acea7389672c4135918f05aa9cbf2f2fa809" 510 | dependencies = [ 511 | "block-buffer", 512 | "digest", 513 | "keccak", 514 | "opaque-debug", 515 | ] 516 | 517 | [[package]] 518 | name = "syn" 519 | version = "1.0.57" 520 | source = "registry+https://github.com/rust-lang/crates.io-index" 521 | checksum = "4211ce9909eb971f111059df92c45640aad50a619cf55cd76476be803c4c68e6" 522 | dependencies = [ 523 | "proc-macro2", 524 | "quote", 525 | "unicode-xid", 526 | ] 527 | 528 | [[package]] 529 | name = "toml" 530 | version = "0.5.8" 531 | source = "registry+https://github.com/rust-lang/crates.io-index" 532 | checksum = "a31142970826733df8241ef35dc040ef98c679ab14d7c3e54d827099b3acecaa" 533 | dependencies = [ 534 | "serde", 535 | ] 536 | 537 | [[package]] 538 | name = "typenum" 539 | version = "1.13.0" 540 | source = "registry+https://github.com/rust-lang/crates.io-index" 541 | checksum = "879f6906492a7cd215bfa4cf595b600146ccfac0c79bcbd1f3000162af5e8b06" 542 | 543 | [[package]] 544 | name = "unicode-xid" 545 | version = "0.2.2" 546 | source = "registry+https://github.com/rust-lang/crates.io-index" 547 | checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" 548 | 549 | [[package]] 550 | name = "version_check" 551 | version = "0.9.3" 552 | source = "registry+https://github.com/rust-lang/crates.io-index" 553 | checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" 554 | 555 | [[package]] 556 | name = "wee_alloc" 557 | version = "0.4.5" 558 | source = "registry+https://github.com/rust-lang/crates.io-index" 559 | checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e" 560 | dependencies = [ 561 | "cfg-if 0.1.10", 562 | "libc", 563 | "memory_units", 564 | "winapi", 565 | ] 566 | 567 | [[package]] 568 | name = "winapi" 569 | version = "0.3.9" 570 | source = "registry+https://github.com/rust-lang/crates.io-index" 571 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 572 | dependencies = [ 573 | "winapi-i686-pc-windows-gnu", 574 | "winapi-x86_64-pc-windows-gnu", 575 | ] 576 | 577 | [[package]] 578 | name = "winapi-i686-pc-windows-gnu" 579 | version = "0.4.0" 580 | source = "registry+https://github.com/rust-lang/crates.io-index" 581 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 582 | 583 | [[package]] 584 | name = "winapi-x86_64-pc-windows-gnu" 585 | version = "0.4.0" 586 | source = "registry+https://github.com/rust-lang/crates.io-index" 587 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 588 | -------------------------------------------------------------------------------- /contract/src/send.rs: -------------------------------------------------------------------------------- 1 | use near_sdk::Balance; 2 | 3 | use crate::*; 4 | 5 | #[near_bindgen] 6 | impl LinkDropProxy { 7 | /* 8 | user has created a keypair and passes in the public key and attaches some deposit. 9 | this will store the account data and allow that key to call claim and create_account_and_claim 10 | on this contract. 11 | 12 | The balance is the amount of $NEAR the sender wants the linkdrop to contain. 13 | */ 14 | #[payable] 15 | pub fn send(&mut self, 16 | public_key: PublicKey, 17 | balance: U128, 18 | ft_data: Option, 19 | nft_data: Option, 20 | fc_data: Option, 21 | ) { 22 | let attached_deposit = env::attached_deposit(); 23 | 24 | assert!( 25 | balance.0 >= NEW_ACCOUNT_BASE, 26 | "cannot have a desired account balance less than the absolute minimum for creating an account" 27 | ); 28 | 29 | // Calculate the storage usage for linkdrop with the maximum U128 size 30 | let initial_storage = env::storage_usage(); 31 | 32 | // Keep track of the cb info 33 | let mut cb_id = None; 34 | 35 | let pk = public_key.clone(); 36 | assert!(self.data_for_pk.insert( 37 | &pk, 38 | &AccountData{ 39 | funder_id: env::predecessor_account_id(), 40 | balance: balance, 41 | storage_used: U128(340282366920938463463374607431768211455), 42 | cb_id: None, 43 | cb_data_sent: false 44 | }, 45 | ).is_none(), 46 | "Account for PublicKey exists" 47 | ); 48 | 49 | // Add the public key to the set of keys mapped to the funder 50 | self.internal_add_key_to_funder(&env::predecessor_account_id(), &public_key); 51 | 52 | // Check if FT data was passed in and insert into map 53 | if ft_data.is_some() { 54 | // Ensure that if FT data is specified, NFT and FC are not 55 | assert!(nft_data.is_none() && fc_data.is_none(), "Cannot have multi-typed linkdrop"); 56 | 57 | // Keep track of the callback type 58 | cb_id = Some(self.nonce); 59 | 60 | // Insert the FT data or the unique callback ID associated with the linkdrop 61 | self.ft.insert( 62 | &self.nonce, 63 | &FTData { 64 | ft_contract: ft_data.clone().unwrap().ft_contract, 65 | ft_sender: ft_data.clone().unwrap().ft_sender, 66 | ft_balance: ft_data.clone().unwrap().ft_balance, 67 | // Maximum possible storage 68 | ft_storage: Some(U128(340282366920938463463374607431768211455)), 69 | } 70 | ); 71 | 72 | // Increment nonce 73 | self.nonce += 1; 74 | } 75 | 76 | // Check if NFT data was passed in and insert into map 77 | if nft_data.is_some() { 78 | // Ensure that if NFT data is specified, FT and FC are not 79 | assert!(ft_data.is_none() && fc_data.is_none(), "Cannot have multi-typed linkdrop"); 80 | 81 | // Keep track of the callback type 82 | cb_id = Some(self.nonce); 83 | 84 | // Insert passed in data into map 85 | self.nft.insert( 86 | &self.nonce, 87 | &nft_data.clone().unwrap() 88 | ); 89 | 90 | // Increment nonce 91 | self.nonce += 1; 92 | } 93 | 94 | // Check if Function call data was passed in and insert into map 95 | if fc_data.is_some() { 96 | // Ensure that if FC data is specified, NFT and FT are not 97 | assert!(nft_data.is_none() && ft_data.is_none(), "Cannot have multi-typed linkdrop"); 98 | // Keep track of the callback type 99 | cb_id = Some(self.nonce); 100 | 101 | // Insert passed in data into map 102 | self.fc.insert( 103 | &self.nonce, 104 | &fc_data.clone().unwrap() 105 | ); 106 | 107 | // Increment nonce 108 | self.nonce += 1; 109 | } 110 | 111 | let final_storage = env::storage_usage(); 112 | let required_storage = Balance::from(final_storage - initial_storage) * env::storage_byte_cost(); 113 | 114 | /* 115 | Insert key back into map with proper used storage 116 | */ 117 | self.data_for_pk.insert( 118 | &pk, 119 | &AccountData{ 120 | funder_id: env::predecessor_account_id(), 121 | balance: balance, 122 | storage_used: U128(required_storage), 123 | cb_id: cb_id, 124 | /* 125 | No need to complete step 2 (sending NFT / FTs) if the linkdrop is either regular or function call 126 | so set callback data being sent to true in that case 127 | */ 128 | cb_data_sent: if ft_data.is_some() || nft_data.is_some() { false } else { true } 129 | }, 130 | ); 131 | 132 | /* 133 | ensure the user attached enough to cover: 134 | - storage on the contract 135 | - creating access key 136 | - Linkdrop data 137 | - access key allowance 138 | - and a balance for the account (which must be greater than new account base) 139 | - Desired function call deposit if specified 140 | */ 141 | env::log_str(&format!( 142 | "Attached Deposit: {}, Required: {}, Access Key Storage: {}, Access Key Allowance: {}, Linkdrop Balance: {}, required storage: {}, Desired FC Attached Deposit If Applicable: {}", 143 | yocto_to_near(attached_deposit), 144 | yocto_to_near(ACCESS_KEY_STORAGE + required_storage + ACCESS_KEY_ALLOWANCE + balance.0 + if fc_data.is_some() {fc_data.clone().unwrap().deposit.0} else {0}), 145 | yocto_to_near(ACCESS_KEY_STORAGE), 146 | yocto_to_near(ACCESS_KEY_ALLOWANCE), 147 | yocto_to_near(balance.0), 148 | yocto_to_near(required_storage), 149 | if fc_data.is_some() {yocto_to_near(fc_data.clone().unwrap().deposit.0)} else {0.0} 150 | ) 151 | ); 152 | assert!( 153 | attached_deposit >= ACCESS_KEY_STORAGE + required_storage + ACCESS_KEY_ALLOWANCE + balance.0 + if fc_data.is_some() {fc_data.clone().unwrap().deposit.0} else {0}, 154 | "Deposit must be large enough to cover desired balance, access key allowance, and contract storage, and function call deposit if applicable." 155 | ); 156 | 157 | /* 158 | add the public key as an access key to the contract 159 | which can only call claim and create_account_and_claim on this contract 160 | */ 161 | Promise::new(env::current_account_id()).add_access_key( 162 | pk.clone(), 163 | ACCESS_KEY_ALLOWANCE, 164 | env::current_account_id(), 165 | ACCESS_KEY_METHOD_NAMES.to_string(), 166 | ); 167 | 168 | // Check if user will attach fungible tokens 169 | if ft_data.is_some() { 170 | /* 171 | Get the storage required by the FT contract and ensure the user has attached enough 172 | deposit to cover the storage and perform refunds if they overpayed. 173 | */ 174 | ext_ft_contract::ext(ft_data.unwrap().ft_contract) 175 | // Call storage balance bounds with exactly this amount of GAS. No unspent GAS will be added on top. 176 | .with_static_gas(GAS_FOR_STORAGE_BALANCE_BOUNDS) 177 | .with_unused_gas_weight(0) 178 | .storage_balance_bounds() 179 | .then( 180 | Self::ext(env::current_account_id()) 181 | // Resolve the promise with the attached deposit and the min GAS. All unspent GAS will be added to this call. 182 | .with_static_gas(MIN_GAS_FOR_RESOLVE_STORAGE_CHECK) 183 | .with_attached_deposit(attached_deposit) 184 | .resolve_storage_check( 185 | vec![pk], 186 | env::predecessor_account_id(), 187 | balance, 188 | U128(required_storage), 189 | vec![cb_id.expect("callback ID expected")], 190 | ) 191 | ); 192 | } else if attached_deposit > balance.0 + ACCESS_KEY_ALLOWANCE + required_storage + ACCESS_KEY_STORAGE + if fc_data.is_some() {fc_data.clone().unwrap().deposit.0} else {0} { 193 | env::log_str(&format!("Refunding User for: {}", yocto_to_near(attached_deposit - balance.0 - ACCESS_KEY_ALLOWANCE - required_storage - ACCESS_KEY_STORAGE - if fc_data.is_some() {fc_data.clone().unwrap().deposit.0} else {0}))); 194 | // If the user overpaid for the desired linkdrop balance, refund them. 195 | Promise::new(env::predecessor_account_id()).transfer(attached_deposit - balance.0 - ACCESS_KEY_ALLOWANCE - required_storage - ACCESS_KEY_STORAGE - if fc_data.is_some() {fc_data.unwrap().deposit.0} else {0}); 196 | } 197 | } 198 | 199 | /* 200 | user has created a bunch of keypairs and passed in the public keys and attached some deposit. 201 | this will store the account data and allow that keys to call claim and create_account_and_claim 202 | on this contract. 203 | 204 | The balance is the amount of $NEAR the sender wants each linkdrop to contain. 205 | */ 206 | #[payable] 207 | pub fn send_multiple( 208 | &mut self, 209 | public_keys: Vec, 210 | balance: U128, 211 | ft_data: Option, 212 | nft_data: Option>, 213 | fc_data: Option> 214 | ) { 215 | let attached_deposit = env::attached_deposit(); 216 | let len = public_keys.len() as u128; 217 | 218 | if let Some(data) = nft_data.clone() { 219 | assert!( 220 | data.len() as u128 == len, 221 | "Must specify NFT Data for each key" 222 | ) 223 | } 224 | 225 | 226 | assert!( 227 | balance.0 >= NEW_ACCOUNT_BASE, 228 | "cannot have a desired account balance less than the absolute minimum for creating an account" 229 | ); 230 | 231 | let current_account_id = env::current_account_id(); 232 | let promise = env::promise_batch_create(¤t_account_id); 233 | let mut required_storage = 0; 234 | let mut cb_ids = vec![]; 235 | // Keep track of the total attached deposit across all function calls 236 | let mut total_attached_deposit = 0; 237 | 238 | let mut index = 0; 239 | // Loop through each public key and insert into the map and create the key 240 | for pk in public_keys.clone() { 241 | // Calculate the storage usage for linkdrop with the maximum U128 size 242 | let initial_storage = env::storage_usage(); 243 | 244 | // Keep track of the cb info 245 | let mut cb_id = None; 246 | 247 | assert!(self.data_for_pk.insert( 248 | &pk, 249 | &AccountData{ 250 | funder_id: env::predecessor_account_id(), 251 | balance: balance, 252 | storage_used: U128(340282366920938463463374607431768211455), 253 | cb_id: None, 254 | cb_data_sent: false 255 | }, 256 | ).is_none(), 257 | "Account for PublicKey exists" 258 | ); 259 | 260 | // Add the public key to the set of keys mapped to the funder 261 | self.internal_add_key_to_funder(&env::predecessor_account_id(), &pk); 262 | 263 | // Check if FT data was passed in and insert into map 264 | if ft_data.is_some() { 265 | // Ensure that if FT data is specified, NFT and FC are not 266 | assert!(nft_data.clone().is_none() && fc_data.clone().is_none(), "Cannot have multi-typed linkdrop"); 267 | 268 | // Keep track of the callback type 269 | cb_ids.push(self.nonce); 270 | cb_id = Some(self.nonce); 271 | 272 | // Insert the FT data or the unique callback ID associated with the linkdrop 273 | self.ft.insert( 274 | &self.nonce, 275 | &FTData { 276 | ft_contract: ft_data.clone().unwrap().ft_contract, 277 | ft_sender: ft_data.clone().unwrap().ft_sender, 278 | ft_balance: ft_data.clone().unwrap().ft_balance, 279 | // Maximum possible storage 280 | ft_storage: Some(U128(340282366920938463463374607431768211455)), 281 | } 282 | ); 283 | 284 | // Increment nonce 285 | self.nonce += 1; 286 | } 287 | 288 | // Check if NFT data was passed in and insert into map 289 | if nft_data.is_some() { 290 | // Ensure that if NFT data is specified, FT and FC are not 291 | assert!(ft_data.is_none() && fc_data.is_none(), "Cannot have multi-typed linkdrop"); 292 | 293 | // Keep track of the callback type 294 | cb_ids.push(self.nonce); 295 | cb_id = Some(self.nonce); 296 | 297 | // Insert passed in data into map 298 | self.nft.insert( 299 | &self.nonce, 300 | &nft_data.clone().unwrap()[index] 301 | ); 302 | 303 | // Increment nonce 304 | self.nonce += 1; 305 | } 306 | 307 | // Check if Function call data was passed in and insert into map 308 | if fc_data.is_some() { 309 | // Ensure that if FC data is specified, NFT and FT are not 310 | assert!(nft_data.is_none() && ft_data.is_none(), "Cannot have multi-typed linkdrop"); 311 | 312 | // Keep track of the callback type 313 | cb_ids.push(self.nonce); 314 | cb_id = Some(self.nonce); 315 | total_attached_deposit = total_attached_deposit + fc_data.clone().unwrap()[index].deposit.0; 316 | 317 | // Insert passed in data into map 318 | self.fc.insert( 319 | &self.nonce, 320 | &fc_data.clone().unwrap()[index] 321 | ); 322 | 323 | // Increment nonce 324 | self.nonce += 1; 325 | } 326 | let final_storage = env::storage_usage(); 327 | required_storage = Balance::from(final_storage - initial_storage) * env::storage_byte_cost(); 328 | 329 | /* 330 | Insert key back into map with proper used storage 331 | */ 332 | self.data_for_pk.insert( 333 | &pk, 334 | &AccountData{ 335 | funder_id: env::predecessor_account_id(), 336 | balance: balance, 337 | storage_used: U128(required_storage), 338 | cb_id: cb_id, 339 | /* 340 | No need to complete step 2 (sending NFT / FTs) if the linkdrop is either regular or function call 341 | so set callback data being sent to true in that case 342 | */ 343 | cb_data_sent: if ft_data.is_some() || nft_data.is_some() { false } else { true } 344 | }, 345 | ); 346 | 347 | 348 | /* 349 | ensure the user attached enough to cover: 350 | - storage on the contract 351 | - creating access key 352 | - Linkdrop data 353 | - access key allowance 354 | - and a balance for the account (which must be greater than new account base) 355 | */ 356 | assert!( 357 | attached_deposit >= ACCESS_KEY_STORAGE + required_storage + ACCESS_KEY_ALLOWANCE + balance.0 + if fc_data.is_some() {fc_data.clone().unwrap()[index].deposit.0} else {0}, 358 | "Deposit must be large enough to cover desired balance, access key allowance, and contract storage" 359 | ); 360 | 361 | // Must assert in the loop so no access keys are made? 362 | env::promise_batch_action_add_key_with_function_call( 363 | promise, 364 | &pk, 365 | 0, 366 | ACCESS_KEY_ALLOWANCE, 367 | ¤t_account_id, 368 | ACCESS_KEY_METHOD_NAMES 369 | ); 370 | 371 | index = index + 1; 372 | } 373 | 374 | /* 375 | ensure the user attached enough to cover: 376 | - storage allowance on the contract for access key and storing account data and pk 377 | - access key allowance 378 | - and a balance for the account (which must be greater than new account base) 379 | 380 | this must be true for every public key passed in. 381 | */ 382 | env::log_str(&format!( 383 | "Attached Deposit: {}, Required: {}, Access Key Storage: {}, Access Key Allowance: {}, Linkdrop Balance: {}, required storage: {}, total function call deposits (if applicable): {}, length: {}", 384 | yocto_to_near(attached_deposit), 385 | yocto_to_near((ACCESS_KEY_STORAGE + required_storage + ACCESS_KEY_ALLOWANCE + balance.0) * len + total_attached_deposit), 386 | yocto_to_near(ACCESS_KEY_STORAGE), 387 | yocto_to_near(ACCESS_KEY_ALLOWANCE), 388 | yocto_to_near(balance.0), 389 | yocto_to_near(required_storage), 390 | yocto_to_near(total_attached_deposit), 391 | len) 392 | ); 393 | assert!( 394 | attached_deposit >= (ACCESS_KEY_STORAGE + required_storage + ACCESS_KEY_ALLOWANCE + balance.0 ) * len + total_attached_deposit, 395 | "Deposit must be large enough to cover desired balance, access key allowance, contract storage, and function call deposit (if applicable) for all keys" 396 | ); 397 | 398 | env::promise_return(promise); 399 | 400 | // Check if user will attach fungible tokens 401 | if ft_data.is_some() { 402 | 403 | /* 404 | Get the storage required by the FT contract and ensure the user has attached enough 405 | deposit to cover the storage and perform refunds if they overpayed. 406 | */ 407 | 408 | ext_ft_contract::ext(ft_data.unwrap().ft_contract) 409 | // Call storage balance bounds with exactly this amount of GAS. No unspent GAS will be added on top. 410 | .with_static_gas(GAS_FOR_STORAGE_BALANCE_BOUNDS) 411 | .with_unused_gas_weight(0) 412 | .storage_balance_bounds() 413 | .then( 414 | Self::ext(env::current_account_id()) 415 | // Resolve the promise with the attached deposit and the min GAS. All unspent GAS will be added to this call. 416 | .with_static_gas(MIN_GAS_FOR_RESOLVE_STORAGE_CHECK) 417 | .with_attached_deposit(attached_deposit) 418 | .resolve_storage_check( 419 | public_keys, 420 | env::predecessor_account_id(), 421 | balance, 422 | U128(required_storage), 423 | cb_ids, 424 | ) 425 | ); 426 | } else if attached_deposit > (ACCESS_KEY_STORAGE + required_storage + ACCESS_KEY_ALLOWANCE + balance.0) * len + total_attached_deposit { 427 | env::log_str(&format!("Refunding User for: {}", yocto_to_near(attached_deposit - ((ACCESS_KEY_STORAGE + required_storage + ACCESS_KEY_ALLOWANCE + balance.0) * len + total_attached_deposit)))); 428 | // If the user overpaid for the desired linkdrop balances, refund them. 429 | Promise::new(env::predecessor_account_id()).transfer(attached_deposit - ((ACCESS_KEY_STORAGE + required_storage + ACCESS_KEY_ALLOWANCE + balance.0) * len + total_attached_deposit)); 430 | } 431 | } 432 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Logo 3 |
4 |

5 | 6 |
7 |

8 | NEAR Linkdrop Proxy 9 |

10 | The hub for creating linkdrops containing $NEAR and one of: NFTs, and FTs or an arbitrary function called upon claim 11 |
12 | 13 |
14 |
15 | 16 | [![made by BenKurrek](https://img.shields.io/badge/made%20by-BenKurrek-ff1414.svg?style=flat-square)](https://github.com/BenKurrek) 17 | [![made by mattlockyer](https://img.shields.io/badge/made%20by-MattLockyer-ff1414.svg?style=flat-square)](https://github.com/mattlockyer) 18 | 19 | 20 |
21 | 22 |
23 | Table of Contents 24 | 25 | - [About](#about) 26 | - [How it Works](#how-it-works) 27 | - [NFTs](#nft-linkdrops) 28 | - [Fungible Tokens](#fungible-token-linkdrops) 29 | - [Function Calls](#function-calls) 30 | - [Getting Started](#getting-started) 31 | - [Prerequisites](#prerequisites) 32 | - [Quickstart](#quickstart) 33 | - [Contributing](#contributing) 34 | - [Acknowledgements](#acknowledgements) 35 | 36 |
37 | 38 | --- 39 | 40 | # About 41 | 42 | 43 | 44 | 71 | 72 |
45 | 46 | The NEAR linkdrop proxy contract was initially created as a way to handle the hardcoded minimum 1 $NEAR fee for creating linkdrops using the [regular linkdrop contract](https://github.com/near/near-linkdrop/blob/f24f2608e1558db773f2408a28849d330abb3881/src/lib.rs#L18). If users wanted to create linkdrops, they needed to attach a **minimum** of 1 $NEAR. This made it costly and unscalable for projects that wanted to mass create linkdrops for an easy onboarding experience to NEAR. 47 | 48 | The proxy contract has a highly optimized fee structure that can be broken down below. Every linkdrop's fees are made up of: 49 | - Actual linkdrop balance sent to the claimed account (**minimum 0.00284 $NEAR**). 50 | - Access key allowance (**0.02 $NEAR**). 51 | - Storage for creating access key (**0.001 $NEAR**). 52 | - Storage cost for storing information on the proxy contract (**dynamically calculated** but **~0.0015 $NEAR** for a basic linkdrop). 53 | 54 | This means that at an absolute **minimum**, you can create a linkdrop for **~0.02534 $NEAR** making it **97.466% cheaper** than the alternate solution. 55 | 56 | In addition, some of this upfront fee **will be refunded** to the funder once the account is created, making it even cheaper. The access key allowance and all storage will be refunded (minus the burnt GAS) once the linkdrop is claimed which makes the true cost of creating a linkdrop roughly `(0.02534 - (0.02 + 0.001 + 0.0015 - 0.01) = 0.01384 $NEAR` which is **~98.616% cheaper**. 57 | 58 | > **NOTE:** any excess $NEAR attached to the call when creating the linkdrop will be automatically refunded to the funder 59 | 60 | Key features of the **Linkdrop Proxy Contract**: 61 | 62 | - **Batch creation** of linkdrops within the contract. 63 | - Ability to specify a **highly customizable function** to be called when the linkdrop is claimed. 64 | - Ability to pre-load the linkdrop with an **NFT** from **any** NEP-171 compatible smart contract. 65 | - Ability to pre-load the linkdrop with **fungible tokens** from **any** NEP-141 compatible smart contract. 66 | - Extremely **low required deposits** when compared with traditional approaches 67 | - **Customizable balance** that the linkdrop will contain. 68 | 69 | 70 |
73 | 74 | ## Built With 75 | 76 | - [near-sdk-rs](https://github.com/near/near-sdk-rs) 77 | - [near-api-js](https://github.com/near/near-api-js) 78 | 79 | # How it Works 80 | 81 | Once the contract is deployed, you can either batch create linkdrops, or you can create them one-by-one. With each basic linkdrop, you have the option to either pre-load them with an NFT, or a fungible token. 82 | 83 | For some background as to how the linkdrop proxy contract works on NEAR: 84 | 85 | *The funder that has an account and some $NEAR:* 86 | - creates a keypair locally `(pubKey1, privKey1)`. The blockchain doesn't know of this key's existence yet since it's all local for now. 87 | - calls `send` on the proxy contract and passes in the `pubKey1` as an argument as well as the desired `balance` for the linkdrop. 88 | - The contract will map the `pubKey1` to the desired `balance` for the linkdrop. 89 | - The contract will then add the `pubKey1` as a **function call access key** with the ability to call `claim` and `create_account_and_claim`. This means that anyone with the `privKey1` that was created locally, can claim this linkdrop. 90 | - Funder will then create a link to send to someone that contains this `privKey1`. The link follows the following format: 91 | ``` 92 | wallet.testnet.near.org/linkdrop/{fundingContractAccountId}/{linkdropKeyPairSecretKey}?redirectUrl={redirectUrl} 93 | ``` 94 | * `fundingContractAccountId`: The contract accountId that was used to send the funds. 95 | * `linkdropKeyPairSecretKey`: The corresponding secret key to the public key sent to the contract. 96 | * `redirectUrl`: The url that wallet will redirect to after funds are successfully claimed to an existing account. The URL is sent the accountId used to claim the funds as a query param. 97 | 98 | *The receiver of the link that is claiming the linkdrop:* 99 | - Receives the link which includes `privKey1` and sends them to the NEAR wallet. 100 | - Wallet creates a new keypair `(pubKey2, privKey2)` locally. The blockchain doesn't know of this key's existence yet since it's all local for now. 101 | - Receiver will then choose an account ID such as `new_account.near`. 102 | - Wallet will then use the `privKey1` which has access to call `claim` and `create_account_and_claim` in order to call `create_account_and_claim` on the proxy contract. 103 | - It will pass in `pubKey2` which will be used to create a full access key for the new account. 104 | - The proxy contract will create the new account and transfer the funds to it alongside any NFT or fungible tokens pre-loaded. 105 | 106 | To view information account data information for a given key, you can call the following view function: 107 | 108 | ```bash 109 | near view YOUR_LINKDROP_PROXY_CONTRACT get_key_information '{"key": "ed25519:7jszQk7sfbdQy8NHM1EfJi9r3ncyvKa4ZoKU7uk9PbqR"}' 110 | ``` 111 | 112 | Example response: 113 |

114 | 115 | ```bash 116 | [ 117 | { 118 | funder_id: 'benjiman.testnet', 119 | balance: '2840000000000000000000', 120 | storage_used: '1320000000000000000000', 121 | cb_id: null, 122 | cb_data_sent: true 123 | }, 124 | null, 125 | null, 126 | null 127 | ] 128 | ``` 129 |

130 | 131 | This will return the Account Data followed by Fungible Token Data, NFT Data, and then Function Call Data. If any of the above don't exist, null is returned in its place. 132 | 133 | Below are some flowcharts for creating single linkdrops and batch creating multiple linkdrops. 134 | 135 |

136 | Logo 137 |
138 | Logo 139 |

140 | 141 | 142 | ## NFT Linkdrops 143 | 144 | With the proxy contract, users can pre-load a linkdrop with **only one** NFT due to GAS constraints. In order to pre-load the NFT, you must: 145 | - create a linkdrop either through `send` or `send_multiple` and specify the NFTData for the NFT that will be pre-loaded onto the linkdrop. The NFT Data struct can be seen below. 146 | 147 | ```rust 148 | pub struct NFTData { 149 | pub nft_sender: String, 150 | pub nft_contract: String, 151 | pub nft_token_id: String, 152 | } 153 | ``` 154 | 155 | An example of creating an NFT linkdrop can be seen: 156 | 157 | ```bash 158 | near call linkdrop-proxy.testnet send '{"public_key": "ed25519:2EVN4CVLu5oH18YFoxGyeVkg1c7MaDb9aDrhkaWPqjd7", "balance": "2840000000000000000000", "nft_data": {"nft_sender": "benjiman.testnet", "nft_contract": "example-nft.testnet", "nft_token_id": "token1"}}' --accountId "benjiman.testnet" --amount 1 159 | ``` 160 | 161 | - Once the regular linkdrop has been created with the specified NFT Data, execute the `nft_transfer_call` funtion on the NFT contract and you *must* pass in `pubKey1` (the public key of the keypair created locally and passed into the `send` function) into the `msg` parameter. If the linkdrop is claimed before activation, it will act as a regular linkdrop with no NFT. 162 | 163 | ```bash 164 | near call example-nft.testnet nft_transfer_call '{"token_id": "token1", "receiver_id": "linkdrop-proxy.testnet", "msg": "ed25519:4iwBf6eAXZ4bcN6TWPikSqu3UJ2HUwF8wNNkGZrgDYqE"}' --accountId "benjiman.testnet" --depositYocto 1 165 | ``` 166 | 167 | > **NOTE:** you must send the NFT after the linkdrop has been created. You cannot send an NFT with a public key that isn't on the contract yet. The NFT must match exactly what was specified in the NFT data when creating the linkdrop. 168 | 169 |

170 | Logo 171 |

172 | 173 | Once the NFT is sent to the contract, it will be registered and you can view the current information about any key using the `get_key_information` function. Upon claiming, the NFT will be transferred from the contract to the newly created account (or existing account) along with the balance of the linkdrop. If any part of the linkdrop claiming process is unsuccessful, **both** the NFT and the $NEAR will be refunded to the funder and token sender respectively. 174 | 175 | > **NOTE:** If the NFT fails to transfer from the contract back to the token sender due to a refund for any reason, the NFT will remain on the proxy contract. 176 | 177 | If the linkdrop is successfully claimed, the funder will be refunded for everything **except** the burnt GAS and linkdrop balance. This results in the actual linkdrop cost being extremely low (burnt GAS + initial balance). 178 | 179 |

180 | Logo 181 |

182 | 183 | ## Fungible Token Linkdrops 184 | 185 | With the proxy contract, users can pre-load a linkdrop with **only one** type of fungible token due to GAS constraints. The number of fungible tokens, however, is not limited. You could load 1 TEAM token, or a million TEAM tokens. You cannot, however, load 10 TEAM tokens and 50 MIKE tokens at the same time. 186 | 187 | Due to the nature of how fungible token contracts handle storage, the user is responsible for attaching enough $NEAR to cover the registration fee. As mentioned in the [About](#about) section, this amount is dynamically calculated before the linkdrop is created in the `send` or `send_multiple` functions. The process for creating fungible token linkdrops is very similar to the NFT linkdrops: 188 | 189 | - create a linkdrop either through `send` or `send_multiple` and specify the FTData for the Fungible Tokens that will be pre-loaded onto the linkdrop. The FT Data struct can be seen below. 190 | 191 | ```rust 192 | pub struct FTData { 193 | pub ft_contract: String, 194 | pub ft_sender: String, 195 | pub ft_balance: U128, // String 196 | pub ft_storage: Option, // String 197 | } 198 | ``` 199 | 200 | An example of creating an FT linkdrop can be seen: 201 | 202 | ```bash 203 | near call linkdrop-proxy.testnet send '{"public_key": "ed25519:2EVN4CVLu5oH18YFoxGyeVkg1c7MaDb9aDrhkaWPqjd7", "balance": "2840000000000000000000", "ft_data": {"ft_sender": "benjiman.testnet", "ft_contract": "ft.benjiman.testnet", "ft_balance": "25"}}' --accountId "benjiman.testnet" --amount 1 204 | ``` 205 | 206 | Once the regular linkdrop is created with the fungible token data, you can the send the fungible tokens to activate the linkdrop. If the linkdrop is claimed before activation, it will act as a regular linkdrop with no FTs. 207 | 208 |

209 | Logo 210 |

211 | 212 | Once the regular linkdrop is created with the fungible token data, you can the send the fungible tokens to activate the linkdrop. If the linkdrop is claimed before activation, it will act as a regular linkdrop with no FTs. 213 | 214 | - execute the `ft_transfer_call` function on the FT contract and you *must* pass in `pubKey1` (the public key of the keypair created locally and passed into the `send` function) into the `msg` parameter. An example of this can be: 215 | 216 | ```bash 217 | near call FT_CONTRACT.testnet ft_transfer_call '{"receiver_id": "linkdrop-proxy.testnet", "amount": "25", "msg": "ed25519:4iwBf6eAXZ4bcN6TWPikSqu3UJ2HUwF8wNNkGZrgDYqE"}' --accountId "benjiman.testnet" --depositYocto 1 218 | ``` 219 | 220 | > **NOTE:** you must send the FT after the linkdrop has been created. You cannot send FTs with a public key that isn't on the contract yet. You are also responsible for registering the proxy contract for the given fungible token contract if it isn't registered already. 221 | 222 | Once the fungible tokens are sent to the contract, they will be registered and you can view the current information about any key using the `get_key_information` function. Upon claiming, the proxy contract will register the newly created account (or existing account) on the fungible token contract using the storage you depositted in the `send` function. After this is complete, the fungible tokens will be transferred from the contract to the claimed account along with the balance of the linkdrop. If any part of the linkdrop claiming process is unsuccessful, **both** the fungible tokens and the $NEAR will be refunded to the funder and token sender respectively. 223 | 224 | > **NOTE:** If the FT fails to transfer from the contract back to the token sender due to a refund for any reason, the fungible tokens will remain on the proxy contract. 225 | 226 | If the linkdrop is successfully claimed, the funder will be refunded for everything **except** the burnt GAS, linkdrop balance, and fungible token storage. 227 | 228 |

229 | Logo 230 |
231 |

232 | 233 | ## Function Calls 234 | 235 | With the proxy contract, users can specify a function that will be called when the linkdrop is claimed. This function call is highly customizable including: 236 | - Any method on any contract 237 | - Any deposit to attach to the call 238 | - Whether or not the refund that normally goes to the funder should be sent along with the deposit 239 | - Specifying a specific field for the claiming account to be called with. 240 | 241 | Let's look at an example to see the power of the proxy contract. If a user wants to be able to lazy mint an NFT to the newly created account (that is unknown at the time of creating the linkdrop) but the mint function takes a parameter `receiver_id` and a deposit of 1 $NEAR, you could specify these parameters. The struct that must be passed in when creating a function call linkdrop is below. 242 | 243 | ```rust 244 | pub struct FCData { 245 | // Contract that will be called 246 | pub receiver: String, 247 | // Method to call on receiver contract 248 | pub method: String, 249 | // Arguments to pass in (stringified JSON) 250 | pub args: String, 251 | // Amount of yoctoNEAR to attach along with the call 252 | pub deposit: U128, 253 | // Should the refund that normally goes to the funder be attached alongside the deposit? 254 | pub refund_to_deposit: Option, 255 | // Specifies what field the claiming account should go in when calling the function 256 | pub claimed_account_field: Option, 257 | } 258 | ``` 259 | 260 | If there was a different NFT contract where the parameter was `nft_contract_id` instead, that is also possible. You can specify the exact field that the claiming account ID should be passed into. An example flow of creating a function call linkdrop is below. 261 | 262 | - create a linkdrop either through `send` or `send_multiple` and specify the FC (function call) data for the function that will be called upon claim 263 | 264 | ```bash 265 | near call linkdrop-proxy.testnet send '{"public_key": "ed25519:2EVN4CVLu5oH18YFoxGyeVkg1c7MaDb9aDrhkaWPqjd7", "balance": "2840000000000000000000", "fc_data": {"receiver": "example-nft.testnet", "method": "nft_mint", "args": "{\"token_id\":\"ed25519:Db3ALuBMU2ruMNroZfwFC5ZGMXK3bRX12UjRAbH19LZL\",\"token_metadata\":{\"title\":\"My Linkdrop Called This Function!\",\"description\":\"Linkdrop NFT that was lazy minted when the linkdrop was claimed\",\"media\":\"https://bafybeicek3skoaae4p5chsutjzytls5dmnj5fbz6iqsd2uej334sy46oge.ipfs.nftstorage.link/\",\"media_hash\":null,\"copies\":10000,\"issued_at\":null,\"expires_at\":null,\"starts_at\":null,\"updated_at\":null,\"extra\":null,\"reference\":null,\"reference_hash\":null}}", "deposit": "1000000000000000000000000", "refund_to_deposit": true, "claimed_account_field": "receiver_id" }}' --accountId "benjiman.testnet" --amount 1 266 | ``` 267 | 268 | This will create a linkdrop for `0.00284 $NEAR` and specify that once the linkdrop is claimed, the method `nft_mint` should be called on the contract `example-nft.testnet` with a set of arguments that are stringified JSON. In addition, an **extra field called receiver_id** should be **added to the args** and the claiming account ID will be set for that field in the arguments. 269 | 270 | > **NOTE:** you must attach enough $NEAR to cover the attached deposit. If the linkdrop claim fails, your $NEAR will be refunded and the function call will NOT execute. 271 | 272 |

273 | Logo 274 |

275 | 276 | # Getting Started 277 | 278 | ## Prerequisites 279 | 280 | In order to successfully use this contract, you should have the following installed on your machine: 281 | 282 | 283 | - [NEAR account](https://docs.near.org/concepts/basics/account) 284 | - [rust toolchain](https://docs.near.org/develop/prerequisites) 285 | - [NEAR CLI](https://docs.near.org/tools/near-cli#setup) 286 | 287 | If you want to run the deploy scripts, you'll need: 288 | - [Node JS](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 289 | 290 | ## Quickstart 291 | 292 | The project comes with several useful scripts in order to test and view functionalities for creating linkdrops. Each script can be set to either batch create linkdrops or create them one by one: 293 | 294 | - [simple.js](deploy/simple.js) creating linkdrops preloaded with just $NEAR 295 | - [nft.js](deploy/nft.js) creating linkdrops preloaded with $NEAR and an NFT 296 | - [ft.js](deploy/ft.js) creating linkdrops preloaded with $NEAR and fungible tokens. 297 | - [function-call.js](deploy/funtion-call.js) creating linkdrops preloaded with $NEAR and fungible tokens. 298 | 299 | In addition, there is a test script that will create a function call recursive linkdrop that keeps calling the contract to create a new linkdrop once the old one is claimed. To test it out, visit the [recursive-fc.js](deploy/recursive-fc.js) script. 300 | 301 | The first step is to compile the contract to WebAssembly by running: 302 | 303 | ``` 304 | yarn build-contract 305 | ``` 306 | This will create the directory `out/main.wasm` where you can then deploy the contract using: 307 | 308 | ``` 309 | near deploy --wasmFile out/main.wasm --accountId YOUR_CONTRACT_ID.testnet 310 | ``` 311 | 312 | > **NOTE:** you must replace `YOUR_CONTRACT_ID.testnet` with the actual NEAR account ID you'll be using. 313 | 314 | 315 | Once deployed, you need to initialize the contract with the external linkdrop contract you want to interact with. In most cases, this will be `near` or `testnet` since you'll want to create sub-accounts of `.testnet` (i.e `benjiman.testnet`). 316 | 317 | ``` 318 | near call YOUR_CONTRACT_ID.testnet new '{"linkdrop_contract": "testnet"}' --accountId YOUR_CONTRACT_ID.testnet 319 | ``` 320 | 321 | You're now ready to create custom linkdrops! You can either interact with the contract directly using the CLI or use one of the pre-deployed scripts. 322 | 323 | ## Using the CLI 324 | After the contract is deployed, you have a couple options for creating linkdrops: 325 | 326 | - Creating single linkdrops. 327 | - Creating multiple linkdrops at a time. 328 | 329 | This will cover creating single linkdrops, however, the only differences between `send` and `send_multiple` are outlined in the [how it works](#how-it-works) flowchart section. 330 | 331 | - Start by creating a keypair locally (you can use near-api-js to do this as seen in the deploy scripts). 332 | - Call the `send` function and pass in the `public_key`, `balance`. If creating a FT, NFT, or FC linkdrop, you must specify the struct as well. This is outlined in the respective sections. 333 | 334 | ```bash 335 | near call YOUR_CONTRACT_ID.testnet send '{"public_key": "ed25519:4iwBf6eAXZ4bcN6TWPikSqu3UJ2HUwF8wNNkGZrgDYqE", "balance": "10000000000000000000000"}' --deposit 1 --accountId "benjiman.testnet" 336 | ``` 337 | 338 | Once the function is successful, you can create the link and click it to claim the linkdrop: 339 | ``` 340 | wallet.testnet.near.org/linkdrop/{YOUR_CONTRACT_ID.testnet}/{privKey1} 341 | ``` 342 | 343 | ## Using the pre-deployed scripts 344 | 345 | If you'd like to use some of the deploy scripts found in the `deploy` folder, those can help automate the process. 346 |
347 | 348 | ### Simple Linkdrops with No NFTs or FTs 349 | 350 | If you'd like to create a simple linkdrop with no pre-loaded NFTs or FTs, first specify the following environment variables: 351 | 352 | ```bash 353 | export LINKDROP_PROXY_CONTRACT_ID="INSERT_HERE" 354 | export FUNDING_ACCOUNT_ID="INSERT_HERE" 355 | export LINKDROP_NEAR_AMOUNT="INSERT_HERE" 356 | export SEND_MULTIPLE="false" 357 | ``` 358 | 359 | This will set the proxy contract that you wish to create linkdrops on, the account ID of the funding address (person creating the linkdrops and sending the funds), the actual $NEAR amount that the linkdrop will contain and whether or not to batch create linkdrops. By default, if the batch option is true, it will create 5 linkdrops. 360 | 361 | It is recommended to simply run a `dev-deploy` and use the dev contract ID to test these scripts. Once this is finished, run the following script: 362 | 363 | ``` 364 | node deploy/simple.js 365 | ``` 366 | 367 | Once the script has finished executing, a link to the wallet should appear in your console similar to: 368 | 369 | ```bash 370 | https://wallet.testnet.near.org/linkdrop/dev-1652794689263-24159113353222/4YULUt1hqv4s96Z8K83VoPnWqXK9vjfYb5QsBrv793aZ2jucBiLP35YWJq9rPGziRpDM35HEUftUtpP1WLzFocqJ 371 | ``` 372 | 373 | Once you've clicked the link, you can either fund an existing account with the linkdrop balance, or you can create a new account and fund it that way. 374 |
375 | 376 | ### Linkdrops with NFTs 377 | 378 | If you'd like to create a linkdrop with a pre-loaded NFT, first specify the following environment variables: 379 | 380 | ```bash 381 | export LINKDROP_PROXY_CONTRACT_ID="INSERT_HERE" 382 | export FUNDING_ACCOUNT_ID="INSERT_HERE" 383 | export LINKDROP_NEAR_AMOUNT="INSERT_HERE" 384 | export SEND_MULTIPLE="false" 385 | ``` 386 | 387 | If you ran the script now, it would mint a predefined NFT on the contract `example-nft.testnet`. If you wish to change the NFT contract or the metadata for the token, simply open the `deploy/nft.js` script and change the following lines: 388 | 389 | ```js 390 | /* 391 | Hard coding NFT contract and metadata. Change this if you want. 392 | */ 393 | let NFT_CONTRACT_ID = "example-nft.testnet"; 394 | const METADATA = { 395 | "title": "Linkdropped Go Team NFT", 396 | "description": "Testing Linkdrop NFT Go Team Token", 397 | "media": "https://bafybeiftczwrtyr3k7a2k4vutd3amkwsmaqyhrdzlhvpt33dyjivufqusq.ipfs.dweb.link/goteam-gif.gif", 398 | "media_hash": null, 399 | "copies": 10000, 400 | "issued_at": null, 401 | "expires_at": null, 402 | "starts_at": null, 403 | "updated_at": null, 404 | "extra": null, 405 | "reference": null, 406 | "reference_hash": null 407 | }; 408 | ``` 409 | 410 | Once you've either changed the NFT info or you're happy with minting a Go Team NFT on the example NFT contract, run the NFT script: 411 | 412 | ``` 413 | node deploy/nft.js 414 | ``` 415 | 416 | Once the script has finished executing, a link to the wallet should appear in your console similar to: 417 | 418 | ```bash 419 | https://wallet.testnet.near.org/linkdrop/dev-1652794689263-24159113353222/4YULUt1hqv4s96Z8K83VoPnWqXK9vjfYb5QsBrv793aZ2jucBiLP35YWJq9rPGziRpDM35HEUftUtpP1WLzFocqJ 420 | ``` 421 | 422 | Once you've clicked the link, you can either fund an existing account with the linkdrop balance, or you can create a new account and fund it that way. When this is finished, navigate to your collectibles tab and you should see an NFT similar to: 423 | 424 |

425 | Logo 426 |
427 |

428 | 429 | ## Linkdrops with FTs 430 | 431 | If you'd like to create a linkdrop with some pre-loaded FTs, you'll need to first specify the following environment variables: 432 | 433 | ```bash 434 | export LINKDROP_PROXY_CONTRACT_ID="INSERT_HERE" 435 | export FUNDING_ACCOUNT_ID="INSERT_HERE" 436 | export LINKDROP_NEAR_AMOUNT="INSERT_HERE" 437 | export SEND_MULTIPLE="false" 438 | ``` 439 | 440 | In addition, you need to specify the FT contract ID you'd like to pre-load the linkdrop with. 441 | 442 | ```bash 443 | export FT_CONTRACT_ID="INSERT_HERE" 444 | ``` 445 | > **NOTE:** the FT script will pay for the proxy contract's storage but the funding account ID must be in possession of at least 25 FTs or else the script will panic. 446 | 447 | Once this is finished, run the FT script. 448 | 449 | ``` 450 | node deploy/ft.js 451 | ``` 452 | 453 | Once the script has finished executing, a link to the wallet should appear in your console similar to: 454 | 455 | ```bash 456 | https://wallet.testnet.near.org/linkdrop/dev-1652794689263-24159113353222/4YULUt1hqv4s96Z8K83VoPnWqXK9vjfYb5QsBrv793aZ2jucBiLP35YWJq9rPGziRpDM35HEUftUtpP1WLzFocqJ 457 | ``` 458 | 459 | Once you've clicked the link, you can either fund an existing account with the linkdrop balance, or you can create a new account and fund it that way. When this is finished, you should see your fungible tokens: 460 | 461 |

462 | Logo 463 |

464 | 465 | ### Linkdrops with Function Calls 466 | 467 | If you'd like to create a linkdrop whereby a function will be called upon claiming, first specify the following environment variables. 468 | 469 | ```bash 470 | export LINKDROP_PROXY_CONTRACT_ID="INSERT_HERE" 471 | export FUNDING_ACCOUNT_ID="INSERT_HERE" 472 | export LINKDROP_NEAR_AMOUNT="INSERT_HERE" 473 | export SEND_MULTIPLE="false" 474 | ``` 475 | 476 | This script will lazy mint an NFT once the linkdrop is claimed. Feel free to edit the logic in the script if you'd like to call a different function. 477 | 478 | ``` 479 | node deploy/function-call.js 480 | ``` 481 | 482 | Once the script has finished executing, a link to the wallet should appear in your console similar to: 483 | 484 | ```bash 485 | https://wallet.testnet.near.org/linkdrop/dev-1652794689263-24159113353222/4YULUt1hqv4s96Z8K83VoPnWqXK9vjfYb5QsBrv793aZ2jucBiLP35YWJq9rPGziRpDM35HEUftUtpP1WLzFocqJ 486 | ``` 487 | 488 | Once you've clicked the link, you can either fund an existing account with the linkdrop balance, or you can create a new account and fund it that way. When this is finished, navigate to your collectibles tab and you should see an NFT similar to: 489 | 490 |

491 | Logo 492 |
493 |

494 | 495 | # Contributing 496 | 497 | First off, thanks for taking the time to contribute! Contributions are what makes the open-source community such an amazing place to learn, inspire, and create. Any contributions you make will benefit everybody else and are **greatly appreciated**. 498 | 499 | Please try to create bug reports that are: 500 | 501 | - _Reproducible._ Include steps to reproduce the problem. 502 | - _Specific._ Include as much detail as possible: which version, what environment, etc. 503 | - _Unique._ Do not duplicate existing opened issues. 504 | - _Scoped to a Single Bug._ One bug per report. 505 | 506 | Please adhere to this project's [code of conduct](docs/CODE_OF_CONDUCT.md). 507 | 508 | You can use [markdownlint-cli](https://github.com/igorshubovych/markdownlint-cli) to check for common markdown style inconsistency. 509 | 510 | # License 511 | 512 | This project is licensed under the **GPL License**. 513 | 514 | # Acknowledgements 515 | 516 | Thanks for these awesome resources that were used during the development of the **Linkdrop Proxy Contract**: 517 | 518 | - 519 | - 520 | - 521 | -------------------------------------------------------------------------------- /contract/src/claim.rs: -------------------------------------------------------------------------------- 1 | use near_sdk::GasWeight; 2 | 3 | use crate::*; 4 | 5 | #[near_bindgen] 6 | impl LinkDropProxy { 7 | /// Claim tokens for specific account that are attached to the public key this tx is signed with. 8 | pub fn claim(&mut self, account_id: AccountId) { 9 | let mut used_gas = env::used_gas(); 10 | let mut prepaid_gas = env::prepaid_gas(); 11 | 12 | env::log_str(&format!("Beginning of regular claim used gas: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 13 | 14 | // Delete the access key and remove / return account data, and optionally callback data. 15 | let key_data = self.process_claim(); 16 | let account_data = key_data.account_data.unwrap(); 17 | 18 | used_gas = env::used_gas(); 19 | prepaid_gas = env::prepaid_gas(); 20 | 21 | env::log_str(&format!("in regular claim right before transfer: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 22 | 23 | // Send the existing account ID the desired linkdrop balance. 24 | Promise::new(account_id.clone()).transfer(account_data.balance.0) 25 | .then( 26 | if let Some(ft_data) = key_data.ft_data { 27 | // Call on_claim_ft with all unspent GAS + min gas for on claim. No attached deposit. 28 | Self::ext(env::current_account_id()) 29 | .with_static_gas(MIN_GAS_FOR_ON_CLAIM) 30 | .on_claim_ft( 31 | // Account ID that claimed the linkdrop 32 | account_id, 33 | // Account ID that funded the linkdrop 34 | account_data.funder_id, 35 | // Balance associated with the linkdrop 36 | account_data.balance, 37 | // How much storage was used to store linkdrop info 38 | account_data.storage_used, 39 | // Did the sender end up sending the FTs to the contract 40 | account_data.cb_data_sent, 41 | // Who sent the FTs? 42 | ft_data.ft_sender, 43 | // Where are the FTs stored 44 | ft_data.ft_contract, 45 | // How many FTs should we send 46 | ft_data.ft_balance, 47 | // How much storage does it cost to register the new account 48 | ft_data.ft_storage.unwrap(), 49 | ) 50 | } else if let Some(nft_data) = key_data.nft_data { 51 | // Call on_claim_nft with all unspent GAS + min gas for on claim. No attached deposit. 52 | Self::ext(env::current_account_id()) 53 | .with_static_gas(MIN_GAS_FOR_ON_CLAIM) 54 | .on_claim_nft( 55 | // Account ID that claimed the linkdrop 56 | account_id, 57 | // Account ID that funded the linkdrop 58 | account_data.funder_id, 59 | // Balance associated with the linkdrop 60 | account_data.balance, 61 | // How much storage was used to store linkdrop info 62 | account_data.storage_used, 63 | // Did the sender end up sending the FTs to the contract 64 | account_data.cb_data_sent, 65 | // Sender of the NFT 66 | nft_data.nft_sender, 67 | // Contract where the NFT is stored 68 | nft_data.nft_contract, 69 | // Token ID for the NFT 70 | nft_data.nft_token_id, 71 | ) 72 | } else if let Some(fc_data) = key_data.fc_data { 73 | // Call on_claim_fc with all unspent GAS + min gas for on claim. No attached deposit. 74 | Self::ext(env::current_account_id()) 75 | .with_static_gas(MIN_GAS_FOR_ON_CLAIM) 76 | .on_claim_fc( 77 | // Account ID that claimed the linkdrop 78 | account_id, 79 | // Account ID that funded the linkdrop 80 | account_data.funder_id, 81 | // Balance associated with the linkdrop 82 | account_data.balance, 83 | // How much storage was used to store linkdrop info 84 | account_data.storage_used, 85 | // Receiver of the function call 86 | fc_data.receiver, 87 | // Method to call on the contract 88 | fc_data.method, 89 | // What args to pass in 90 | fc_data.args, 91 | // What deposit should we attach 92 | fc_data.deposit, 93 | // Should the refund be sent to the funder or attached to the deposit 94 | fc_data.refund_to_deposit, 95 | // Should we add the account ID as part of the args and what key should it live in 96 | fc_data.claimed_account_field, 97 | ) 98 | } else { 99 | // Call on_claim_simple with all unspent GAS + min gas for on claim. No attached deposit. 100 | Self::ext(env::current_account_id()) 101 | .with_static_gas(MIN_GAS_FOR_ON_CLAIM) 102 | .on_claim_simple( 103 | // Account ID that funded the linkdrop 104 | account_data.funder_id, 105 | // Balance associated with the linkdrop 106 | account_data.balance, 107 | // How much storage was used to store linkdrop info 108 | account_data.storage_used, 109 | ) 110 | } 111 | ); 112 | 113 | used_gas = env::used_gas(); 114 | prepaid_gas = env::prepaid_gas(); 115 | 116 | env::log_str(&format!("End of regular claim function: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 117 | 118 | } 119 | 120 | /// Create new account and and claim tokens to it. 121 | pub fn create_account_and_claim( 122 | &mut self, 123 | new_account_id: AccountId, 124 | new_public_key: PublicKey, 125 | ) { 126 | let mut used_gas = env::used_gas(); 127 | let mut prepaid_gas = env::prepaid_gas(); 128 | 129 | env::log_str(&format!("Beginning of CAAC used gas: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 130 | 131 | // Delete the access key and remove / return account data, and optionally callback data. 132 | let key_data = self.process_claim(); 133 | let account_data = key_data.account_data.unwrap(); 134 | 135 | used_gas = env::used_gas(); 136 | prepaid_gas = env::prepaid_gas(); 137 | 138 | env::log_str(&format!("In CAAC after process claim used gas: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 139 | 140 | // CCC to the linkdrop contract to create the account with the desired balance as the linkdrop amount 141 | ext_linkdrop::ext(self.linkdrop_contract.clone()) 142 | // Attach the balance of the linkdrop along with the exact gas for create account. No unspent GAS is attached. 143 | .with_attached_deposit(account_data.balance.0) 144 | .with_static_gas(GAS_FOR_CREATE_ACCOUNT) 145 | .with_unused_gas_weight(0) 146 | .create_account( 147 | new_account_id.clone(), 148 | new_public_key, 149 | ) 150 | .then( 151 | if let Some(ft_data) = key_data.ft_data { 152 | // Call on_claim_ft with all unspent GAS + min gas for on claim. No attached deposit. 153 | Self::ext(env::current_account_id()) 154 | .with_static_gas(MIN_GAS_FOR_ON_CLAIM) 155 | .on_claim_ft( 156 | // Account ID that claimed the linkdrop 157 | new_account_id, 158 | // Account ID that funded the linkdrop 159 | account_data.funder_id, 160 | // Balance associated with the linkdrop 161 | account_data.balance, 162 | // How much storage was used to store linkdrop info 163 | account_data.storage_used, 164 | // Did the sender end up sending the FTs to the contract 165 | account_data.cb_data_sent, 166 | // Who sent the FTs? 167 | ft_data.ft_sender, 168 | // Where are the FTs stored 169 | ft_data.ft_contract, 170 | // How many FTs should we send 171 | ft_data.ft_balance, 172 | // How much storage does it cost to register the new account 173 | ft_data.ft_storage.unwrap(), 174 | ) 175 | } else if let Some(nft_data) = key_data.nft_data { 176 | // Call on_claim_nft with all unspent GAS + min gas for on claim. No attached deposit. 177 | Self::ext(env::current_account_id()) 178 | .with_static_gas(MIN_GAS_FOR_ON_CLAIM) 179 | .on_claim_nft( 180 | // Account ID that claimed the linkdrop 181 | new_account_id, 182 | // Account ID that funded the linkdrop 183 | account_data.funder_id, 184 | // Balance associated with the linkdrop 185 | account_data.balance, 186 | // How much storage was used to store linkdrop info 187 | account_data.storage_used, 188 | // Did the sender end up sending the FTs to the contract 189 | account_data.cb_data_sent, 190 | // Sender of the NFT 191 | nft_data.nft_sender, 192 | // Contract where the NFT is stored 193 | nft_data.nft_contract, 194 | // Token ID for the NFT 195 | nft_data.nft_token_id, 196 | ) 197 | } else if let Some(fc_data) = key_data.fc_data { 198 | // Call on_claim_fc with all unspent GAS + min gas for on claim. No attached deposit. 199 | Self::ext(env::current_account_id()) 200 | .with_static_gas(MIN_GAS_FOR_ON_CLAIM) 201 | .on_claim_fc( 202 | // Account ID that claimed the linkdrop 203 | new_account_id, 204 | // Account ID that funded the linkdrop 205 | account_data.funder_id, 206 | // Balance associated with the linkdrop 207 | account_data.balance, 208 | // How much storage was used to store linkdrop info 209 | account_data.storage_used, 210 | // Receiver of the function call 211 | fc_data.receiver, 212 | // Method to call on the contract 213 | fc_data.method, 214 | // What args to pass in 215 | fc_data.args, 216 | // What deposit should we attach 217 | fc_data.deposit, 218 | // Should the refund be sent to the funder or attached to the deposit 219 | fc_data.refund_to_deposit, 220 | // Should we add the account ID as part of the args and what key should it live in 221 | fc_data.claimed_account_field, 222 | ) 223 | } else { 224 | // Call on_claim_simple with all unspent GAS + min gas for on claim. No attached deposit. 225 | Self::ext(env::current_account_id()) 226 | .with_static_gas(MIN_GAS_FOR_ON_CLAIM) 227 | .on_claim_simple( 228 | // Account ID that funded the linkdrop 229 | account_data.funder_id, 230 | // Balance associated with the linkdrop 231 | account_data.balance, 232 | // How much storage was used to store linkdrop info 233 | account_data.storage_used, 234 | ) 235 | } 236 | ); 237 | 238 | used_gas = env::used_gas(); 239 | prepaid_gas = env::prepaid_gas(); 240 | 241 | env::log_str(&format!("End of on CAAC function: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 242 | 243 | } 244 | 245 | /// Internal method for deleting the used key and removing / returning linkdrop data. 246 | fn process_claim(&mut self) -> KeyInfo { 247 | // Ensure only the current contract is calling the method using the access key 248 | assert_eq!( 249 | env::predecessor_account_id(), 250 | env::current_account_id(), 251 | "predecessor != current" 252 | ); 253 | 254 | // Get the PK of the signer which should be the contract's function call access key 255 | let signer_pk = env::signer_account_pk(); 256 | 257 | // By default, every key should have account data 258 | let account_data = self.data_for_pk 259 | .remove(&signer_pk) 260 | .expect("Key missing"); 261 | 262 | // Remove the key from the set of keys mapped to the funder 263 | self.internal_remove_key_to_funder(&account_data.funder_id, &signer_pk); 264 | 265 | // Delete the key 266 | Promise::new(env::current_account_id()).delete_key(env::signer_account_pk()); 267 | 268 | // Default all callback data to None 269 | let mut key_info = KeyInfo { 270 | pk: None, 271 | account_data: Some(account_data.clone()), 272 | fc_data: None, 273 | nft_data: None, 274 | ft_data: None 275 | }; 276 | 277 | // If there's a Nonce, remove all occurrences of the nonce and return the linkdrop data 278 | if let Some(nonce) = account_data.cb_id { 279 | key_info.ft_data = self.ft.remove(&nonce); 280 | key_info.nft_data = self.nft.remove(&nonce); 281 | key_info.fc_data = self.fc.remove(&nonce); 282 | } 283 | 284 | // Return the key info 285 | key_info 286 | } 287 | 288 | /// self callback for simple linkdrops with no FTs, NFTs, or FCs. 289 | #[private] 290 | pub fn on_claim_simple( 291 | &mut self, 292 | // Account ID that sent the funds for the linkdrop 293 | funder_id: AccountId, 294 | // Balance contained within the linkdrop 295 | balance: U128, 296 | // How much storage was used up for the linkdrop 297 | storage_used: U128, 298 | ) -> bool { 299 | // Get the status of the cross contract call 300 | let claim_succeeded = self.assert_success(); 301 | 302 | let used_gas = env::used_gas(); 303 | let prepaid_gas = env::prepaid_gas(); 304 | 305 | env::log_str(&format!("Simple on claim used gas: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 306 | 307 | // Default amount to refund to be everything except balance and burnt GAS since balance was sent to new account. 308 | let mut amount_to_refund = ACCESS_KEY_ALLOWANCE + ACCESS_KEY_STORAGE + storage_used.0 - BURNT_GAS; 309 | 310 | env::log_str(&format!("Refund Amount: {}, Access Key Allowance: {}, Access Key Storage: {}, Storage Used: {}, Burnt GAS: {}", yocto_to_near(amount_to_refund), yocto_to_near(ACCESS_KEY_ALLOWANCE), yocto_to_near(ACCESS_KEY_STORAGE), yocto_to_near(storage_used.0), yocto_to_near(BURNT_GAS))); 311 | 312 | // If not successful, the balance is added to the amount to refund since it was never transferred. 313 | if !claim_succeeded { 314 | env::log_str(&format!("Claim unsuccessful. Refunding linkdrop balance as well: {}", balance.0)); 315 | amount_to_refund += balance.0 316 | } 317 | 318 | env::log_str(&format!("Refunding funder: {:?} For amount: {:?}", funder_id, yocto_to_near(amount_to_refund))); 319 | // Send the necessary funds to the funder 320 | Promise::new(funder_id.clone()).transfer(amount_to_refund); 321 | 322 | claim_succeeded 323 | } 324 | 325 | /// self callback for FT linkdrop 326 | #[private] 327 | pub fn on_claim_ft( 328 | &mut self, 329 | // Account ID that claimed the linkdrop 330 | account_id: AccountId, 331 | // Account ID that funded the linkdrop 332 | funder_id: AccountId, 333 | // Balance associated with the linkdrop 334 | balance: U128, 335 | // How much storage was used to store linkdrop info 336 | storage_used: U128, 337 | // Did the sender end up sending the FTs to the contract 338 | did_send_fts: bool, 339 | // Who sent the FTs? 340 | ft_sender: AccountId, 341 | // Where are the FTs stored 342 | ft_contract: AccountId, 343 | // How many FTs should we send 344 | ft_balance: U128, 345 | // How much storage does it cost to register the new account 346 | ft_storage: U128, 347 | ) -> bool { 348 | let used_gas = env::used_gas(); 349 | let prepaid_gas = env::prepaid_gas(); 350 | 351 | env::log_str(&format!("Did FTs get sent: {}",did_send_fts)); 352 | env::log_str(&format!("Beginning of on claim FT used gas: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 353 | 354 | // Get the status of the cross contract call 355 | let claim_succeeded = self.assert_success(); 356 | 357 | // Default amount to refund to be everything except balance and burnt GAS since balance was sent to new account. 358 | let mut amount_to_refund = ACCESS_KEY_ALLOWANCE + ACCESS_KEY_STORAGE + storage_used.0 - BURNT_GAS; 359 | 360 | env::log_str(&format!("Refund Amount: {}, Access Key Allowance: {}, Access Key Storage: {}, Storage Used: {}, Burnt GAS: {}", yocto_to_near(amount_to_refund), yocto_to_near(ACCESS_KEY_ALLOWANCE), yocto_to_near(ACCESS_KEY_STORAGE), yocto_to_near(storage_used.0), yocto_to_near(BURNT_GAS))); 361 | 362 | // If not successful, the balance is added to the amount to refund since it was never transferred. 363 | if !claim_succeeded { 364 | env::log_str(&format!("Claim unsuccessful. Refunding linkdrop balance as well: {}", balance.0)); 365 | amount_to_refund += balance.0 366 | } 367 | 368 | env::log_str(&format!("Refunding funder: {:?} For amount: {:?}", funder_id, yocto_to_near(amount_to_refund))); 369 | // Perform the refund for the necessary amount 370 | Promise::new(funder_id.clone()).transfer(amount_to_refund); 371 | 372 | /* 373 | Fungible Tokens. 374 | - Only send the FTs if the sender ended up sending the contract the tokens. 375 | */ 376 | if did_send_fts == true { 377 | // Only send the fungible tokens to the new account if the claim was successful. We return the FTs if it wasn't successful in the else case. 378 | if claim_succeeded { 379 | // Create a new batch promise to pay storage and transfer NFTs to the new account ID 380 | let batch_ft_promise_id = env::promise_batch_create(&ft_contract); 381 | 382 | // Pay the required storage as outlined in the AccountData. This will run first and then we send the fungible tokens 383 | // Call the function with the min GAS and then attach 1/5 of the unspent GAS to the call 384 | env::promise_batch_action_function_call_weight( 385 | batch_ft_promise_id, 386 | "storage_deposit", 387 | json!({ "account_id": account_id }).to_string().as_bytes(), 388 | ft_storage.0, 389 | MIN_GAS_FOR_STORAGE_DEPOSIT, 390 | GasWeight(1) 391 | ); 392 | 393 | // Send the fungible tokens (after the storage deposit is finished since these run sequentially) 394 | // Call the function with the min GAS and then attach 1/5 of the unspent GAS to the call 395 | env::promise_batch_action_function_call_weight( 396 | batch_ft_promise_id, 397 | "ft_transfer", 398 | json!({ "receiver_id": account_id, "amount": ft_balance, "memo": "Linkdropped FT Tokens" }).to_string().as_bytes(), 399 | 1, 400 | MIN_GAS_FOR_FT_TRANSFER, 401 | GasWeight(1) 402 | ); 403 | 404 | // Create the second batch promise to execute after the batch_ft_promise_id batch is finished executing. 405 | // It will execute on the current account ID (this contract) 406 | let batch_ft_resolve_promise_id = env::promise_batch_then(batch_ft_promise_id, &env::current_account_id()); 407 | 408 | // Execute a function call as part of the resolved promise index created in promise_batch_then 409 | // Callback after both the storage was deposited and the fungible tokens were sent 410 | // Call the function with the min GAS and then attach 3/5 of the unspent GAS to the call 411 | env::promise_batch_action_function_call_weight( 412 | batch_ft_resolve_promise_id, 413 | "ft_resolve_batch", 414 | json!({ "amount": ft_balance, "token_sender": ft_sender, "token_contract": ft_contract }).to_string().as_bytes(), 415 | NO_DEPOSIT, 416 | MIN_GAS_FOR_RESOLVE_BATCH, 417 | GasWeight(3) 418 | ); 419 | 420 | } else { 421 | // Create a new batch promise to pay storage and refund the FTs to the original sender 422 | let batch_ft_promise_id = env::promise_batch_create(&ft_contract); 423 | 424 | // Send the fungible tokens (after the storage deposit is finished since these run sequentially) 425 | // Call the function with the min GAS and then attach 1/2 of the unspent GAS to the call 426 | env::promise_batch_action_function_call_weight( 427 | batch_ft_promise_id, 428 | "storage_deposit", 429 | json!({ "account_id": ft_sender }).to_string().as_bytes(), 430 | ft_storage.0, 431 | MIN_GAS_FOR_STORAGE_DEPOSIT, 432 | GasWeight(1) 433 | ); 434 | 435 | // Send the fungible tokens (after the storage deposit is finished since these run sequentially) 436 | // Call the function with the min GAS and then attach 1/2 of the unspent GAS to the call 437 | env::promise_batch_action_function_call_weight( 438 | batch_ft_promise_id, 439 | "ft_transfer", 440 | json!({ "receiver_id": ft_sender, "amount": ft_balance, "memo": "Linkdropped FT Tokens" }).to_string().as_bytes(), 441 | 1, 442 | MIN_GAS_FOR_FT_TRANSFER, 443 | GasWeight(1) 444 | ); 445 | 446 | // Return the result of the batch as the return of the function 447 | env::promise_return(batch_ft_promise_id); 448 | } 449 | } else { 450 | env::log_str("Cannot send FTs since the sender never transferred the contract the tokens."); 451 | } 452 | 453 | claim_succeeded 454 | } 455 | 456 | /// self callback for a linkdrop loaded with an NFT 457 | #[private] 458 | pub fn on_claim_nft(&mut self, 459 | // Account ID that claimed the linkdrop 460 | account_id: AccountId, 461 | // Account ID that funded the linkdrop 462 | funder_id: AccountId, 463 | // Balance associated with the linkdrop 464 | balance: U128, 465 | // How much storage was used to store linkdrop info 466 | storage_used: U128, 467 | // Did the sender end up sending the NFT to the contract 468 | did_send_nft: bool, 469 | // Sender of the NFT 470 | nft_sender: AccountId, 471 | // Contract where the NFT is stored 472 | nft_contract: AccountId, 473 | // Token ID for the NFT 474 | token_id: String, 475 | ) -> bool { 476 | let used_gas = env::used_gas(); 477 | let prepaid_gas = env::prepaid_gas(); 478 | 479 | env::log_str(&format!("Was NFT sent to contract: {}",did_send_nft)); 480 | env::log_str(&format!("Beginning of on claim NFT used gas: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 481 | 482 | // Get the status of the cross contract call 483 | let claim_succeeded = self.assert_success(); 484 | 485 | // Default amount to refund to be everything except balance and burnt GAS since balance was sent to new account. 486 | let mut amount_to_refund = ACCESS_KEY_ALLOWANCE + ACCESS_KEY_STORAGE + storage_used.0 - BURNT_GAS; 487 | 488 | env::log_str(&format!("Refund Amount: {}, Access Key Allowance: {}, Access Key Storage: {}, Storage Used: {}, Burnt GAS: {}", yocto_to_near(amount_to_refund), yocto_to_near(ACCESS_KEY_ALLOWANCE), yocto_to_near(ACCESS_KEY_STORAGE), yocto_to_near(storage_used.0), yocto_to_near(BURNT_GAS))); 489 | 490 | // If not successful, the balance is added to the amount to refund since it was never transferred. 491 | if !claim_succeeded { 492 | env::log_str(&format!("Claim unsuccessful. Refunding linkdrop balance as well: {}", balance.0)); 493 | amount_to_refund += balance.0 494 | } 495 | 496 | env::log_str(&format!("Refunding funder: {:?} For amount: {:?}", funder_id, yocto_to_near(amount_to_refund))); 497 | // Perform the refund for the necessary amount 498 | Promise::new(funder_id.clone()).transfer(amount_to_refund); 499 | 500 | /* 501 | Non Fungible Tokens 502 | */ 503 | if did_send_nft == true { 504 | // Only send the NFT to the new account if the claim was successful. We return the NFT if it wasn't successful in the else case. 505 | if claim_succeeded { 506 | // CCC to the NFT contract to transfer the token to the new account. If this is unsuccessful, we transfer to the original token sender in the callback. 507 | ext_nft_contract::ext(nft_contract.clone()) 508 | // Call nft transfer with the min GAS and 1 yoctoNEAR. 1/2 unspent GAS will be added on top 509 | .with_static_gas(MIN_GAS_FOR_SIMPLE_NFT_TRANSFER) 510 | .with_attached_deposit(1) 511 | .nft_transfer( 512 | account_id.clone(), 513 | token_id.clone(), 514 | None, 515 | Some("Linkdropped NFT".to_string()), 516 | ) 517 | // We then resolve the promise and call nft_resolve_transfer on our own contract 518 | .then( 519 | // Call resolve transfer with the min GAS and no deposit. 1/2 unspent GAS will be added on top 520 | Self::ext(env::current_account_id()) 521 | .with_static_gas(MIN_GAS_FOR_RESOLVE_TRANSFER) 522 | .nft_resolve_transfer( 523 | token_id, 524 | nft_sender, 525 | nft_contract, 526 | ) 527 | ); 528 | } else { 529 | // CCC to the NFT contract to transfer the token to the new account. If this is unsuccessful, we transfer to the original token sender in the callback. 530 | ext_nft_contract::ext(nft_contract) 531 | // Call nft transfer with the min GAS and 1 yoctoNEAR. all unspent GAS will be added on top 532 | .with_static_gas(MIN_GAS_FOR_SIMPLE_NFT_TRANSFER) 533 | .with_attached_deposit(1) 534 | .nft_transfer( 535 | nft_sender, 536 | token_id, 537 | None, 538 | Some("Linkdropped NFT".to_string()), 539 | ); 540 | } 541 | 542 | } else { 543 | env::log_str("Cannot send FTs since the sender never transferred the contract the tokens."); 544 | } 545 | 546 | claim_succeeded 547 | } 548 | 549 | /// self callback checks if account was created successfully or not. If yes, refunds excess storage, sends NFTs, FTs etc.. 550 | #[private] 551 | pub fn on_claim_fc(&mut self, 552 | // Account ID that claimed the linkdrop 553 | account_id: AccountId, 554 | // Account ID that funded the linkdrop 555 | funder_id: AccountId, 556 | // Balance associated with the linkdrop 557 | balance: U128, 558 | // How much storage was used to store linkdrop info 559 | storage_used: U128, 560 | // Receiver of the function call 561 | receiver: AccountId, 562 | // Method to call on the contract 563 | method: String, 564 | // What args to pass in 565 | args: String, 566 | // What deposit should we attach 567 | deposit: U128, 568 | // Should the refund be sent to the funder or attached to the deposit 569 | add_refund_to_deposit: Option, 570 | // Should we add the account ID as part of the args and what key should it live in 571 | claimed_account_field: Option, 572 | ) -> bool { 573 | let used_gas = env::used_gas(); 574 | let prepaid_gas = env::prepaid_gas(); 575 | 576 | env::log_str(&format!("Beginning of on claim Function Call used gas: {:?} prepaid gas: {:?}", used_gas.0 / ONE_GIGGA_GAS, prepaid_gas.0 / ONE_GIGGA_GAS)); 577 | 578 | // Get the status of the cross contract call 579 | let claim_succeeded = self.assert_success(); 580 | 581 | // Default amount to refund to be everything except balance (and FC deposit) and burnt GAS since balance was sent to new account. 582 | let mut amount_to_refund = ACCESS_KEY_ALLOWANCE + ACCESS_KEY_STORAGE + storage_used.0 - BURNT_GAS; 583 | 584 | env::log_str(&format!("Refund Amount: {}, Access Key Allowance: {}, Access Key Storage: {}, Storage Used: {}, Burnt GAS: {}", yocto_to_near(amount_to_refund), yocto_to_near(ACCESS_KEY_ALLOWANCE), yocto_to_near(ACCESS_KEY_STORAGE), yocto_to_near(storage_used.0), yocto_to_near(BURNT_GAS))); 585 | 586 | // If not successful, the balance and deposit is added to the amount to refund since it was never transferred. 587 | if !claim_succeeded { 588 | env::log_str(&format!("Claim unsuccessful. Refunding linkdrop balance: {} and deposit: {}", balance.0, deposit.0)); 589 | amount_to_refund += balance.0 + deposit.0 590 | } 591 | 592 | /* 593 | If the claim is not successful, we should always refund. The only case where we don't refund is 594 | if the claim was successful and the user specified that the refund should go into the 595 | deposit. 596 | 597 | 0 0 Refund !success -> do refund 598 | 0 1 Refund success -> do refund 599 | 1 0 No Refund !success -> do refund 600 | 1 1 No Refund Success -> don't do refund 601 | */ 602 | if !claim_succeeded || (!add_refund_to_deposit.unwrap_or(false) && claim_succeeded) { 603 | // Refunding 604 | env::log_str(&format!("Refunding funder: {:?} For amount: {:?}", funder_id, yocto_to_near(amount_to_refund))); 605 | Promise::new(funder_id.clone()).transfer(amount_to_refund); 606 | } else { 607 | env::log_str(&format!("Skipping the refund to funder: {:?} claim success: {:?} refund to deposit?: {:?}", funder_id, claim_succeeded, add_refund_to_deposit.unwrap_or(false))); 608 | } 609 | 610 | /* 611 | Function Calls 612 | */ 613 | // Only call the function if the claim was successful. 614 | if claim_succeeded { 615 | let mut final_args = args.clone(); 616 | 617 | // Add the account ID that claimed the linkdrop as part of the args to the function call in the key specified by the user 618 | if let Some(account_field) = claimed_account_field { 619 | final_args.insert_str(final_args.len()-1, &format!(",\"{}\":\"{}\"", account_field, account_id)); 620 | env::log_str(&format!("Adding claimed account ID to specified field: {:?} in args: {:?}", account_field, args)); 621 | } 622 | 623 | env::log_str(&format!("Attaching Total: {:?} Deposit: {:?} Should Refund?: {:?} Amount To Refund: {:?} With args: {:?}", yocto_to_near(deposit.0 + if add_refund_to_deposit.unwrap_or(false) {amount_to_refund} else {0}), yocto_to_near(deposit.0), add_refund_to_deposit.unwrap_or(false), yocto_to_near(amount_to_refund), final_args)); 624 | 625 | // Call function with the min GAS and deposit. all unspent GAS will be added on top 626 | Promise::new(receiver).function_call_weight( 627 | method, 628 | final_args.as_bytes().to_vec(), 629 | // The claim is successful so attach the amount to refund to the deposit instead of refunding the funder. 630 | deposit.0 + if add_refund_to_deposit.unwrap_or(false) {amount_to_refund} else {0}, 631 | MIN_GAS_FOR_CALLBACK_FUNCTION_CALL, 632 | GasWeight(1) 633 | ); 634 | } 635 | 636 | claim_succeeded 637 | } 638 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------